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