• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.hash;
18 
19 import static com.google.common.base.Charsets.UTF_16LE;
20 
21 import com.google.common.collect.Iterables;
22 import com.google.common.collect.Lists;
23 import com.google.common.hash.HashTestUtils.RandomHasherAction;
24 import java.io.ByteArrayOutputStream;
25 import java.nio.ByteBuffer;
26 import java.nio.ByteOrder;
27 import java.util.Arrays;
28 import java.util.Collections;
29 import java.util.List;
30 import java.util.Random;
31 import junit.framework.TestCase;
32 
33 /**
34  * Tests for AbstractStreamingHasher.
35  *
36  * @author Dimitris Andreou
37  */
38 public class AbstractStreamingHasherTest extends TestCase {
testBytes()39   public void testBytes() {
40     Sink sink = new Sink(4); // byte order insignificant here
41     byte[] expected = {1, 2, 3, 4, 5, 6, 7, 8};
42     sink.putByte((byte) 1);
43     sink.putBytes(new byte[] {2, 3, 4, 5, 6});
44     sink.putByte((byte) 7);
45     sink.putBytes(new byte[] {});
46     sink.putBytes(new byte[] {8});
47     HashCode unused = sink.hash();
48     sink.assertInvariants(8);
49     sink.assertBytes(expected);
50   }
51 
testShort()52   public void testShort() {
53     Sink sink = new Sink(4);
54     sink.putShort((short) 0x0201);
55     HashCode unused = sink.hash();
56     sink.assertInvariants(2);
57     sink.assertBytes(new byte[] {1, 2, 0, 0}); // padded with zeros
58   }
59 
testInt()60   public void testInt() {
61     Sink sink = new Sink(4);
62     sink.putInt(0x04030201);
63     HashCode unused = sink.hash();
64     sink.assertInvariants(4);
65     sink.assertBytes(new byte[] {1, 2, 3, 4});
66   }
67 
testLong()68   public void testLong() {
69     Sink sink = new Sink(8);
70     sink.putLong(0x0807060504030201L);
71     HashCode unused = sink.hash();
72     sink.assertInvariants(8);
73     sink.assertBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
74   }
75 
testChar()76   public void testChar() {
77     Sink sink = new Sink(4);
78     sink.putChar((char) 0x0201);
79     HashCode unused = sink.hash();
80     sink.assertInvariants(2);
81     sink.assertBytes(new byte[] {1, 2, 0, 0}); // padded with zeros
82   }
83 
testString()84   public void testString() {
85     Random random = new Random();
86     for (int i = 0; i < 100; i++) {
87       byte[] bytes = new byte[64];
88       random.nextBytes(bytes);
89       String s = new String(bytes, UTF_16LE); // so all random strings are valid
90       assertEquals(
91           new Sink(4).putUnencodedChars(s).hash(),
92           new Sink(4).putBytes(s.getBytes(UTF_16LE)).hash());
93       assertEquals(
94           new Sink(4).putUnencodedChars(s).hash(), new Sink(4).putString(s, UTF_16LE).hash());
95     }
96   }
97 
testFloat()98   public void testFloat() {
99     Sink sink = new Sink(4);
100     sink.putFloat(Float.intBitsToFloat(0x04030201));
101     HashCode unused = sink.hash();
102     sink.assertInvariants(4);
103     sink.assertBytes(new byte[] {1, 2, 3, 4});
104   }
105 
testDouble()106   public void testDouble() {
107     Sink sink = new Sink(8);
108     sink.putDouble(Double.longBitsToDouble(0x0807060504030201L));
109     HashCode unused = sink.hash();
110     sink.assertInvariants(8);
111     sink.assertBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
112   }
113 
testCorrectExceptions()114   public void testCorrectExceptions() {
115     Sink sink = new Sink(4);
116     try {
117       sink.putBytes(new byte[8], -1, 4);
118       fail();
119     } catch (IndexOutOfBoundsException ok) {
120     }
121     try {
122       sink.putBytes(new byte[8], 0, 16);
123       fail();
124     } catch (IndexOutOfBoundsException ok) {
125     }
126     try {
127       sink.putBytes(new byte[8], 0, -1);
128       fail();
129     } catch (IndexOutOfBoundsException ok) {
130     }
131   }
132 
133   /**
134    * This test creates a long random sequence of inputs, then a lot of differently configured sinks
135    * process it; all should produce the same answer, the only difference should be the number of
136    * process()/processRemaining() invocations, due to alignment.
137    */
138   @AndroidIncompatible // slow. TODO(cpovirk): Maybe just reduce iterations under Android.
testExhaustive()139   public void testExhaustive() throws Exception {
140     Random random = new Random(0); // will iteratively make more debuggable, each time it breaks
141     for (int totalInsertions = 0; totalInsertions < 200; totalInsertions++) {
142 
143       List<Sink> sinks = Lists.newArrayList();
144       for (int chunkSize = 4; chunkSize <= 32; chunkSize++) {
145         for (int bufferSize = chunkSize; bufferSize <= chunkSize * 4; bufferSize += chunkSize) {
146           // yes, that's a lot of sinks!
147           sinks.add(new Sink(chunkSize, bufferSize));
148           // For convenience, testing only with big endianness, to match DataOutputStream.
149           // I regard highly unlikely that both the little endianness tests above and this one
150           // passes, and there is still a little endianness bug lurking around.
151         }
152       }
153 
154       Control control = new Control();
155       Hasher controlSink = control.newHasher(1024);
156 
157       Iterable<Hasher> sinksAndControl =
158           Iterables.concat(sinks, Collections.singleton(controlSink));
159       for (int insertion = 0; insertion < totalInsertions; insertion++) {
160         RandomHasherAction.pickAtRandom(random).performAction(random, sinksAndControl);
161       }
162       // We need to ensure that at least 4 bytes have been put into the hasher or else
163       // Hasher#hash will throw an ISE.
164       int intToPut = random.nextInt();
165       for (Hasher hasher : sinksAndControl) {
166         hasher.putInt(intToPut);
167       }
168       for (Sink sink : sinks) {
169         HashCode unused = sink.hash();
170       }
171 
172       byte[] expected = controlSink.hash().asBytes();
173       for (Sink sink : sinks) {
174         sink.assertInvariants(expected.length);
175         sink.assertBytes(expected);
176       }
177     }
178   }
179 
180   private static class Sink extends AbstractStreamingHasher {
181     final int chunkSize;
182     final int bufferSize;
183     final ByteArrayOutputStream out = new ByteArrayOutputStream();
184 
185     int processCalled = 0;
186     boolean remainingCalled = false;
187 
Sink(int chunkSize, int bufferSize)188     Sink(int chunkSize, int bufferSize) {
189       super(chunkSize, bufferSize);
190       this.chunkSize = chunkSize;
191       this.bufferSize = bufferSize;
192     }
193 
Sink(int chunkSize)194     Sink(int chunkSize) {
195       super(chunkSize);
196       this.chunkSize = chunkSize;
197       this.bufferSize = chunkSize;
198     }
199 
200     @Override
makeHash()201     protected HashCode makeHash() {
202       return HashCode.fromBytes(out.toByteArray());
203     }
204 
205     @Override
process(ByteBuffer bb)206     protected void process(ByteBuffer bb) {
207       processCalled++;
208       assertEquals(ByteOrder.LITTLE_ENDIAN, bb.order());
209       assertTrue(bb.remaining() >= chunkSize);
210       for (int i = 0; i < chunkSize; i++) {
211         out.write(bb.get());
212       }
213     }
214 
215     @Override
processRemaining(ByteBuffer bb)216     protected void processRemaining(ByteBuffer bb) {
217       assertFalse(remainingCalled);
218       remainingCalled = true;
219       assertEquals(ByteOrder.LITTLE_ENDIAN, bb.order());
220       assertTrue(bb.remaining() > 0);
221       assertTrue(bb.remaining() < bufferSize);
222       int before = processCalled;
223       super.processRemaining(bb);
224       int after = processCalled;
225       assertEquals(before + 1, after); // default implementation pads and calls process()
226       processCalled--; // don't count the tail invocation (makes tests a bit more understandable)
227     }
228 
229     // ensures that the number of invocations looks sane
230     void assertInvariants(int expectedBytes) {
231       // we should have seen as many bytes as the next multiple of chunk after expectedBytes - 1
232       assertEquals(out.toByteArray().length, ceilToMultiple(expectedBytes, chunkSize));
233       assertEquals(expectedBytes / chunkSize, processCalled);
234       assertEquals(expectedBytes % chunkSize != 0, remainingCalled);
235     }
236 
237     // returns the minimum x such as x >= a && (x % b) == 0
238     private static int ceilToMultiple(int a, int b) {
239       int remainder = a % b;
240       return remainder == 0 ? a : a + b - remainder;
241     }
242 
243     void assertBytes(byte[] expected) {
244       byte[] got = out.toByteArray();
245       for (int i = 0; i < expected.length; i++) {
246         assertEquals(expected[i], got[i]);
247       }
248     }
249   }
250 
251   // Assumes that AbstractNonStreamingHashFunction works properly (must be tested elsewhere!)
252   private static class Control extends AbstractNonStreamingHashFunction {
253     @Override
254     public HashCode hashBytes(byte[] input, int off, int len) {
255       return HashCode.fromBytes(Arrays.copyOfRange(input, off, off + len));
256     }
257 
258     @Override
259     public int bits() {
260       throw new UnsupportedOperationException();
261     }
262   }
263 }
264