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; 026import com.google.common.base.Converter; 027 028import java.io.Serializable; 029import java.util.AbstractList; 030import java.util.Arrays; 031import java.util.Collection; 032import java.util.Collections; 033import java.util.Comparator; 034import java.util.List; 035import java.util.RandomAccess; 036 037import javax.annotation.CheckForNull; 038import javax.annotation.CheckReturnValue; 039import javax.annotation.Nullable; 040 041/** 042 * Static utility methods pertaining to {@code long} primitives, that are not 043 * already found in either {@link Long} or {@link Arrays}. 044 * 045 * <p>See the Guava User Guide article on <a href= 046 * "https://github.com/google/guava/wiki/PrimitivesExplained"> 047 * primitive utilities</a>. 048 * 049 * @author Kevin Bourrillion 050 * @since 1.0 051 */ 052@CheckReturnValue 053@GwtCompatible 054public final class Longs { 055 private Longs() {} 056 057 /** 058 * The number of bytes required to represent a primitive {@code long} 059 * value. 060 */ 061 public static final int BYTES = Long.SIZE / Byte.SIZE; 062 063 /** 064 * The largest power of two that can be represented as a {@code long}. 065 * 066 * @since 10.0 067 */ 068 public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2); 069 070 /** 071 * Returns a hash code for {@code value}; equal to the result of invoking 072 * {@code ((Long) value).hashCode()}. 073 * 074 * <p>This method always return the value specified by {@link 075 * Long#hashCode()} in java, which might be different from 076 * {@code ((Long) value).hashCode()} in GWT because {@link Long#hashCode()} 077 * in GWT does not obey the JRE contract. 078 * 079 * @param value a primitive {@code long} value 080 * @return a hash code for the value 081 */ 082 public static int hashCode(long value) { 083 return (int) (value ^ (value >>> 32)); 084 } 085 086 /** 087 * Compares the two specified {@code long} values. The sign of the value 088 * returned is the same as that of {@code ((Long) a).compareTo(b)}. 089 * 090 * <p><b>Note for Java 7 and later:</b> this method should be treated as 091 * deprecated; use the equivalent {@link Long#compare} method instead. 092 * 093 * @param a the first {@code long} to compare 094 * @param b the second {@code long} to compare 095 * @return a negative value if {@code a} is less than {@code b}; a positive 096 * value if {@code a} is greater than {@code b}; or zero if they are equal 097 */ 098 public static int compare(long a, long b) { 099 return (a < b) ? -1 : ((a > b) ? 1 : 0); 100 } 101 102 /** 103 * Returns {@code true} if {@code target} is present as an element anywhere in 104 * {@code array}. 105 * 106 * @param array an array of {@code long} values, possibly empty 107 * @param target a primitive {@code long} value 108 * @return {@code true} if {@code array[i] == target} for some value of {@code 109 * i} 110 */ 111 public static boolean contains(long[] array, long target) { 112 for (long value : array) { 113 if (value == target) { 114 return true; 115 } 116 } 117 return false; 118 } 119 120 /** 121 * Returns the index of the first appearance of the value {@code target} in 122 * {@code array}. 123 * 124 * @param array an array of {@code long} values, possibly empty 125 * @param target a primitive {@code long} value 126 * @return the least index {@code i} for which {@code array[i] == target}, or 127 * {@code -1} if no such index exists. 128 */ 129 public static int indexOf(long[] array, long target) { 130 return indexOf(array, target, 0, array.length); 131 } 132 133 // TODO(kevinb): consider making this public 134 private static int indexOf(long[] array, long target, int start, int end) { 135 for (int i = start; i < end; i++) { 136 if (array[i] == target) { 137 return i; 138 } 139 } 140 return -1; 141 } 142 143 /** 144 * Returns the start position of the first occurrence of the specified {@code 145 * target} within {@code array}, or {@code -1} if there is no such occurrence. 146 * 147 * <p>More formally, returns the lowest index {@code i} such that {@code 148 * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly 149 * the same elements as {@code target}. 150 * 151 * @param array the array to search for the sequence {@code target} 152 * @param target the array to search for as a sub-sequence of {@code array} 153 */ 154 public static int indexOf(long[] array, long[] target) { 155 checkNotNull(array, "array"); 156 checkNotNull(target, "target"); 157 if (target.length == 0) { 158 return 0; 159 } 160 161 outer: 162 for (int i = 0; i < array.length - target.length + 1; i++) { 163 for (int j = 0; j < target.length; j++) { 164 if (array[i + j] != target[j]) { 165 continue outer; 166 } 167 } 168 return i; 169 } 170 return -1; 171 } 172 173 /** 174 * Returns the index of the last appearance of the value {@code target} in 175 * {@code array}. 176 * 177 * @param array an array of {@code long} values, possibly empty 178 * @param target a primitive {@code long} value 179 * @return the greatest index {@code i} for which {@code array[i] == target}, 180 * or {@code -1} if no such index exists. 181 */ 182 public static int lastIndexOf(long[] array, long target) { 183 return lastIndexOf(array, target, 0, array.length); 184 } 185 186 // TODO(kevinb): consider making this public 187 private static int lastIndexOf(long[] array, long target, int start, int end) { 188 for (int i = end - 1; i >= start; i--) { 189 if (array[i] == target) { 190 return i; 191 } 192 } 193 return -1; 194 } 195 196 /** 197 * Returns the least value present in {@code array}. 198 * 199 * @param array a <i>nonempty</i> array of {@code long} values 200 * @return the value present in {@code array} that is less than or equal to 201 * every other value in the array 202 * @throws IllegalArgumentException if {@code array} is empty 203 */ 204 public static long min(long... array) { 205 checkArgument(array.length > 0); 206 long min = array[0]; 207 for (int i = 1; i < array.length; i++) { 208 if (array[i] < min) { 209 min = array[i]; 210 } 211 } 212 return min; 213 } 214 215 /** 216 * Returns the greatest value present in {@code array}. 217 * 218 * @param array a <i>nonempty</i> array of {@code long} values 219 * @return the value present in {@code array} that is greater than or equal to 220 * every other value in the array 221 * @throws IllegalArgumentException if {@code array} is empty 222 */ 223 public static long max(long... array) { 224 checkArgument(array.length > 0); 225 long max = array[0]; 226 for (int i = 1; i < array.length; i++) { 227 if (array[i] > max) { 228 max = array[i]; 229 } 230 } 231 return max; 232 } 233 234 /** 235 * Returns the values from each provided array combined into a single array. 236 * For example, {@code concat(new long[] {a, b}, new long[] {}, new 237 * long[] {c}} returns the array {@code {a, b, c}}. 238 * 239 * @param arrays zero or more {@code long} arrays 240 * @return a single array containing all the values from the source arrays, in 241 * order 242 */ 243 public static long[] concat(long[]... arrays) { 244 int length = 0; 245 for (long[] array : arrays) { 246 length += array.length; 247 } 248 long[] result = new long[length]; 249 int pos = 0; 250 for (long[] array : arrays) { 251 System.arraycopy(array, 0, result, pos, array.length); 252 pos += array.length; 253 } 254 return result; 255 } 256 257 /** 258 * Returns a big-endian representation of {@code value} in an 8-element byte 259 * array; equivalent to {@code ByteBuffer.allocate(8).putLong(value).array()}. 260 * For example, the input value {@code 0x1213141516171819L} would yield the 261 * byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}}. 262 * 263 * <p>If you need to convert and concatenate several values (possibly even of 264 * different types), use a shared {@link java.nio.ByteBuffer} instance, or use 265 * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable 266 * buffer. 267 */ 268 public static byte[] toByteArray(long value) { 269 // Note that this code needs to stay compatible with GWT, which has known 270 // bugs when narrowing byte casts of long values occur. 271 byte[] result = new byte[8]; 272 for (int i = 7; i >= 0; i--) { 273 result[i] = (byte) (value & 0xffL); 274 value >>= 8; 275 } 276 return result; 277 } 278 279 /** 280 * Returns the {@code long} value whose big-endian representation is 281 * stored in the first 8 bytes of {@code bytes}; equivalent to {@code 282 * ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array 283 * {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the 284 * {@code long} value {@code 0x1213141516171819L}. 285 * 286 * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that 287 * library exposes much more flexibility at little cost in readability. 288 * 289 * @throws IllegalArgumentException if {@code bytes} has fewer than 8 290 * elements 291 */ 292 public static long fromByteArray(byte[] bytes) { 293 checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); 294 return fromBytes( 295 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]); 296 } 297 298 /** 299 * Returns the {@code long} value whose byte representation is the given 8 300 * bytes, in big-endian order; equivalent to {@code Longs.fromByteArray(new 301 * byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}. 302 * 303 * @since 7.0 304 */ 305 public static long fromBytes( 306 byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) { 307 return (b1 & 0xFFL) << 56 308 | (b2 & 0xFFL) << 48 309 | (b3 & 0xFFL) << 40 310 | (b4 & 0xFFL) << 32 311 | (b5 & 0xFFL) << 24 312 | (b6 & 0xFFL) << 16 313 | (b7 & 0xFFL) << 8 314 | (b8 & 0xFFL); 315 } 316 317 /** 318 * Parses the specified string as a signed decimal long value. The ASCII 319 * character {@code '-'} (<code>'\u002D'</code>) is recognized as the 320 * minus sign. 321 * 322 * <p>Unlike {@link Long#parseLong(String)}, this method returns 323 * {@code null} instead of throwing an exception if parsing fails. 324 * Additionally, this method only accepts ASCII digits, and returns 325 * {@code null} if non-ASCII digits are present in the string. 326 * 327 * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even 328 * under JDK 7, despite the change to {@link Long#parseLong(String)} for 329 * that version. 330 * 331 * @param string the string representation of a long value 332 * @return the long value represented by {@code string}, or {@code null} if 333 * {@code string} has a length of zero or cannot be parsed as a long 334 * value 335 * @since 14.0 336 */ 337 @Beta 338 @Nullable 339 @CheckForNull 340 public static Long tryParse(String string) { 341 if (checkNotNull(string).isEmpty()) { 342 return null; 343 } 344 boolean negative = string.charAt(0) == '-'; 345 int index = negative ? 1 : 0; 346 if (index == string.length()) { 347 return null; 348 } 349 int digit = string.charAt(index++) - '0'; 350 if (digit < 0 || digit > 9) { 351 return null; 352 } 353 long accum = -digit; 354 while (index < string.length()) { 355 digit = string.charAt(index++) - '0'; 356 if (digit < 0 || digit > 9 || accum < Long.MIN_VALUE / 10) { 357 return null; 358 } 359 accum *= 10; 360 if (accum < Long.MIN_VALUE + digit) { 361 return null; 362 } 363 accum -= digit; 364 } 365 366 if (negative) { 367 return accum; 368 } else if (accum == Long.MIN_VALUE) { 369 return null; 370 } else { 371 return -accum; 372 } 373 } 374 375 private static final class LongConverter extends Converter<String, Long> implements Serializable { 376 static final LongConverter INSTANCE = new LongConverter(); 377 378 @Override 379 protected Long doForward(String value) { 380 return Long.decode(value); 381 } 382 383 @Override 384 protected String doBackward(Long value) { 385 return value.toString(); 386 } 387 388 @Override 389 public String toString() { 390 return "Longs.stringConverter()"; 391 } 392 393 private Object readResolve() { 394 return INSTANCE; 395 } 396 397 private static final long serialVersionUID = 1; 398 } 399 400 /** 401 * Returns a serializable converter object that converts between strings and 402 * longs using {@link Long#decode} and {@link Long#toString()}. 403 * 404 * @since 16.0 405 */ 406 @Beta 407 public static Converter<String, Long> stringConverter() { 408 return LongConverter.INSTANCE; 409 } 410 411 /** 412 * Returns an array containing the same values as {@code array}, but 413 * guaranteed to be of a specified minimum length. If {@code array} already 414 * has a length of at least {@code minLength}, it is returned directly. 415 * Otherwise, a new array of size {@code minLength + padding} is returned, 416 * containing the values of {@code array}, and zeroes in the remaining places. 417 * 418 * @param array the source array 419 * @param minLength the minimum length the returned array must guarantee 420 * @param padding an extra amount to "grow" the array by if growth is 421 * necessary 422 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is 423 * negative 424 * @return an array containing the values of {@code array}, with guaranteed 425 * minimum length {@code minLength} 426 */ 427 public static long[] ensureCapacity(long[] array, int minLength, int padding) { 428 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 429 checkArgument(padding >= 0, "Invalid padding: %s", padding); 430 return (array.length < minLength) 431 ? copyOf(array, minLength + padding) 432 : array; 433 } 434 435 // Arrays.copyOf() requires Java 6 436 private static long[] copyOf(long[] original, int length) { 437 long[] copy = new long[length]; 438 System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); 439 return copy; 440 } 441 442 /** 443 * Returns a string containing the supplied {@code long} values separated 444 * by {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns 445 * the string {@code "1-2-3"}. 446 * 447 * @param separator the text that should appear between consecutive values in 448 * the resulting string (but not at the start or end) 449 * @param array an array of {@code long} values, possibly empty 450 */ 451 public static String join(String separator, long... array) { 452 checkNotNull(separator); 453 if (array.length == 0) { 454 return ""; 455 } 456 457 // For pre-sizing a builder, just get the right order of magnitude 458 StringBuilder builder = new StringBuilder(array.length * 10); 459 builder.append(array[0]); 460 for (int i = 1; i < array.length; i++) { 461 builder.append(separator).append(array[i]); 462 } 463 return builder.toString(); 464 } 465 466 /** 467 * Returns a comparator that compares two {@code long} arrays 468 * lexicographically. That is, it compares, using {@link 469 * #compare(long, long)}), the first pair of values that follow any 470 * common prefix, or when one array is a prefix of the other, treats the 471 * shorter array as the lesser. For example, 472 * {@code [] < [1L] < [1L, 2L] < [2L]}. 473 * 474 * <p>The returned comparator is inconsistent with {@link 475 * Object#equals(Object)} (since arrays support only identity equality), but 476 * it is consistent with {@link Arrays#equals(long[], long[])}. 477 * 478 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> 479 * Lexicographical order article at Wikipedia</a> 480 * @since 2.0 481 */ 482 public static Comparator<long[]> lexicographicalComparator() { 483 return LexicographicalComparator.INSTANCE; 484 } 485 486 private enum LexicographicalComparator implements Comparator<long[]> { 487 INSTANCE; 488 489 @Override 490 public int compare(long[] left, long[] right) { 491 int minLength = Math.min(left.length, right.length); 492 for (int i = 0; i < minLength; i++) { 493 int result = Longs.compare(left[i], right[i]); 494 if (result != 0) { 495 return result; 496 } 497 } 498 return left.length - right.length; 499 } 500 } 501 502 /** 503 * Returns an array containing each value of {@code collection}, converted to 504 * a {@code long} value in the manner of {@link Number#longValue}. 505 * 506 * <p>Elements are copied from the argument collection as if by {@code 507 * collection.toArray()}. Calling this method is as thread-safe as calling 508 * that method. 509 * 510 * @param collection a collection of {@code Number} instances 511 * @return an array containing the same values as {@code collection}, in the 512 * same order, converted to primitives 513 * @throws NullPointerException if {@code collection} or any of its elements 514 * is null 515 * @since 1.0 (parameter was {@code Collection<Long>} before 12.0) 516 */ 517 public static long[] toArray(Collection<? extends Number> collection) { 518 if (collection instanceof LongArrayAsList) { 519 return ((LongArrayAsList) collection).toLongArray(); 520 } 521 522 Object[] boxedArray = collection.toArray(); 523 int len = boxedArray.length; 524 long[] array = new long[len]; 525 for (int i = 0; i < len; i++) { 526 // checkNotNull for GWT (do not optimize) 527 array[i] = ((Number) checkNotNull(boxedArray[i])).longValue(); 528 } 529 return array; 530 } 531 532 /** 533 * Returns a fixed-size list backed by the specified array, similar to {@link 534 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, 535 * but any attempt to set a value to {@code null} will result in a {@link 536 * NullPointerException}. 537 * 538 * <p>The returned list maintains the values, but not the identities, of 539 * {@code Long} objects written to or read from it. For example, whether 540 * {@code list.get(0) == list.get(0)} is true for the returned list is 541 * unspecified. 542 * 543 * @param backingArray the array to back the list 544 * @return a list view of the array 545 */ 546 public static List<Long> asList(long... backingArray) { 547 if (backingArray.length == 0) { 548 return Collections.emptyList(); 549 } 550 return new LongArrayAsList(backingArray); 551 } 552 553 @GwtCompatible 554 private static class LongArrayAsList extends AbstractList<Long> 555 implements RandomAccess, Serializable { 556 final long[] array; 557 final int start; 558 final int end; 559 560 LongArrayAsList(long[] array) { 561 this(array, 0, array.length); 562 } 563 564 LongArrayAsList(long[] array, int start, int end) { 565 this.array = array; 566 this.start = start; 567 this.end = end; 568 } 569 570 @Override 571 public int size() { 572 return end - start; 573 } 574 575 @Override 576 public boolean isEmpty() { 577 return false; 578 } 579 580 @Override 581 public Long get(int index) { 582 checkElementIndex(index, size()); 583 return array[start + index]; 584 } 585 586 @Override 587 public boolean contains(Object target) { 588 // Overridden to prevent a ton of boxing 589 return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1; 590 } 591 592 @Override 593 public int indexOf(Object target) { 594 // Overridden to prevent a ton of boxing 595 if (target instanceof Long) { 596 int i = Longs.indexOf(array, (Long) target, start, end); 597 if (i >= 0) { 598 return i - start; 599 } 600 } 601 return -1; 602 } 603 604 @Override 605 public int lastIndexOf(Object target) { 606 // Overridden to prevent a ton of boxing 607 if (target instanceof Long) { 608 int i = Longs.lastIndexOf(array, (Long) target, start, end); 609 if (i >= 0) { 610 return i - start; 611 } 612 } 613 return -1; 614 } 615 616 @Override 617 public Long set(int index, Long element) { 618 checkElementIndex(index, size()); 619 long oldValue = array[start + index]; 620 // checkNotNull for GWT (do not optimize) 621 array[start + index] = checkNotNull(element); 622 return oldValue; 623 } 624 625 @Override 626 public List<Long> subList(int fromIndex, int toIndex) { 627 int size = size(); 628 checkPositionIndexes(fromIndex, toIndex, size); 629 if (fromIndex == toIndex) { 630 return Collections.emptyList(); 631 } 632 return new LongArrayAsList(array, start + fromIndex, start + toIndex); 633 } 634 635 @Override 636 public boolean equals(@Nullable Object object) { 637 if (object == this) { 638 return true; 639 } 640 if (object instanceof LongArrayAsList) { 641 LongArrayAsList that = (LongArrayAsList) object; 642 int size = size(); 643 if (that.size() != size) { 644 return false; 645 } 646 for (int i = 0; i < size; i++) { 647 if (array[start + i] != that.array[that.start + i]) { 648 return false; 649 } 650 } 651 return true; 652 } 653 return super.equals(object); 654 } 655 656 @Override 657 public int hashCode() { 658 int result = 1; 659 for (int i = start; i < end; i++) { 660 result = 31 * result + Longs.hashCode(array[i]); 661 } 662 return result; 663 } 664 665 @Override 666 public String toString() { 667 StringBuilder builder = new StringBuilder(size() * 10); 668 builder.append('[').append(array[start]); 669 for (int i = start + 1; i < end; i++) { 670 builder.append(", ").append(array[i]); 671 } 672 return builder.append(']').toString(); 673 } 674 675 long[] toLongArray() { 676 // Arrays.copyOfRange() is not available under GWT 677 int size = size(); 678 long[] result = new long[size]; 679 System.arraycopy(array, start, result, 0, size); 680 return result; 681 } 682 683 private static final long serialVersionUID = 0; 684 } 685}