001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.primitives;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkElementIndex;
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkPositionIndexes;
021import static java.lang.Math.min;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.errorprone.annotations.InlineMe;
025import java.io.Serializable;
026import java.util.AbstractList;
027import java.util.Arrays;
028import java.util.Collection;
029import java.util.Collections;
030import java.util.Comparator;
031import java.util.List;
032import java.util.RandomAccess;
033import org.checkerframework.checker.nullness.qual.Nullable;
034
035/**
036 * Static utility methods pertaining to {@code boolean} primitives, that are not already found in
037 * either {@link Boolean} or {@link Arrays}.
038 *
039 * <p>See the Guava User Guide article on <a
040 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
041 *
042 * @author Kevin Bourrillion
043 * @since 1.0
044 */
045@GwtCompatible
046public final class Booleans {
047  private Booleans() {}
048
049  /** Comparators for {@code Boolean} values. */
050  private enum BooleanComparator implements Comparator<Boolean> {
051    TRUE_FIRST(1, "Booleans.trueFirst()"),
052    FALSE_FIRST(-1, "Booleans.falseFirst()");
053
054    private final int trueValue;
055    private final String toString;
056
057    BooleanComparator(int trueValue, String toString) {
058      this.trueValue = trueValue;
059      this.toString = toString;
060    }
061
062    @Override
063    public int compare(Boolean a, Boolean b) {
064      int aVal = a ? trueValue : 0;
065      int bVal = b ? trueValue : 0;
066      return bVal - aVal;
067    }
068
069    @Override
070    public String toString() {
071      return toString;
072    }
073  }
074
075  /**
076   * Returns a {@code Comparator<Boolean>} that sorts {@code true} before {@code false}.
077   *
078   * <p>This is particularly useful in Java 8+ in combination with {@code Comparator.comparing},
079   * e.g. {@code Comparator.comparing(Foo::hasBar, trueFirst())}.
080   *
081   * @since 21.0
082   */
083  public static Comparator<Boolean> trueFirst() {
084    return BooleanComparator.TRUE_FIRST;
085  }
086
087  /**
088   * Returns a {@code Comparator<Boolean>} that sorts {@code false} before {@code true}.
089   *
090   * <p>This is particularly useful in Java 8+ in combination with {@code Comparator.comparing},
091   * e.g. {@code Comparator.comparing(Foo::hasBar, falseFirst())}.
092   *
093   * @since 21.0
094   */
095  public static Comparator<Boolean> falseFirst() {
096    return BooleanComparator.FALSE_FIRST;
097  }
098
099  /**
100   * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Boolean)
101   * value).hashCode()}.
102   *
103   * <p><b>Java 8+ users:</b> use {@link Boolean#hashCode(boolean)} instead.
104   *
105   * @param value a primitive {@code boolean} value
106   * @return a hash code for the value
107   */
108  public static int hashCode(boolean value) {
109    return value ? 1231 : 1237;
110  }
111
112  /**
113   * Compares the two specified {@code boolean} values in the standard way ({@code false} is
114   * considered less than {@code true}). The sign of the value returned is the same as that of
115   * {@code ((Boolean) a).compareTo(b)}.
116   *
117   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the
118   * equivalent {@link Boolean#compare} method instead.
119   *
120   * @param a the first {@code boolean} to compare
121   * @param b the second {@code boolean} to compare
122   * @return a positive number if only {@code a} is {@code true}, a negative number if only {@code
123   *     b} is true, or zero if {@code a == b}
124   */
125  @InlineMe(replacement = "Boolean.compare(a, b)")
126  public static int compare(boolean a, boolean b) {
127    return Boolean.compare(a, b);
128  }
129
130  /**
131   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
132   *
133   * <p><b>Note:</b> consider representing the array as a {@link java.util.BitSet} instead,
134   * replacing {@code Booleans.contains(array, true)} with {@code !bitSet.isEmpty()} and {@code
135   * Booleans.contains(array, false)} with {@code bitSet.nextClearBit(0) == sizeOfBitSet}.
136   *
137   * @param array an array of {@code boolean} values, possibly empty
138   * @param target a primitive {@code boolean} value
139   * @return {@code true} if {@code array[i] == target} for some value of {@code i}
140   */
141  public static boolean contains(boolean[] array, boolean target) {
142    for (boolean value : array) {
143      if (value == target) {
144        return true;
145      }
146    }
147    return false;
148  }
149
150  /**
151   * Returns the index of the first appearance of the value {@code target} in {@code array}.
152   *
153   * <p><b>Note:</b> consider representing the array as a {@link java.util.BitSet} instead, and
154   * using {@link java.util.BitSet#nextSetBit(int)} or {@link java.util.BitSet#nextClearBit(int)}.
155   *
156   * @param array an array of {@code boolean} values, possibly empty
157   * @param target a primitive {@code boolean} value
158   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
159   *     such index exists.
160   */
161  public static int indexOf(boolean[] array, boolean target) {
162    return indexOf(array, target, 0, array.length);
163  }
164
165  // TODO(kevinb): consider making this public
166  private static int indexOf(boolean[] array, boolean target, int start, int end) {
167    for (int i = start; i < end; i++) {
168      if (array[i] == target) {
169        return i;
170      }
171    }
172    return -1;
173  }
174
175  /**
176   * Returns the start position of the first occurrence of the specified {@code target} within
177   * {@code array}, or {@code -1} if there is no such occurrence.
178   *
179   * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array,
180   * i, i + target.length)} contains exactly the same elements as {@code target}.
181   *
182   * @param array the array to search for the sequence {@code target}
183   * @param target the array to search for as a sub-sequence of {@code array}
184   */
185  public static int indexOf(boolean[] array, boolean[] target) {
186    checkNotNull(array, "array");
187    checkNotNull(target, "target");
188    if (target.length == 0) {
189      return 0;
190    }
191
192    outer:
193    for (int i = 0; i < array.length - target.length + 1; i++) {
194      for (int j = 0; j < target.length; j++) {
195        if (array[i + j] != target[j]) {
196          continue outer;
197        }
198      }
199      return i;
200    }
201    return -1;
202  }
203
204  /**
205   * Returns the index of the last appearance of the value {@code target} in {@code array}.
206   *
207   * @param array an array of {@code boolean} values, possibly empty
208   * @param target a primitive {@code boolean} value
209   * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
210   *     such index exists.
211   */
212  public static int lastIndexOf(boolean[] array, boolean target) {
213    return lastIndexOf(array, target, 0, array.length);
214  }
215
216  // TODO(kevinb): consider making this public
217  private static int lastIndexOf(boolean[] array, boolean target, int start, int end) {
218    for (int i = end - 1; i >= start; i--) {
219      if (array[i] == target) {
220        return i;
221      }
222    }
223    return -1;
224  }
225
226  /**
227   * Returns the values from each provided array combined into a single array. For example, {@code
228   * concat(new boolean[] {a, b}, new boolean[] {}, new boolean[] {c}} returns the array {@code {a,
229   * b, c}}.
230   *
231   * @param arrays zero or more {@code boolean} arrays
232   * @return a single array containing all the values from the source arrays, in order
233   * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit
234   *     in an {@code int}
235   */
236  public static boolean[] concat(boolean[]... arrays) {
237    long length = 0;
238    for (boolean[] array : arrays) {
239      length += array.length;
240    }
241    boolean[] result = new boolean[checkNoOverflow(length)];
242    int pos = 0;
243    for (boolean[] array : arrays) {
244      System.arraycopy(array, 0, result, pos, array.length);
245      pos += array.length;
246    }
247    return result;
248  }
249
250  private static int checkNoOverflow(long result) {
251    checkArgument(
252        result == (int) result,
253        "the total number of elements (%s) in the arrays must fit in an int",
254        result);
255    return (int) result;
256  }
257
258  /**
259   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
260   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
261   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
262   * returned, containing the values of {@code array}, and zeroes in the remaining places.
263   *
264   * @param array the source array
265   * @param minLength the minimum length the returned array must guarantee
266   * @param padding an extra amount to "grow" the array by if growth is necessary
267   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
268   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
269   *     minLength}
270   */
271  public static boolean[] ensureCapacity(boolean[] array, int minLength, int padding) {
272    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
273    checkArgument(padding >= 0, "Invalid padding: %s", padding);
274    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
275  }
276
277  /**
278   * Returns a string containing the supplied {@code boolean} values separated by {@code separator}.
279   * For example, {@code join("-", false, true, false)} returns the string {@code
280   * "false-true-false"}.
281   *
282   * @param separator the text that should appear between consecutive values in the resulting string
283   *     (but not at the start or end)
284   * @param array an array of {@code boolean} values, possibly empty
285   */
286  public static String join(String separator, boolean... array) {
287    checkNotNull(separator);
288    if (array.length == 0) {
289      return "";
290    }
291
292    // For pre-sizing a builder, just get the right order of magnitude
293    StringBuilder builder = new StringBuilder(array.length * 7);
294    builder.append(array[0]);
295    for (int i = 1; i < array.length; i++) {
296      builder.append(separator).append(array[i]);
297    }
298    return builder.toString();
299  }
300
301  /**
302   * Returns a comparator that compares two {@code boolean} arrays <a
303   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
304   * compares, using {@link #compare(boolean, boolean)}), the first pair of values that follow any
305   * common prefix, or when one array is a prefix of the other, treats the shorter array as the
306   * lesser. For example, {@code [] < [false] < [false, true] < [true]}.
307   *
308   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
309   * support only identity equality), but it is consistent with {@link Arrays#equals(boolean[],
310   * boolean[])}.
311   *
312   * @since 2.0
313   */
314  public static Comparator<boolean[]> lexicographicalComparator() {
315    return LexicographicalComparator.INSTANCE;
316  }
317
318  private enum LexicographicalComparator implements Comparator<boolean[]> {
319    INSTANCE;
320
321    @Override
322    public int compare(boolean[] left, boolean[] right) {
323      int minLength = min(left.length, right.length);
324      for (int i = 0; i < minLength; i++) {
325        int result = Boolean.compare(left[i], right[i]);
326        if (result != 0) {
327          return result;
328        }
329      }
330      return left.length - right.length;
331    }
332
333    @Override
334    public String toString() {
335      return "Booleans.lexicographicalComparator()";
336    }
337  }
338
339  /**
340   * Copies a collection of {@code Boolean} instances into a new array of primitive {@code boolean}
341   * values.
342   *
343   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
344   * Calling this method is as thread-safe as calling that method.
345   *
346   * <p><b>Note:</b> consider representing the collection as a {@link java.util.BitSet} instead.
347   *
348   * @param collection a collection of {@code Boolean} objects
349   * @return an array containing the same values as {@code collection}, in the same order, converted
350   *     to primitives
351   * @throws NullPointerException if {@code collection} or any of its elements is null
352   */
353  public static boolean[] toArray(Collection<Boolean> collection) {
354    if (collection instanceof BooleanArrayAsList) {
355      return ((BooleanArrayAsList) collection).toBooleanArray();
356    }
357
358    Object[] boxedArray = collection.toArray();
359    int len = boxedArray.length;
360    boolean[] array = new boolean[len];
361    for (int i = 0; i < len; i++) {
362      // checkNotNull for GWT (do not optimize)
363      array[i] = (Boolean) checkNotNull(boxedArray[i]);
364    }
365    return array;
366  }
367
368  /**
369   * Returns a fixed-size list backed by the specified array, similar to {@link
370   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
371   * set a value to {@code null} will result in a {@link NullPointerException}.
372   *
373   * <p>There are at most two distinct objects in this list, {@code (Boolean) true} and {@code
374   * (Boolean) false}. Java guarantees that those are always represented by the same objects.
375   *
376   * <p>The returned list is serializable.
377   *
378   * @param backingArray the array to back the list
379   * @return a list view of the array
380   */
381  public static List<Boolean> asList(boolean... backingArray) {
382    if (backingArray.length == 0) {
383      return Collections.emptyList();
384    }
385    return new BooleanArrayAsList(backingArray);
386  }
387
388  @GwtCompatible
389  private static class BooleanArrayAsList extends AbstractList<Boolean>
390      implements RandomAccess, Serializable {
391    final boolean[] array;
392    final int start;
393    final int end;
394
395    BooleanArrayAsList(boolean[] array) {
396      this(array, 0, array.length);
397    }
398
399    BooleanArrayAsList(boolean[] array, int start, int end) {
400      this.array = array;
401      this.start = start;
402      this.end = end;
403    }
404
405    @Override
406    public int size() {
407      return end - start;
408    }
409
410    @Override
411    public boolean isEmpty() {
412      return false;
413    }
414
415    @Override
416    public Boolean get(int index) {
417      checkElementIndex(index, size());
418      return array[start + index];
419    }
420
421    @Override
422    public boolean contains(@Nullable Object target) {
423      // Overridden to prevent a ton of boxing
424      return (target instanceof Boolean)
425          && Booleans.indexOf(array, (Boolean) target, start, end) != -1;
426    }
427
428    @Override
429    public int indexOf(@Nullable Object target) {
430      // Overridden to prevent a ton of boxing
431      if (target instanceof Boolean) {
432        int i = Booleans.indexOf(array, (Boolean) target, start, end);
433        if (i >= 0) {
434          return i - start;
435        }
436      }
437      return -1;
438    }
439
440    @Override
441    public int lastIndexOf(@Nullable Object target) {
442      // Overridden to prevent a ton of boxing
443      if (target instanceof Boolean) {
444        int i = Booleans.lastIndexOf(array, (Boolean) target, start, end);
445        if (i >= 0) {
446          return i - start;
447        }
448      }
449      return -1;
450    }
451
452    @Override
453    public Boolean set(int index, Boolean element) {
454      checkElementIndex(index, size());
455      boolean oldValue = array[start + index];
456      // checkNotNull for GWT (do not optimize)
457      array[start + index] = checkNotNull(element);
458      return oldValue;
459    }
460
461    @Override
462    public List<Boolean> subList(int fromIndex, int toIndex) {
463      int size = size();
464      checkPositionIndexes(fromIndex, toIndex, size);
465      if (fromIndex == toIndex) {
466        return Collections.emptyList();
467      }
468      return new BooleanArrayAsList(array, start + fromIndex, start + toIndex);
469    }
470
471    @Override
472    public boolean equals(@Nullable Object object) {
473      if (object == this) {
474        return true;
475      }
476      if (object instanceof BooleanArrayAsList) {
477        BooleanArrayAsList that = (BooleanArrayAsList) object;
478        int size = size();
479        if (that.size() != size) {
480          return false;
481        }
482        for (int i = 0; i < size; i++) {
483          if (array[start + i] != that.array[that.start + i]) {
484            return false;
485          }
486        }
487        return true;
488      }
489      return super.equals(object);
490    }
491
492    @Override
493    public int hashCode() {
494      int result = 1;
495      for (int i = start; i < end; i++) {
496        result = 31 * result + Booleans.hashCode(array[i]);
497      }
498      return result;
499    }
500
501    @Override
502    public String toString() {
503      StringBuilder builder = new StringBuilder(size() * 7);
504      builder.append(array[start] ? "[true" : "[false");
505      for (int i = start + 1; i < end; i++) {
506        builder.append(array[i] ? ", true" : ", false");
507      }
508      return builder.append(']').toString();
509    }
510
511    boolean[] toBooleanArray() {
512      return Arrays.copyOfRange(array, start, end);
513    }
514
515    private static final long serialVersionUID = 0;
516  }
517
518  /**
519   * Returns the number of {@code values} that are {@code true}.
520   *
521   * @since 16.0
522   */
523  public static int countTrue(boolean... values) {
524    int count = 0;
525    for (boolean value : values) {
526      if (value) {
527        count++;
528      }
529    }
530    return count;
531  }
532
533  /**
534   * Reverses the elements of {@code array}. This is equivalent to {@code
535   * Collections.reverse(Booleans.asList(array))}, but is likely to be more efficient.
536   *
537   * @since 23.1
538   */
539  public static void reverse(boolean[] array) {
540    checkNotNull(array);
541    reverse(array, 0, array.length);
542  }
543
544  /**
545   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
546   * exclusive. This is equivalent to {@code
547   * Collections.reverse(Booleans.asList(array).subList(fromIndex, toIndex))}, but is likely to be
548   * more efficient.
549   *
550   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
551   *     {@code toIndex > fromIndex}
552   * @since 23.1
553   */
554  public static void reverse(boolean[] array, int fromIndex, int toIndex) {
555    checkNotNull(array);
556    checkPositionIndexes(fromIndex, toIndex, array.length);
557    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
558      boolean tmp = array[i];
559      array[i] = array[j];
560      array[j] = tmp;
561    }
562  }
563
564  /**
565   * Performs a right rotation of {@code array} of "distance" places, so that the first element is
566   * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
567   * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Booleans.asList(array),
568   * distance)}, but is somewhat faster.
569   *
570   * <p>The provided "distance" may be negative, which will rotate left.
571   *
572   * @since 32.0.0
573   */
574  public static void rotate(boolean[] array, int distance) {
575    rotate(array, distance, 0, array.length);
576  }
577
578  /**
579   * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
580   * toIndex} exclusive. This is equivalent to {@code
581   * Collections.rotate(Booleans.asList(array).subList(fromIndex, toIndex), distance)}, but is
582   * somewhat faster.
583   *
584   * <p>The provided "distance" may be negative, which will rotate left.
585   *
586   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
587   *     {@code toIndex > fromIndex}
588   * @since 32.0.0
589   */
590  public static void rotate(boolean[] array, int distance, int fromIndex, int toIndex) {
591    // See Ints.rotate for more details about possible algorithms here.
592    checkNotNull(array);
593    checkPositionIndexes(fromIndex, toIndex, array.length);
594    if (array.length <= 1) {
595      return;
596    }
597
598    int length = toIndex - fromIndex;
599    // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
600    // places left to rotate.
601    int m = -distance % length;
602    m = (m < 0) ? m + length : m;
603    // The current index of what will become the first element of the rotated section.
604    int newFirstIndex = m + fromIndex;
605    if (newFirstIndex == fromIndex) {
606      return;
607    }
608
609    reverse(array, fromIndex, newFirstIndex);
610    reverse(array, newFirstIndex, toIndex);
611    reverse(array, fromIndex, toIndex);
612  }
613}