View Javadoc
1   /*
2    * Copyright (C) 2017 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.hash;
16  
17  import static com.google.common.base.Preconditions.checkArgument;
18  import static com.google.common.base.Preconditions.checkPositionIndexes;
19  
20  import java.nio.ByteBuffer;
21  import java.nio.charset.Charset;
22  
23  /** 
24   * Skeleton implementation of {@link HashFunction} in terms of {@link #newHasher()}.
25   * 
26   * TODO(lowasser): make public 
27   */
28  abstract class AbstractHashFunction implements HashFunction {
29    @Override
30    public <T> HashCode hashObject(T instance, Funnel<? super T> funnel) {
31      return newHasher().putObject(instance, funnel).hash();
32    }
33  
34    @Override
35    public HashCode hashUnencodedChars(CharSequence input) {
36      int len = input.length();
37      return newHasher(len * 2).putUnencodedChars(input).hash();
38    }
39  
40    @Override
41    public HashCode hashString(CharSequence input, Charset charset) {
42      return newHasher().putString(input, charset).hash();
43    }
44  
45    @Override
46    public HashCode hashInt(int input) {
47      return newHasher(4).putInt(input).hash();
48    }
49  
50    @Override
51    public HashCode hashLong(long input) {
52      return newHasher(8).putLong(input).hash();
53    }
54  
55    @Override
56    public HashCode hashBytes(byte[] input) {
57      return hashBytes(input, 0, input.length);
58    }
59  
60    @Override
61    public HashCode hashBytes(byte[] input, int off, int len) {
62      checkPositionIndexes(off, off + len, input.length);
63      return newHasher(len).putBytes(input, off, len).hash();
64    }
65  
66    @Override
67    public HashCode hashBytes(ByteBuffer input) {
68      return newHasher(input.remaining()).putBytes(input).hash();
69    }
70  
71    @Override
72    public Hasher newHasher(int expectedInputSize) {
73      checkArgument(
74          expectedInputSize >= 0, "expectedInputSize must be >= 0 but was %s", expectedInputSize);
75      return newHasher();
76    }
77  }