1 /* 2 * Copyright (C) 2009 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.primitives; 18 19 import static com.google.common.base.Preconditions.checkArgument; 20 import static com.google.common.base.Preconditions.checkNotNull; 21 22 import com.google.common.annotations.Beta; 23 import com.google.common.annotations.VisibleForTesting; 24 25 import java.util.Comparator; 26 27 /** 28 * Static utility methods pertaining to {@code byte} primitives that interpret 29 * values as <i>unsigned</i> (that is, any negative value {@code b} is treated 30 * as the positive value {@code 256 + b}). The corresponding methods that treat 31 * the values as signed are found in {@link SignedBytes}, and the methods for 32 * which signedness is not an issue are in {@link Bytes}. 33 * 34 * <p>See the Guava User Guide article on <a href= 35 * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> 36 * primitive utilities</a>. 37 * 38 * @author Kevin Bourrillion 39 * @author Martin Buchholz 40 * @author Hiroshi Yamauchi 41 * @author Louis Wasserman 42 * @since 1.0 43 */ 44 public final class UnsignedBytes { UnsignedBytes()45 private UnsignedBytes() {} 46 47 /** 48 * The largest power of two that can be represented as an unsigned {@code 49 * byte}. 50 * 51 * @since 10.0 52 */ 53 public static final byte MAX_POWER_OF_TWO = (byte) 0x80; 54 55 /** 56 * The largest value that fits into an unsigned byte. 57 * 58 * @since 13.0 59 */ 60 public static final byte MAX_VALUE = (byte) 0xFF; 61 62 private static final int UNSIGNED_MASK = 0xFF; 63 64 /** 65 * Returns the value of the given byte as an integer, when treated as 66 * unsigned. That is, returns {@code value + 256} if {@code value} is 67 * negative; {@code value} itself otherwise. 68 * 69 * @since 6.0 70 */ toInt(byte value)71 public static int toInt(byte value) { 72 return value & UNSIGNED_MASK; 73 } 74 75 /** 76 * Returns the {@code byte} value that, when treated as unsigned, is equal to 77 * {@code value}, if possible. 78 * 79 * @param value a value between 0 and 255 inclusive 80 * @return the {@code byte} value that, when treated as unsigned, equals 81 * {@code value} 82 * @throws IllegalArgumentException if {@code value} is negative or greater 83 * than 255 84 */ checkedCast(long value)85 public static byte checkedCast(long value) { 86 if ((value >> Byte.SIZE) != 0) { 87 // don't use checkArgument here, to avoid boxing 88 throw new IllegalArgumentException("Out of range: " + value); 89 } 90 return (byte) value; 91 } 92 93 /** 94 * Returns the {@code byte} value that, when treated as unsigned, is nearest 95 * in value to {@code value}. 96 * 97 * @param value any {@code long} value 98 * @return {@code (byte) 255} if {@code value >= 255}, {@code (byte) 0} if 99 * {@code value <= 0}, and {@code value} cast to {@code byte} otherwise 100 */ saturatedCast(long value)101 public static byte saturatedCast(long value) { 102 if (value > toInt(MAX_VALUE)) { 103 return MAX_VALUE; // -1 104 } 105 if (value < 0) { 106 return (byte) 0; 107 } 108 return (byte) value; 109 } 110 111 /** 112 * Compares the two specified {@code byte} values, treating them as unsigned 113 * values between 0 and 255 inclusive. For example, {@code (byte) -127} is 114 * considered greater than {@code (byte) 127} because it is seen as having 115 * the value of positive {@code 129}. 116 * 117 * @param a the first {@code byte} to compare 118 * @param b the second {@code byte} to compare 119 * @return a negative value if {@code a} is less than {@code b}; a positive 120 * value if {@code a} is greater than {@code b}; or zero if they are equal 121 */ compare(byte a, byte b)122 public static int compare(byte a, byte b) { 123 return toInt(a) - toInt(b); 124 } 125 126 /** 127 * Returns the least value present in {@code array}. 128 * 129 * @param array a <i>nonempty</i> array of {@code byte} values 130 * @return the value present in {@code array} that is less than or equal to 131 * every other value in the array 132 * @throws IllegalArgumentException if {@code array} is empty 133 */ min(byte... array)134 public static byte min(byte... array) { 135 checkArgument(array.length > 0); 136 int min = toInt(array[0]); 137 for (int i = 1; i < array.length; i++) { 138 int next = toInt(array[i]); 139 if (next < min) { 140 min = next; 141 } 142 } 143 return (byte) min; 144 } 145 146 /** 147 * Returns the greatest value present in {@code array}. 148 * 149 * @param array a <i>nonempty</i> array of {@code byte} values 150 * @return the value present in {@code array} that is greater than or equal 151 * to every other value in the array 152 * @throws IllegalArgumentException if {@code array} is empty 153 */ max(byte... array)154 public static byte max(byte... array) { 155 checkArgument(array.length > 0); 156 int max = toInt(array[0]); 157 for (int i = 1; i < array.length; i++) { 158 int next = toInt(array[i]); 159 if (next > max) { 160 max = next; 161 } 162 } 163 return (byte) max; 164 } 165 166 /** 167 * Returns a string representation of x, where x is treated as unsigned. 168 * 169 * @since 13.0 170 */ 171 @Beta toString(byte x)172 public static String toString(byte x) { 173 return toString(x, 10); 174 } 175 176 /** 177 * Returns a string representation of {@code x} for the given radix, where {@code x} is treated 178 * as unsigned. 179 * 180 * @param x the value to convert to a string. 181 * @param radix the radix to use while working with {@code x} 182 * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} 183 * and {@link Character#MAX_RADIX}. 184 * @since 13.0 185 */ 186 @Beta toString(byte x, int radix)187 public static String toString(byte x, int radix) { 188 checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX, 189 "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix); 190 // Benchmarks indicate this is probably not worth optimizing. 191 return Integer.toString(toInt(x), radix); 192 } 193 194 /** 195 * Returns the unsigned {@code byte} value represented by the given decimal string. 196 * 197 * @throws NumberFormatException if the string does not contain a valid unsigned {@code byte} 198 * value 199 * @throws NullPointerException if {@code s} is null 200 * (in contrast to {@link Byte#parseByte(String)}) 201 * @since 13.0 202 */ 203 @Beta parseUnsignedByte(String string)204 public static byte parseUnsignedByte(String string) { 205 return parseUnsignedByte(string, 10); 206 } 207 208 /** 209 * Returns the unsigned {@code byte} value represented by a string with the given radix. 210 * 211 * @param string the string containing the unsigned {@code byte} representation to be parsed. 212 * @param radix the radix to use while parsing {@code string} 213 * @throws NumberFormatException if the string does not contain a valid unsigned {@code byte} 214 * with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} 215 * and {@link Character#MAX_RADIX}. 216 * @throws NullPointerException if {@code s} is null 217 * (in contrast to {@link Byte#parseByte(String)}) 218 * @since 13.0 219 */ 220 @Beta parseUnsignedByte(String string, int radix)221 public static byte parseUnsignedByte(String string, int radix) { 222 int parse = Integer.parseInt(checkNotNull(string), radix); 223 // We need to throw a NumberFormatException, so we have to duplicate checkedCast. =( 224 if (parse >> Byte.SIZE == 0) { 225 return (byte) parse; 226 } else { 227 throw new NumberFormatException("out of range: " + parse); 228 } 229 } 230 231 /** 232 * Returns a string containing the supplied {@code byte} values separated by 233 * {@code separator}. For example, {@code join(":", (byte) 1, (byte) 2, 234 * (byte) 255)} returns the string {@code "1:2:255"}. 235 * 236 * @param separator the text that should appear between consecutive values in 237 * the resulting string (but not at the start or end) 238 * @param array an array of {@code byte} values, possibly empty 239 */ join(String separator, byte... array)240 public static String join(String separator, byte... array) { 241 checkNotNull(separator); 242 if (array.length == 0) { 243 return ""; 244 } 245 246 // For pre-sizing a builder, just get the right order of magnitude 247 StringBuilder builder = new StringBuilder(array.length * (3 + separator.length())); 248 builder.append(toInt(array[0])); 249 for (int i = 1; i < array.length; i++) { 250 builder.append(separator).append(toString(array[i])); 251 } 252 return builder.toString(); 253 } 254 255 /** 256 * Returns a comparator that compares two {@code byte} arrays 257 * lexicographically. That is, it compares, using {@link 258 * #compare(byte, byte)}), the first pair of values that follow any common 259 * prefix, or when one array is a prefix of the other, treats the shorter 260 * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x7F] < 261 * [0x01, 0x80] < [0x02]}. Values are treated as unsigned. 262 * 263 * <p>The returned comparator is inconsistent with {@link 264 * Object#equals(Object)} (since arrays support only identity equality), but 265 * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}. 266 * 267 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> 268 * Lexicographical order article at Wikipedia</a> 269 * @since 2.0 270 */ lexicographicalComparator()271 public static Comparator<byte[]> lexicographicalComparator() { 272 return LexicographicalComparatorHolder.BEST_COMPARATOR; 273 } 274 275 @VisibleForTesting lexicographicalComparatorJavaImpl()276 static Comparator<byte[]> lexicographicalComparatorJavaImpl() { 277 return LexicographicalComparatorHolder.PureJavaComparator.INSTANCE; 278 } 279 280 /** 281 * Provides a pure Java lexicographical comparator implementation. 282 */ 283 @VisibleForTesting 284 static class LexicographicalComparatorHolder { 285 286 static final Comparator<byte[]> BEST_COMPARATOR = lexicographicalComparatorJavaImpl(); 287 288 enum PureJavaComparator implements Comparator<byte[]> { 289 INSTANCE; 290 compare(byte[] left, byte[] right)291 @Override public int compare(byte[] left, byte[] right) { 292 int minLength = Math.min(left.length, right.length); 293 for (int i = 0; i < minLength; i++) { 294 int result = UnsignedBytes.compare(left[i], right[i]); 295 if (result != 0) { 296 return result; 297 } 298 } 299 return left.length - right.length; 300 } 301 } 302 } 303 } 304