001/*
002 * Copyright (C) 2008 The Guava Authors
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
017package com.google.common.primitives;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkElementIndex;
021import static com.google.common.base.Preconditions.checkNotNull;
022import static com.google.common.base.Preconditions.checkPositionIndexes;
023
024import com.google.common.annotations.Beta;
025import com.google.common.annotations.GwtCompatible;
026
027import java.io.Serializable;
028import java.util.AbstractList;
029import java.util.Arrays;
030import java.util.BitSet;
031import java.util.Collection;
032import java.util.Collections;
033import java.util.Comparator;
034import java.util.List;
035import java.util.RandomAccess;
036
037/**
038 * Static utility methods pertaining to {@code boolean} primitives, that are not
039 * already found in either {@link Boolean} or {@link Arrays}.
040 *
041 * <p>See the Guava User Guide article on <a href=
042 * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
043 * primitive utilities</a>.
044 *
045 * @author Kevin Bourrillion
046 * @since 1.0
047 */
048@GwtCompatible
049public final class Booleans {
050  private Booleans() {}
051
052  /**
053   * Returns a hash code for {@code value}; equal to the result of invoking
054   * {@code ((Boolean) value).hashCode()}.
055   *
056   * @param value a primitive {@code boolean} value
057   * @return a hash code for the value
058   */
059  public static int hashCode(boolean value) {
060    return value ? 1231 : 1237;
061  }
062
063  /**
064   * Compares the two specified {@code boolean} values in the standard way
065   * ({@code false} is considered less than {@code true}). The sign of the
066   * value returned is the same as that of {@code ((Boolean) a).compareTo(b)}.
067   *
068   * <p><b>Note:</b> projects using JDK 7 or later should use the equivalent
069   * {@link Boolean#compare} method instead.
070   *
071   * @param a the first {@code boolean} to compare
072   * @param b the second {@code boolean} to compare
073   * @return a positive number if only {@code a} is {@code true}, a negative
074   *     number if only {@code b} is true, or zero if {@code a == b}
075   */
076  // TODO(kevinb): if JDK 6 ever becomes a non-concern, remove this
077  public static int compare(boolean a, boolean b) {
078    return (a == b) ? 0 : (a ? 1 : -1);
079  }
080
081  /**
082   * Returns {@code true} if {@code target} is present as an element anywhere in
083   * {@code array}.
084   *
085   * <p><b>Note:</b> consider representing the array as a {@link
086   * BitSet} instead, replacing {@code Booleans.contains(array, true)}
087   * with {@code !bitSet.isEmpty()} and {@code Booleans.contains(array, false)}
088   * with {@code bitSet.nextClearBit(0) == sizeOfBitSet}.
089   *
090   * @param array an array of {@code boolean} values, possibly empty
091   * @param target a primitive {@code boolean} value
092   * @return {@code true} if {@code array[i] == target} for some value of {@code
093   *     i}
094   */
095  public static boolean contains(boolean[] array, boolean target) {
096    for (boolean value : array) {
097      if (value == target) {
098        return true;
099      }
100    }
101    return false;
102  }
103
104  /**
105   * Returns the index of the first appearance of the value {@code target} in
106   * {@code array}.
107   *
108   * <p><b>Note:</b> consider representing the array as a {@link BitSet}
109   * instead, and using {@link BitSet#nextSetBit(int)} or {@link
110   * BitSet#nextClearBit(int)}.
111   *
112   * @param array an array of {@code boolean} values, possibly empty
113   * @param target a primitive {@code boolean} value
114   * @return the least index {@code i} for which {@code array[i] == target}, or
115   *     {@code -1} if no such index exists.
116   */
117  public static int indexOf(boolean[] array, boolean target) {
118    return indexOf(array, target, 0, array.length);
119  }
120
121  // TODO(kevinb): consider making this public
122  private static int indexOf(
123      boolean[] array, boolean target, int start, int end) {
124    for (int i = start; i < end; i++) {
125      if (array[i] == target) {
126        return i;
127      }
128    }
129    return -1;
130  }
131
132  /**
133   * Returns the start position of the first occurrence of the specified {@code
134   * target} within {@code array}, or {@code -1} if there is no such occurrence.
135   *
136   * <p>More formally, returns the lowest index {@code i} such that {@code
137   * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
138   * the same elements as {@code target}.
139   *
140   * @param array the array to search for the sequence {@code target}
141   * @param target the array to search for as a sub-sequence of {@code array}
142   */
143  public static int indexOf(boolean[] array, boolean[] target) {
144    checkNotNull(array, "array");
145    checkNotNull(target, "target");
146    if (target.length == 0) {
147      return 0;
148    }
149
150    outer:
151    for (int i = 0; i < array.length - target.length + 1; i++) {
152      for (int j = 0; j < target.length; j++) {
153        if (array[i + j] != target[j]) {
154          continue outer;
155        }
156      }
157      return i;
158    }
159    return -1;
160  }
161
162  /**
163   * Returns the index of the last appearance of the value {@code target} in
164   * {@code array}.
165   *
166   * @param array an array of {@code boolean} values, possibly empty
167   * @param target a primitive {@code boolean} value
168   * @return the greatest index {@code i} for which {@code array[i] == target},
169   *     or {@code -1} if no such index exists.
170   */
171  public static int lastIndexOf(boolean[] array, boolean target) {
172    return lastIndexOf(array, target, 0, array.length);
173  }
174
175  // TODO(kevinb): consider making this public
176  private static int lastIndexOf(
177      boolean[] array, boolean target, int start, int end) {
178    for (int i = end - 1; i >= start; i--) {
179      if (array[i] == target) {
180        return i;
181      }
182    }
183    return -1;
184  }
185
186  /**
187   * Returns the values from each provided array combined into a single array.
188   * For example, {@code concat(new boolean[] {a, b}, new boolean[] {}, new
189   * boolean[] {c}} returns the array {@code {a, b, c}}.
190   *
191   * @param arrays zero or more {@code boolean} arrays
192   * @return a single array containing all the values from the source arrays, in
193   *     order
194   */
195  public static boolean[] concat(boolean[]... arrays) {
196    int length = 0;
197    for (boolean[] array : arrays) {
198      length += array.length;
199    }
200    boolean[] result = new boolean[length];
201    int pos = 0;
202    for (boolean[] array : arrays) {
203      System.arraycopy(array, 0, result, pos, array.length);
204      pos += array.length;
205    }
206    return result;
207  }
208
209  /**
210   * Returns an array containing the same values as {@code array}, but
211   * guaranteed to be of a specified minimum length. If {@code array} already
212   * has a length of at least {@code minLength}, it is returned directly.
213   * Otherwise, a new array of size {@code minLength + padding} is returned,
214   * containing the values of {@code array}, and zeroes in the remaining places.
215   *
216   * @param array the source array
217   * @param minLength the minimum length the returned array must guarantee
218   * @param padding an extra amount to "grow" the array by if growth is
219   *     necessary
220   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
221   *     negative
222   * @return an array containing the values of {@code array}, with guaranteed
223   *     minimum length {@code minLength}
224   */
225  public static boolean[] ensureCapacity(
226      boolean[] array, int minLength, int padding) {
227    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
228    checkArgument(padding >= 0, "Invalid padding: %s", padding);
229    return (array.length < minLength)
230        ? copyOf(array, minLength + padding)
231        : array;
232  }
233
234  // Arrays.copyOf() requires Java 6
235  private static boolean[] copyOf(boolean[] original, int length) {
236    boolean[] copy = new boolean[length];
237    System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
238    return copy;
239  }
240
241  /**
242   * Returns a string containing the supplied {@code boolean} values separated
243   * by {@code separator}. For example, {@code join("-", false, true, false)}
244   * returns the string {@code "false-true-false"}.
245   *
246   * @param separator the text that should appear between consecutive values in
247   *     the resulting string (but not at the start or end)
248   * @param array an array of {@code boolean} values, possibly empty
249   */
250  public static String join(String separator, boolean... array) {
251    checkNotNull(separator);
252    if (array.length == 0) {
253      return "";
254    }
255
256    // For pre-sizing a builder, just get the right order of magnitude
257    StringBuilder builder = new StringBuilder(array.length * 7);
258    builder.append(array[0]);
259    for (int i = 1; i < array.length; i++) {
260      builder.append(separator).append(array[i]);
261    }
262    return builder.toString();
263  }
264
265  /**
266   * Returns a comparator that compares two {@code boolean} arrays
267   * lexicographically. That is, it compares, using {@link
268   * #compare(boolean, boolean)}), the first pair of values that follow any
269   * common prefix, or when one array is a prefix of the other, treats the
270   * shorter array as the lesser. For example,
271   * {@code [] < [false] < [false, true] < [true]}.
272   *
273   * <p>The returned comparator is inconsistent with {@link
274   * Object#equals(Object)} (since arrays support only identity equality), but
275   * it is consistent with {@link Arrays#equals(boolean[], boolean[])}.
276   *
277   * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
278   *     Lexicographical order article at Wikipedia</a>
279   * @since 2.0
280   */
281  public static Comparator<boolean[]> lexicographicalComparator() {
282    return LexicographicalComparator.INSTANCE;
283  }
284
285  private enum LexicographicalComparator implements Comparator<boolean[]> {
286    INSTANCE;
287
288    @Override
289    public int compare(boolean[] left, boolean[] right) {
290      int minLength = Math.min(left.length, right.length);
291      for (int i = 0; i < minLength; i++) {
292        int result = Booleans.compare(left[i], right[i]);
293        if (result != 0) {
294          return result;
295        }
296      }
297      return left.length - right.length;
298    }
299  }
300
301  /**
302   * Copies a collection of {@code Boolean} instances into a new array of
303   * primitive {@code boolean} values.
304   *
305   * <p>Elements are copied from the argument collection as if by {@code
306   * collection.toArray()}.  Calling this method is as thread-safe as calling
307   * that method.
308   *
309   * <p><b>Note:</b> consider representing the collection as a {@link
310   * BitSet} instead.
311   *
312   * @param collection a collection of {@code Boolean} objects
313   * @return an array containing the same values as {@code collection}, in the
314   *     same order, converted to primitives
315   * @throws NullPointerException if {@code collection} or any of its elements
316   *     is null
317   */
318  public static boolean[] toArray(Collection<Boolean> collection) {
319    if (collection instanceof BooleanArrayAsList) {
320      return ((BooleanArrayAsList) collection).toBooleanArray();
321    }
322
323    Object[] boxedArray = collection.toArray();
324    int len = boxedArray.length;
325    boolean[] array = new boolean[len];
326    for (int i = 0; i < len; i++) {
327      // checkNotNull for GWT (do not optimize)
328      array[i] = (Boolean) checkNotNull(boxedArray[i]);
329    }
330    return array;
331  }
332
333  /**
334   * Returns a fixed-size list backed by the specified array, similar to {@link
335   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
336   * but any attempt to set a value to {@code null} will result in a {@link
337   * NullPointerException}.
338   *
339   * <p>The returned list maintains the values, but not the identities, of
340   * {@code Boolean} objects written to or read from it.  For example, whether
341   * {@code list.get(0) == list.get(0)} is true for the returned list is
342   * unspecified.
343   *
344   * @param backingArray the array to back the list
345   * @return a list view of the array
346   */
347  public static List<Boolean> asList(boolean... backingArray) {
348    if (backingArray.length == 0) {
349      return Collections.emptyList();
350    }
351    return new BooleanArrayAsList(backingArray);
352  }
353
354  @GwtCompatible
355  private static class BooleanArrayAsList extends AbstractList<Boolean>
356      implements RandomAccess, Serializable {
357    final boolean[] array;
358    final int start;
359    final int end;
360
361    BooleanArrayAsList(boolean[] array) {
362      this(array, 0, array.length);
363    }
364
365    BooleanArrayAsList(boolean[] array, int start, int end) {
366      this.array = array;
367      this.start = start;
368      this.end = end;
369    }
370
371    @Override public int size() {
372      return end - start;
373    }
374
375    @Override public boolean isEmpty() {
376      return false;
377    }
378
379    @Override public Boolean get(int index) {
380      checkElementIndex(index, size());
381      return array[start + index];
382    }
383
384    @Override public boolean contains(Object target) {
385      // Overridden to prevent a ton of boxing
386      return (target instanceof Boolean)
387          && Booleans.indexOf(array, (Boolean) target, start, end) != -1;
388    }
389
390    @Override public int indexOf(Object target) {
391      // Overridden to prevent a ton of boxing
392      if (target instanceof Boolean) {
393        int i = Booleans.indexOf(array, (Boolean) target, start, end);
394        if (i >= 0) {
395          return i - start;
396        }
397      }
398      return -1;
399    }
400
401    @Override public int lastIndexOf(Object target) {
402      // Overridden to prevent a ton of boxing
403      if (target instanceof Boolean) {
404        int i = Booleans.lastIndexOf(array, (Boolean) target, start, end);
405        if (i >= 0) {
406          return i - start;
407        }
408      }
409      return -1;
410    }
411
412    @Override public Boolean set(int index, Boolean element) {
413      checkElementIndex(index, size());
414      boolean oldValue = array[start + index];
415      // checkNotNull for GWT (do not optimize)
416      array[start + index] = checkNotNull(element);
417      return oldValue;
418    }
419
420    @Override public List<Boolean> subList(int fromIndex, int toIndex) {
421      int size = size();
422      checkPositionIndexes(fromIndex, toIndex, size);
423      if (fromIndex == toIndex) {
424        return Collections.emptyList();
425      }
426      return new BooleanArrayAsList(array, start + fromIndex, start + toIndex);
427    }
428
429    @Override public boolean equals(Object object) {
430      if (object == this) {
431        return true;
432      }
433      if (object instanceof BooleanArrayAsList) {
434        BooleanArrayAsList that = (BooleanArrayAsList) object;
435        int size = size();
436        if (that.size() != size) {
437          return false;
438        }
439        for (int i = 0; i < size; i++) {
440          if (array[start + i] != that.array[that.start + i]) {
441            return false;
442          }
443        }
444        return true;
445      }
446      return super.equals(object);
447    }
448
449    @Override public int hashCode() {
450      int result = 1;
451      for (int i = start; i < end; i++) {
452        result = 31 * result + Booleans.hashCode(array[i]);
453      }
454      return result;
455    }
456
457    @Override public String toString() {
458      StringBuilder builder = new StringBuilder(size() * 7);
459      builder.append(array[start] ? "[true" : "[false");
460      for (int i = start + 1; i < end; i++) {
461        builder.append(array[i] ? ", true" : ", false");
462      }
463      return builder.append(']').toString();
464    }
465
466    boolean[] toBooleanArray() {
467      // Arrays.copyOfRange() is not available under GWT
468      int size = size();
469      boolean[] result = new boolean[size];
470      System.arraycopy(array, start, result, 0, size);
471      return result;
472    }
473
474    private static final long serialVersionUID = 0;
475  }
476
477  /**
478   * Returns the number of {@code values} that are {@code true}.
479   *
480   * @since 16.0
481   */
482  @Beta
483  public static int countTrue(boolean... values) {
484    int count = 0;
485    for (boolean value : values) {
486      if (value) {
487        count++;
488      }
489    }
490    return count;
491  }
492}