001    /*
002     * Copyright (C) 2008 Google Inc.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.primitives;
018    
019    import static com.google.common.base.Preconditions.checkArgument;
020    import static com.google.common.base.Preconditions.checkElementIndex;
021    import static com.google.common.base.Preconditions.checkNotNull;
022    import static com.google.common.base.Preconditions.checkPositionIndexes;
023    
024    import com.google.common.annotations.GwtCompatible;
025    import com.google.common.annotations.GwtIncompatible;
026    
027    import java.io.Serializable;
028    import java.util.AbstractList;
029    import java.util.Arrays;
030    import java.util.Collection;
031    import java.util.Collections;
032    import java.util.Comparator;
033    import java.util.List;
034    import java.util.RandomAccess;
035    
036    /**
037     * Static utility methods pertaining to {@code int} primitives, that are not
038     * already found in either {@link Integer} or {@link Arrays}.
039     *
040     * @author Kevin Bourrillion
041     * @since 1
042     */
043    @GwtCompatible(emulated = true)
044    public final class Ints {
045      private Ints() {}
046    
047      /**
048       * The number of bytes required to represent a primitive {@code int}
049       * value.
050       */
051      public static final int BYTES = Integer.SIZE / Byte.SIZE;
052    
053      /**
054       * Returns a hash code for {@code value}; equal to the result of invoking
055       * {@code ((Integer) value).hashCode()}.
056       *
057       * @param value a primitive {@code int} value
058       * @return a hash code for the value
059       */
060      public static int hashCode(int value) {
061        return value;
062      }
063    
064      /**
065       * Returns the {@code int} value that is equal to {@code value}, if possible.
066       *
067       * @param value any value in the range of the {@code int} type
068       * @return the {@code int} value that equals {@code value}
069       * @throws IllegalArgumentException if {@code value} is greater than {@link
070       *     Integer#MAX_VALUE} or less than {@link Integer#MIN_VALUE}
071       */
072      public static int checkedCast(long value) {
073        int result = (int) value;
074        checkArgument(result == value, "Out of range: %s", value);
075        return result;
076      }
077    
078      /**
079       * Returns the {@code int} nearest in value to {@code value}.
080       *
081       * @param value any {@code long} value
082       * @return the same value cast to {@code int} if it is in the range of the
083       *     {@code int} type, {@link Integer#MAX_VALUE} if it is too large,
084       *     or {@link Integer#MIN_VALUE} if it is too small
085       */
086      public static int saturatedCast(long value) {
087        if (value > Integer.MAX_VALUE) {
088          return Integer.MAX_VALUE;
089        }
090        if (value < Integer.MIN_VALUE) {
091          return Integer.MIN_VALUE;
092        }
093        return (int) value;
094      }
095    
096      /**
097       * Compares the two specified {@code int} values. The sign of the value
098       * returned is the same as that of {@code ((Integer) a).compareTo(b)}.
099       *
100       * @param a the first {@code int} to compare
101       * @param b the second {@code int} to compare
102       * @return a negative value if {@code a} is less than {@code b}; a positive
103       *     value if {@code a} is greater than {@code b}; or zero if they are equal
104       */
105      public static int compare(int a, int b) {
106        return (a < b) ? -1 : ((a > b) ? 1 : 0);
107      }
108    
109      /**
110       * Returns {@code true} if {@code target} is present as an element anywhere in
111       * {@code array}.
112       *
113       * @param array an array of {@code int} values, possibly empty
114       * @param target a primitive {@code int} value
115       * @return {@code true} if {@code array[i] == target} for some value of {@code
116       *     i}
117       */
118      public static boolean contains(int[] array, int target) {
119        for (int value : array) {
120          if (value == target) {
121            return true;
122          }
123        }
124        return false;
125      }
126    
127      /**
128       * Returns the index of the first appearance of the value {@code target} in
129       * {@code array}.
130       *
131       * @param array an array of {@code int} values, possibly empty
132       * @param target a primitive {@code int} value
133       * @return the least index {@code i} for which {@code array[i] == target}, or
134       *     {@code -1} if no such index exists.
135       */
136      public static int indexOf(int[] array, int target) {
137        return indexOf(array, target, 0, array.length);
138      }
139    
140      // TODO(kevinb): consider making this public
141      private static int indexOf(
142          int[] array, int target, int start, int end) {
143        for (int i = start; i < end; i++) {
144          if (array[i] == target) {
145            return i;
146          }
147        }
148        return -1;
149      }
150    
151      /**
152       * Returns the start position of the first occurrence of the specified {@code
153       * target} within {@code array}, or {@code -1} if there is no such occurrence.
154       *
155       * <p>More formally, returns the lowest index {@code i} such that {@code
156       * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
157       * the same elements as {@code target}.
158       *
159       * @param array the array to search for the sequence {@code target}
160       * @param target the array to search for as a sub-sequence of {@code array}
161       */
162      public static int indexOf(int[] array, int[] target) {
163        checkNotNull(array, "array");
164        checkNotNull(target, "target");
165        if (target.length == 0) {
166          return 0;
167        }
168    
169        outer:
170        for (int i = 0; i < array.length - target.length + 1; i++) {
171          for (int j = 0; j < target.length; j++) {
172            if (array[i + j] != target[j]) {
173              continue outer;
174            }
175          }
176          return i;
177        }
178        return -1;
179      }
180    
181      /**
182       * Returns the index of the last appearance of the value {@code target} in
183       * {@code array}.
184       *
185       * @param array an array of {@code int} values, possibly empty
186       * @param target a primitive {@code int} value
187       * @return the greatest index {@code i} for which {@code array[i] == target},
188       *     or {@code -1} if no such index exists.
189       */
190      public static int lastIndexOf(int[] array, int target) {
191        return lastIndexOf(array, target, 0, array.length);
192      }
193    
194      // TODO(kevinb): consider making this public
195      private static int lastIndexOf(
196          int[] array, int target, int start, int end) {
197        for (int i = end - 1; i >= start; i--) {
198          if (array[i] == target) {
199            return i;
200          }
201        }
202        return -1;
203      }
204    
205      /**
206       * Returns the least value present in {@code array}.
207       *
208       * @param array a <i>nonempty</i> array of {@code int} values
209       * @return the value present in {@code array} that is less than or equal to
210       *     every other value in the array
211       * @throws IllegalArgumentException if {@code array} is empty
212       */
213      public static int min(int... array) {
214        checkArgument(array.length > 0);
215        int min = array[0];
216        for (int i = 1; i < array.length; i++) {
217          if (array[i] < min) {
218            min = array[i];
219          }
220        }
221        return min;
222      }
223    
224      /**
225       * Returns the greatest value present in {@code array}.
226       *
227       * @param array a <i>nonempty</i> array of {@code int} values
228       * @return the value present in {@code array} that is greater than or equal to
229       *     every other value in the array
230       * @throws IllegalArgumentException if {@code array} is empty
231       */
232      public static int max(int... array) {
233        checkArgument(array.length > 0);
234        int max = array[0];
235        for (int i = 1; i < array.length; i++) {
236          if (array[i] > max) {
237            max = array[i];
238          }
239        }
240        return max;
241      }
242    
243      /**
244       * Returns the values from each provided array combined into a single array.
245       * For example, {@code concat(new int[] {a, b}, new int[] {}, new
246       * int[] {c}} returns the array {@code {a, b, c}}.
247       *
248       * @param arrays zero or more {@code int} arrays
249       * @return a single array containing all the values from the source arrays, in
250       *     order
251       */
252      public static int[] concat(int[]... arrays) {
253        int length = 0;
254        for (int[] array : arrays) {
255          length += array.length;
256        }
257        int[] result = new int[length];
258        int pos = 0;
259        for (int[] array : arrays) {
260          System.arraycopy(array, 0, result, pos, array.length);
261          pos += array.length;
262        }
263        return result;
264      }
265    
266      /**
267       * Returns a big-endian representation of {@code value} in a 4-element byte
268       * array; equivalent to {@code ByteBuffer.allocate(4).putInt(value).array()}.
269       * For example, the input value {@code 0x12131415} would yield the byte array
270       * {@code {0x12, 0x13, 0x14, 0x15}}.
271       *
272       * <p>If you need to convert and concatenate several values (possibly even of
273       * different types), use a shared {@link java.nio.ByteBuffer} instance, or use
274       * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable
275       * buffer.
276       */
277      @GwtIncompatible("doesn't work")
278      public static byte[] toByteArray(int value) {
279        return new byte[] {
280            (byte) (value >> 24),
281            (byte) (value >> 16),
282            (byte) (value >> 8),
283            (byte) value};
284      }
285    
286      /**
287       * Returns the {@code int} value whose big-endian representation is stored in
288       * the first 4 bytes of {@code bytes}; equivalent to {@code
289       * ByteBuffer.wrap(bytes).getInt()}. For example, the input byte array {@code
290       * {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value {@code
291       * 0x12131415}.
292       *
293       * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
294       * library exposes much more flexibility at little cost in readability.
295       *
296       * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements
297       */
298      @GwtIncompatible("doesn't work")
299      public static int fromByteArray(byte[] bytes) {
300        checkArgument(bytes.length >= BYTES,
301            "array too small: %s < %s", bytes.length, BYTES);
302        return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]);
303      }
304    
305      /**
306       * Returns the {@code int} value whose byte representation is the given 4
307       * bytes, in big-endian order; equivalent to {@code Ints.fromByteArray(new
308       * byte[] {b1, b2, b3, b4})}.
309       *
310       * @since 7
311       */
312      @GwtIncompatible("doesn't work")
313      public static int fromBytes(byte b1, byte b2, byte b3, byte b4) {
314        return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF);
315      }
316    
317      /**
318       * Returns an array containing the same values as {@code array}, but
319       * guaranteed to be of a specified minimum length. If {@code array} already
320       * has a length of at least {@code minLength}, it is returned directly.
321       * Otherwise, a new array of size {@code minLength + padding} is returned,
322       * containing the values of {@code array}, and zeroes in the remaining places.
323       *
324       * @param array the source array
325       * @param minLength the minimum length the returned array must guarantee
326       * @param padding an extra amount to "grow" the array by if growth is
327       *     necessary
328       * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
329       *     negative
330       * @return an array containing the values of {@code array}, with guaranteed
331       *     minimum length {@code minLength}
332       */
333      public static int[] ensureCapacity(
334          int[] array, int minLength, int padding) {
335        checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
336        checkArgument(padding >= 0, "Invalid padding: %s", padding);
337        return (array.length < minLength)
338            ? copyOf(array, minLength + padding)
339            : array;
340      }
341    
342      // Arrays.copyOf() requires Java 6
343      private static int[] copyOf(int[] original, int length) {
344        int[] copy = new int[length];
345        System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
346        return copy;
347      }
348    
349      /**
350       * Returns a string containing the supplied {@code int} values separated
351       * by {@code separator}. For example, {@code join("-", 1, 2, 3)} returns
352       * the string {@code "1-2-3"}.
353       *
354       * @param separator the text that should appear between consecutive values in
355       *     the resulting string (but not at the start or end)
356       * @param array an array of {@code int} values, possibly empty
357       */
358      public static String join(String separator, int... array) {
359        checkNotNull(separator);
360        if (array.length == 0) {
361          return "";
362        }
363    
364        // For pre-sizing a builder, just get the right order of magnitude
365        StringBuilder builder = new StringBuilder(array.length * 5);
366        builder.append(array[0]);
367        for (int i = 1; i < array.length; i++) {
368          builder.append(separator).append(array[i]);
369        }
370        return builder.toString();
371      }
372    
373      /**
374       * Returns a comparator that compares two {@code int} arrays
375       * lexicographically. That is, it compares, using {@link
376       * #compare(int, int)}), the first pair of values that follow any
377       * common prefix, or when one array is a prefix of the other, treats the
378       * shorter array as the lesser. For example, {@code [] < [1] < [1, 2] < [2]}.
379       *
380       * <p>The returned comparator is inconsistent with {@link
381       * Object#equals(Object)} (since arrays support only identity equality), but
382       * it is consistent with {@link Arrays#equals(int[], int[])}.
383       *
384       * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
385       *     Lexicographical order article at Wikipedia</a>
386       * @since 2
387       */
388      public static Comparator<int[]> lexicographicalComparator() {
389        return LexicographicalComparator.INSTANCE;
390      }
391    
392      private enum LexicographicalComparator implements Comparator<int[]> {
393        INSTANCE;
394    
395        public int compare(int[] left, int[] right) {
396          int minLength = Math.min(left.length, right.length);
397          for (int i = 0; i < minLength; i++) {
398            int result = Ints.compare(left[i], right[i]);
399            if (result != 0) {
400              return result;
401            }
402          }
403          return left.length - right.length;
404        }
405      }
406    
407      /**
408       * Copies a collection of {@code Integer} instances into a new array of
409       * primitive {@code int} values.
410       *
411       * <p>Elements are copied from the argument collection as if by {@code
412       * collection.toArray()}.  Calling this method is as thread-safe as calling
413       * that method.
414       *
415       * @param collection a collection of {@code Integer} objects
416       * @return an array containing the same values as {@code collection}, in the
417       *     same order, converted to primitives
418       * @throws NullPointerException if {@code collection} or any of its elements
419       *     is null
420       */
421      public static int[] toArray(Collection<Integer> collection) {
422        if (collection instanceof IntArrayAsList) {
423          return ((IntArrayAsList) collection).toIntArray();
424        }
425    
426        Object[] boxedArray = collection.toArray();
427        int len = boxedArray.length;
428        int[] array = new int[len];
429        for (int i = 0; i < len; i++) {
430          array[i] = (Integer) boxedArray[i];
431        }
432        return array;
433      }
434    
435      /**
436       * Returns a fixed-size list backed by the specified array, similar to {@link
437       * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
438       * but any attempt to set a value to {@code null} will result in a {@link
439       * NullPointerException}.
440       *
441       * <p>The returned list maintains the values, but not the identities, of
442       * {@code Integer} objects written to or read from it.  For example, whether
443       * {@code list.get(0) == list.get(0)} is true for the returned list is
444       * unspecified.
445       *
446       * @param backingArray the array to back the list
447       * @return a list view of the array
448       */
449      public static List<Integer> asList(int... backingArray) {
450        if (backingArray.length == 0) {
451          return Collections.emptyList();
452        }
453        return new IntArrayAsList(backingArray);
454      }
455    
456      @GwtCompatible
457      private static class IntArrayAsList extends AbstractList<Integer>
458          implements RandomAccess, Serializable {
459        final int[] array;
460        final int start;
461        final int end;
462    
463        IntArrayAsList(int[] array) {
464          this(array, 0, array.length);
465        }
466    
467        IntArrayAsList(int[] array, int start, int end) {
468          this.array = array;
469          this.start = start;
470          this.end = end;
471        }
472    
473        @Override public int size() {
474          return end - start;
475        }
476    
477        @Override public boolean isEmpty() {
478          return false;
479        }
480    
481        @Override public Integer get(int index) {
482          checkElementIndex(index, size());
483          return array[start + index];
484        }
485    
486        @Override public boolean contains(Object target) {
487          // Overridden to prevent a ton of boxing
488          return (target instanceof Integer)
489              && Ints.indexOf(array, (Integer) target, start, end) != -1;
490        }
491    
492        @Override public int indexOf(Object target) {
493          // Overridden to prevent a ton of boxing
494          if (target instanceof Integer) {
495            int i = Ints.indexOf(array, (Integer) target, start, end);
496            if (i >= 0) {
497              return i - start;
498            }
499          }
500          return -1;
501        }
502    
503        @Override public int lastIndexOf(Object target) {
504          // Overridden to prevent a ton of boxing
505          if (target instanceof Integer) {
506            int i = Ints.lastIndexOf(array, (Integer) target, start, end);
507            if (i >= 0) {
508              return i - start;
509            }
510          }
511          return -1;
512        }
513    
514        @Override public Integer set(int index, Integer element) {
515          checkElementIndex(index, size());
516          int oldValue = array[start + index];
517          array[start + index] = element;
518          return oldValue;
519        }
520    
521        @Override public List<Integer> subList(int fromIndex, int toIndex) {
522          int size = size();
523          checkPositionIndexes(fromIndex, toIndex, size);
524          if (fromIndex == toIndex) {
525            return Collections.emptyList();
526          }
527          return new IntArrayAsList(array, start + fromIndex, start + toIndex);
528        }
529    
530        @Override public boolean equals(Object object) {
531          if (object == this) {
532            return true;
533          }
534          if (object instanceof IntArrayAsList) {
535            IntArrayAsList that = (IntArrayAsList) object;
536            int size = size();
537            if (that.size() != size) {
538              return false;
539            }
540            for (int i = 0; i < size; i++) {
541              if (array[start + i] != that.array[that.start + i]) {
542                return false;
543              }
544            }
545            return true;
546          }
547          return super.equals(object);
548        }
549    
550        @Override public int hashCode() {
551          int result = 1;
552          for (int i = start; i < end; i++) {
553            result = 31 * result + Ints.hashCode(array[i]);
554          }
555          return result;
556        }
557    
558        @Override public String toString() {
559          StringBuilder builder = new StringBuilder(size() * 5);
560          builder.append('[').append(array[start]);
561          for (int i = start + 1; i < end; i++) {
562            builder.append(", ").append(array[i]);
563          }
564          return builder.append(']').toString();
565        }
566    
567        int[] toIntArray() {
568          // Arrays.copyOfRange() requires Java 6
569          int size = size();
570          int[] result = new int[size];
571          System.arraycopy(array, start, result, 0, size);
572          return result;
573        }
574    
575        private static final long serialVersionUID = 0;
576      }
577    }