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