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