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 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 @Override 379 public int compare(long[] left, long[] right) { 380 int minLength = Math.min(left.length, right.length); 381 for (int i = 0; i < minLength; i++) { 382 int result = Longs.compare(left[i], right[i]); 383 if (result != 0) { 384 return result; 385 } 386 } 387 return left.length - right.length; 388 } 389 } 390 391 /** 392 * Copies a collection of {@code Long} instances into a new array of 393 * primitive {@code long} values. 394 * 395 * <p>Elements are copied from the argument collection as if by {@code 396 * collection.toArray()}. Calling this method is as thread-safe as calling 397 * that method. 398 * 399 * @param collection a collection of {@code Long} objects 400 * @return an array containing the same values as {@code collection}, in the 401 * same order, converted to primitives 402 * @throws NullPointerException if {@code collection} or any of its elements 403 * is null 404 */ 405 public static long[] toArray(Collection<Long> collection) { 406 if (collection instanceof LongArrayAsList) { 407 return ((LongArrayAsList) collection).toLongArray(); 408 } 409 410 Object[] boxedArray = collection.toArray(); 411 int len = boxedArray.length; 412 long[] array = new long[len]; 413 for (int i = 0; i < len; i++) { 414 array[i] = (Long) boxedArray[i]; 415 } 416 return array; 417 } 418 419 /** 420 * Returns a fixed-size list backed by the specified array, similar to {@link 421 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, 422 * but any attempt to set a value to {@code null} will result in a {@link 423 * NullPointerException}. 424 * 425 * <p>The returned list maintains the values, but not the identities, of 426 * {@code Long} objects written to or read from it. For example, whether 427 * {@code list.get(0) == list.get(0)} is true for the returned list is 428 * unspecified. 429 * 430 * @param backingArray the array to back the list 431 * @return a list view of the array 432 */ 433 public static List<Long> asList(long... backingArray) { 434 if (backingArray.length == 0) { 435 return Collections.emptyList(); 436 } 437 return new LongArrayAsList(backingArray); 438 } 439 440 @GwtCompatible 441 private static class LongArrayAsList extends AbstractList<Long> 442 implements RandomAccess, Serializable { 443 final long[] array; 444 final int start; 445 final int end; 446 447 LongArrayAsList(long[] array) { 448 this(array, 0, array.length); 449 } 450 451 LongArrayAsList(long[] array, int start, int end) { 452 this.array = array; 453 this.start = start; 454 this.end = end; 455 } 456 457 @Override public int size() { 458 return end - start; 459 } 460 461 @Override public boolean isEmpty() { 462 return false; 463 } 464 465 @Override public Long get(int index) { 466 checkElementIndex(index, size()); 467 return array[start + index]; 468 } 469 470 @Override public boolean contains(Object target) { 471 // Overridden to prevent a ton of boxing 472 return (target instanceof Long) 473 && Longs.indexOf(array, (Long) target, start, end) != -1; 474 } 475 476 @Override public int indexOf(Object target) { 477 // Overridden to prevent a ton of boxing 478 if (target instanceof Long) { 479 int i = Longs.indexOf(array, (Long) target, start, end); 480 if (i >= 0) { 481 return i - start; 482 } 483 } 484 return -1; 485 } 486 487 @Override public int lastIndexOf(Object target) { 488 // Overridden to prevent a ton of boxing 489 if (target instanceof Long) { 490 int i = Longs.lastIndexOf(array, (Long) target, start, end); 491 if (i >= 0) { 492 return i - start; 493 } 494 } 495 return -1; 496 } 497 498 @Override public Long set(int index, Long element) { 499 checkElementIndex(index, size()); 500 long oldValue = array[start + index]; 501 array[start + index] = element; 502 return oldValue; 503 } 504 505 @Override public List<Long> subList(int fromIndex, int toIndex) { 506 int size = size(); 507 checkPositionIndexes(fromIndex, toIndex, size); 508 if (fromIndex == toIndex) { 509 return Collections.emptyList(); 510 } 511 return new LongArrayAsList(array, start + fromIndex, start + toIndex); 512 } 513 514 @Override public boolean equals(Object object) { 515 if (object == this) { 516 return true; 517 } 518 if (object instanceof LongArrayAsList) { 519 LongArrayAsList that = (LongArrayAsList) object; 520 int size = size(); 521 if (that.size() != size) { 522 return false; 523 } 524 for (int i = 0; i < size; i++) { 525 if (array[start + i] != that.array[that.start + i]) { 526 return false; 527 } 528 } 529 return true; 530 } 531 return super.equals(object); 532 } 533 534 @Override public int hashCode() { 535 int result = 1; 536 for (int i = start; i < end; i++) { 537 result = 31 * result + Longs.hashCode(array[i]); 538 } 539 return result; 540 } 541 542 @Override public String toString() { 543 StringBuilder builder = new StringBuilder(size() * 10); 544 builder.append('[').append(array[start]); 545 for (int i = start + 1; i < end; i++) { 546 builder.append(", ").append(array[i]); 547 } 548 return builder.append(']').toString(); 549 } 550 551 long[] toLongArray() { 552 // Arrays.copyOfRange() requires Java 6 553 int size = size(); 554 long[] result = new long[size]; 555 System.arraycopy(array, start, result, 0, size); 556 return result; 557 } 558 559 private static final long serialVersionUID = 0; 560 } 561 }