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