LongsTest.java revision 7dd252788645e940eada959bdde927426e2531c9
1/*
2 * Copyright (C) 2008 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
17package com.google.common.primitives;
18
19import static java.lang.Long.MAX_VALUE;
20import static java.lang.Long.MIN_VALUE;
21
22import com.google.common.annotations.GwtCompatible;
23import com.google.common.annotations.GwtIncompatible;
24import com.google.common.collect.testing.Helpers;
25import com.google.common.testing.NullPointerTester;
26import com.google.common.testing.SerializableTester;
27
28import java.math.BigInteger;
29import java.util.Arrays;
30import java.util.Collection;
31import java.util.Collections;
32import java.util.Comparator;
33import java.util.List;
34import java.util.Random;
35
36import junit.framework.TestCase;
37
38/**
39 * Unit test for {@link Longs}.
40 *
41 * @author Kevin Bourrillion
42 */
43@GwtCompatible(emulated = true)
44@SuppressWarnings("cast") // redundant casts are intentional and harmless
45public class LongsTest extends TestCase {
46  private static final long[] EMPTY = {};
47  private static final long[] ARRAY1 = {(long) 1};
48  private static final long[] ARRAY234
49      = {(long) 2, (long) 3, (long) 4};
50
51  private static final long[] VALUES =
52      { MIN_VALUE, (long) -1, (long) 0, (long) 1, MAX_VALUE };
53
54  @GwtIncompatible("Long.hashCode returns different values in GWT.")
55  public void testHashCode() {
56    for (long value : VALUES) {
57      assertEquals("hashCode for " + value,
58          ((Long) value).hashCode(), Longs.hashCode(value));
59    }
60  }
61
62  public void testCompare() {
63    for (long x : VALUES) {
64      for (long y : VALUES) {
65        // note: spec requires only that the sign is the same
66        assertEquals(x + ", " + y,
67                     Long.valueOf(x).compareTo(y),
68                     Longs.compare(x, y));
69      }
70    }
71  }
72
73  public void testContains() {
74    assertFalse(Longs.contains(EMPTY, (long) 1));
75    assertFalse(Longs.contains(ARRAY1, (long) 2));
76    assertFalse(Longs.contains(ARRAY234, (long) 1));
77    assertTrue(Longs.contains(new long[] {(long) -1}, (long) -1));
78    assertTrue(Longs.contains(ARRAY234, (long) 2));
79    assertTrue(Longs.contains(ARRAY234, (long) 3));
80    assertTrue(Longs.contains(ARRAY234, (long) 4));
81  }
82
83  public void testIndexOf() {
84    assertEquals(-1, Longs.indexOf(EMPTY, (long) 1));
85    assertEquals(-1, Longs.indexOf(ARRAY1, (long) 2));
86    assertEquals(-1, Longs.indexOf(ARRAY234, (long) 1));
87    assertEquals(0, Longs.indexOf(
88        new long[] {(long) -1}, (long) -1));
89    assertEquals(0, Longs.indexOf(ARRAY234, (long) 2));
90    assertEquals(1, Longs.indexOf(ARRAY234, (long) 3));
91    assertEquals(2, Longs.indexOf(ARRAY234, (long) 4));
92    assertEquals(1, Longs.indexOf(
93        new long[] { (long) 2, (long) 3, (long) 2, (long) 3 },
94        (long) 3));
95  }
96
97  public void testIndexOf_arrayTarget() {
98    assertEquals(0, Longs.indexOf(EMPTY, EMPTY));
99    assertEquals(0, Longs.indexOf(ARRAY234, EMPTY));
100    assertEquals(-1, Longs.indexOf(EMPTY, ARRAY234));
101    assertEquals(-1, Longs.indexOf(ARRAY234, ARRAY1));
102    assertEquals(-1, Longs.indexOf(ARRAY1, ARRAY234));
103    assertEquals(0, Longs.indexOf(ARRAY1, ARRAY1));
104    assertEquals(0, Longs.indexOf(ARRAY234, ARRAY234));
105    assertEquals(0, Longs.indexOf(
106        ARRAY234, new long[] { (long) 2, (long) 3 }));
107    assertEquals(1, Longs.indexOf(
108        ARRAY234, new long[] { (long) 3, (long) 4 }));
109    assertEquals(1, Longs.indexOf(ARRAY234, new long[] { (long) 3 }));
110    assertEquals(2, Longs.indexOf(ARRAY234, new long[] { (long) 4 }));
111    assertEquals(1, Longs.indexOf(new long[] { (long) 2, (long) 3,
112        (long) 3, (long) 3, (long) 3 },
113        new long[] { (long) 3 }
114    ));
115    assertEquals(2, Longs.indexOf(
116        new long[] { (long) 2, (long) 3, (long) 2,
117            (long) 3, (long) 4, (long) 2, (long) 3},
118        new long[] { (long) 2, (long) 3, (long) 4}
119    ));
120    assertEquals(1, Longs.indexOf(
121        new long[] { (long) 2, (long) 2, (long) 3,
122            (long) 4, (long) 2, (long) 3, (long) 4},
123        new long[] { (long) 2, (long) 3, (long) 4}
124    ));
125    assertEquals(-1, Longs.indexOf(
126        new long[] { (long) 4, (long) 3, (long) 2},
127        new long[] { (long) 2, (long) 3, (long) 4}
128    ));
129  }
130
131  public void testLastIndexOf() {
132    assertEquals(-1, Longs.lastIndexOf(EMPTY, (long) 1));
133    assertEquals(-1, Longs.lastIndexOf(ARRAY1, (long) 2));
134    assertEquals(-1, Longs.lastIndexOf(ARRAY234, (long) 1));
135    assertEquals(0, Longs.lastIndexOf(
136        new long[] {(long) -1}, (long) -1));
137    assertEquals(0, Longs.lastIndexOf(ARRAY234, (long) 2));
138    assertEquals(1, Longs.lastIndexOf(ARRAY234, (long) 3));
139    assertEquals(2, Longs.lastIndexOf(ARRAY234, (long) 4));
140    assertEquals(3, Longs.lastIndexOf(
141        new long[] { (long) 2, (long) 3, (long) 2, (long) 3 },
142        (long) 3));
143  }
144
145  public void testMax_noArgs() {
146    try {
147      Longs.max();
148      fail();
149    } catch (IllegalArgumentException expected) {
150    }
151  }
152
153  public void testMax() {
154    assertEquals(MIN_VALUE, Longs.max(MIN_VALUE));
155    assertEquals(MAX_VALUE, Longs.max(MAX_VALUE));
156    assertEquals((long) 9, Longs.max(
157        (long) 8, (long) 6, (long) 7,
158        (long) 5, (long) 3, (long) 0, (long) 9));
159  }
160
161  public void testMin_noArgs() {
162    try {
163      Longs.min();
164      fail();
165    } catch (IllegalArgumentException expected) {
166    }
167  }
168
169  public void testMin() {
170    assertEquals(MIN_VALUE, Longs.min(MIN_VALUE));
171    assertEquals(MAX_VALUE, Longs.min(MAX_VALUE));
172    assertEquals((long) 0, Longs.min(
173        (long) 8, (long) 6, (long) 7,
174        (long) 5, (long) 3, (long) 0, (long) 9));
175  }
176
177  public void testConcat() {
178    assertTrue(Arrays.equals(EMPTY, Longs.concat()));
179    assertTrue(Arrays.equals(EMPTY, Longs.concat(EMPTY)));
180    assertTrue(Arrays.equals(EMPTY, Longs.concat(EMPTY, EMPTY, EMPTY)));
181    assertTrue(Arrays.equals(ARRAY1, Longs.concat(ARRAY1)));
182    assertNotSame(ARRAY1, Longs.concat(ARRAY1));
183    assertTrue(Arrays.equals(ARRAY1, Longs.concat(EMPTY, ARRAY1, EMPTY)));
184    assertTrue(Arrays.equals(
185        new long[] {(long) 1, (long) 1, (long) 1},
186        Longs.concat(ARRAY1, ARRAY1, ARRAY1)));
187    assertTrue(Arrays.equals(
188        new long[] {(long) 1, (long) 2, (long) 3, (long) 4},
189        Longs.concat(ARRAY1, ARRAY234)));
190  }
191
192  private static void assertByteArrayEquals(byte[] expected, byte[] actual) {
193    assertTrue(
194        "Expected: " + Arrays.toString(expected) + ", but got: " + Arrays.toString(actual),
195        Arrays.equals(expected, actual));
196  }
197
198  public void testToByteArray() {
199    assertByteArrayEquals(
200        new byte[] {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19},
201        Longs.toByteArray(0x1213141516171819L));
202    assertByteArrayEquals(
203        new byte[] {
204            (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC,
205            (byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88},
206        Longs.toByteArray(0xFFEEDDCCBBAA9988L));
207  }
208
209  public void testFromByteArray() {
210    assertEquals(0x1213141516171819L, Longs.fromByteArray(
211        new byte[] {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x33}));
212    assertEquals(0xFFEEDDCCBBAA9988L, Longs.fromByteArray(
213        new byte[] {
214            (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC,
215            (byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88}));
216
217    try {
218      Longs.fromByteArray(new byte[Longs.BYTES - 1]);
219      fail();
220    } catch (IllegalArgumentException expected) {
221    }
222  }
223
224  public void testFromBytes() {
225    assertEquals(0x1213141516171819L, Longs.fromBytes(
226        (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15,
227        (byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19));
228    assertEquals(0xFFEEDDCCBBAA9988L, Longs.fromBytes(
229        (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC,
230        (byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88));
231  }
232
233  public void testByteArrayRoundTrips() {
234    Random r = new Random(5);
235    byte[] b = new byte[Longs.BYTES];
236
237    // total overkill, but, it takes 0.1 sec so why not...
238    for (int i = 0; i < 10000; i++) {
239      long num = r.nextLong();
240      assertEquals(num, Longs.fromByteArray(Longs.toByteArray(num)));
241
242      r.nextBytes(b);
243      long value = Longs.fromByteArray(b);
244      assertTrue("" + value, Arrays.equals(b, Longs.toByteArray(value)));
245    }
246  }
247
248  public void testEnsureCapacity() {
249    assertSame(EMPTY, Longs.ensureCapacity(EMPTY, 0, 1));
250    assertSame(ARRAY1, Longs.ensureCapacity(ARRAY1, 0, 1));
251    assertSame(ARRAY1, Longs.ensureCapacity(ARRAY1, 1, 1));
252    assertTrue(Arrays.equals(
253        new long[] {(long) 1, (long) 0, (long) 0},
254        Longs.ensureCapacity(ARRAY1, 2, 1)));
255  }
256
257  public void testEnsureCapacity_fail() {
258    try {
259      Longs.ensureCapacity(ARRAY1, -1, 1);
260      fail();
261    } catch (IllegalArgumentException expected) {
262    }
263    try {
264      // notice that this should even fail when no growth was needed
265      Longs.ensureCapacity(ARRAY1, 1, -1);
266      fail();
267    } catch (IllegalArgumentException expected) {
268    }
269  }
270
271  public void testJoin() {
272    assertEquals("", Longs.join(",", EMPTY));
273    assertEquals("1", Longs.join(",", ARRAY1));
274    assertEquals("1,2", Longs.join(",", (long) 1, (long) 2));
275    assertEquals("123",
276        Longs.join("", (long) 1, (long) 2, (long) 3));
277  }
278
279  public void testLexicographicalComparator() {
280    List<long[]> ordered = Arrays.asList(
281        new long[] {},
282        new long[] {MIN_VALUE},
283        new long[] {MIN_VALUE, MIN_VALUE},
284        new long[] {MIN_VALUE, (long) 1},
285        new long[] {(long) 1},
286        new long[] {(long) 1, MIN_VALUE},
287        new long[] {MAX_VALUE, MAX_VALUE - (long) 1},
288        new long[] {MAX_VALUE, MAX_VALUE},
289        new long[] {MAX_VALUE, MAX_VALUE, MAX_VALUE});
290
291    Comparator<long[]> comparator = Longs.lexicographicalComparator();
292    Helpers.testComparator(comparator, ordered);
293  }
294
295  @GwtIncompatible("SerializableTester")
296  public void testLexicographicalComparatorSerializable() {
297    Comparator<long[]> comparator = Longs.lexicographicalComparator();
298    assertSame(comparator, SerializableTester.reserialize(comparator));
299  }
300
301  public void testToArray() {
302    // need explicit type parameter to avoid javac warning!?
303    List<Long> none = Arrays.<Long>asList();
304    assertTrue(Arrays.equals(EMPTY, Longs.toArray(none)));
305
306    List<Long> one = Arrays.asList((long) 1);
307    assertTrue(Arrays.equals(ARRAY1, Longs.toArray(one)));
308
309    long[] array = {(long) 0, (long) 1, 0x0FF1C1AL};
310
311    List<Long> three = Arrays.asList((long) 0, (long) 1, 0x0FF1C1AL);
312    assertTrue(Arrays.equals(array, Longs.toArray(three)));
313
314    assertTrue(Arrays.equals(array, Longs.toArray(Longs.asList(array))));
315  }
316
317  public void testToArray_threadSafe() {
318    for (int delta : new int[] { +1, 0, -1 }) {
319      for (int i = 0; i < VALUES.length; i++) {
320        List<Long> list = Longs.asList(VALUES).subList(0, i);
321        Collection<Long> misleadingSize =
322            Helpers.misleadingSizeCollection(delta);
323        misleadingSize.addAll(list);
324        long[] arr = Longs.toArray(misleadingSize);
325        assertEquals(i, arr.length);
326        for (int j = 0; j < i; j++) {
327          assertEquals(VALUES[j], arr[j]);
328        }
329      }
330    }
331  }
332
333  public void testToArray_withNull() {
334    List<Long> list = Arrays.asList((long) 0, (long) 1, null);
335    try {
336      Longs.toArray(list);
337      fail();
338    } catch (NullPointerException expected) {
339    }
340  }
341
342  public void testToArray_withConversion() {
343    long[] array = {(long) 0, (long) 1, (long) 2};
344
345    List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2);
346    List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2);
347    List<Integer> ints = Arrays.asList(0, 1, 2);
348    List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2);
349    List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
350    List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
351
352    assertTrue(Arrays.equals(array, Longs.toArray(bytes)));
353    assertTrue(Arrays.equals(array, Longs.toArray(shorts)));
354    assertTrue(Arrays.equals(array, Longs.toArray(ints)));
355    assertTrue(Arrays.equals(array, Longs.toArray(floats)));
356    assertTrue(Arrays.equals(array, Longs.toArray(longs)));
357    assertTrue(Arrays.equals(array, Longs.toArray(doubles)));
358  }
359
360  public void testAsList_isAView() {
361    long[] array = {(long) 0, (long) 1};
362    List<Long> list = Longs.asList(array);
363    list.set(0, (long) 2);
364    assertTrue(Arrays.equals(new long[] {(long) 2, (long) 1}, array));
365    array[1] = (long) 3;
366    assertEquals(Arrays.asList((long) 2, (long) 3), list);
367  }
368
369  public void testAsList_toArray_roundTrip() {
370    long[] array = { (long) 0, (long) 1, (long) 2 };
371    List<Long> list = Longs.asList(array);
372    long[] newArray = Longs.toArray(list);
373
374    // Make sure it returned a copy
375    list.set(0, (long) 4);
376    assertTrue(Arrays.equals(
377        new long[] { (long) 0, (long) 1, (long) 2 }, newArray));
378    newArray[1] = (long) 5;
379    assertEquals((long) 1, (long) list.get(1));
380  }
381
382  // This test stems from a real bug found by andrewk
383  public void testAsList_subList_toArray_roundTrip() {
384    long[] array = { (long) 0, (long) 1, (long) 2, (long) 3 };
385    List<Long> list = Longs.asList(array);
386    assertTrue(Arrays.equals(new long[] { (long) 1, (long) 2 },
387        Longs.toArray(list.subList(1, 3))));
388    assertTrue(Arrays.equals(new long[] {},
389        Longs.toArray(list.subList(2, 2))));
390  }
391
392  public void testAsListEmpty() {
393    assertSame(Collections.emptyList(), Longs.asList(EMPTY));
394  }
395
396  @GwtIncompatible("NullPointerTester")
397  public void testNulls() {
398    new NullPointerTester().testAllPublicStaticMethods(Longs.class);
399  }
400
401  @GwtIncompatible("AndroidInteger")
402  public void testTryParse() {
403    tryParseAndAssertEquals(0L, "0");
404    tryParseAndAssertEquals(0L, "-0");
405    tryParseAndAssertEquals(1L, "1");
406    tryParseAndAssertEquals(-1L, "-1");
407    tryParseAndAssertEquals(8900L, "8900");
408    tryParseAndAssertEquals(-8900L, "-8900");
409    tryParseAndAssertEquals(MAX_VALUE, Long.toString(MAX_VALUE));
410    tryParseAndAssertEquals(MIN_VALUE, Long.toString(MIN_VALUE));
411    assertNull(Longs.tryParse(""));
412    assertNull(Longs.tryParse("-"));
413    assertNull(Longs.tryParse("+1"));
414    assertNull(Longs.tryParse("999999999999999999999999"));
415    assertNull("Max integer + 1",
416        Longs.tryParse(BigInteger.valueOf(MAX_VALUE).add(BigInteger.ONE).toString()));
417    assertNull("Min integer - 1",
418        Longs.tryParse(BigInteger.valueOf(MIN_VALUE).subtract(BigInteger.ONE).toString()));
419  }
420
421  /**
422   * Applies {@link Longs#tryParse(String)} to the given string and asserts that
423   * the result is as expected.
424   */
425  private static void tryParseAndAssertEquals(Long expected, String value) {
426    assertEquals(expected, Longs.tryParse(value));
427  }
428}
429