001 /*
002 * Copyright (C) 2009 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.checkNotNull;
021
022 import java.util.Comparator;
023
024 /**
025 * Static utility methods pertaining to {@code byte} primitives that interpret
026 * values as <i>unsigned</i> (that is, any negative value {@code b} is treated
027 * as the positive value {@code 256 + b}). The corresponding methods that treat
028 * the values as signed are found in {@link SignedBytes}, and the methods for
029 * which signedness is not an issue are in {@link Bytes}.
030 *
031 * @author Kevin Bourrillion
032 * @since 1
033 */
034 public final class UnsignedBytes {
035 private UnsignedBytes() {}
036
037 /**
038 * Returns the value of the given byte as an integer, when treated as
039 * unsigned. That is, returns {@code value + 256} if {@code value} is
040 * negative; {@code value} itself otherwise.
041 *
042 * @since 6
043 */
044 public static int toInt(byte value) {
045 return value & 0xFF;
046 }
047
048 /**
049 * Returns the {@code byte} value that, when treated as unsigned, is equal to
050 * {@code value}, if possible.
051 *
052 * @param value a value between 0 and 255 inclusive
053 * @return the {@code byte} value that, when treated as unsigned, equals
054 * {@code value}
055 * @throws IllegalArgumentException if {@code value} is negative or greater
056 * than 255
057 */
058 public static byte checkedCast(long value) {
059 checkArgument(value >> 8 == 0, "out of range: %s", value);
060 return (byte) value;
061 }
062
063 /**
064 * Returns the {@code byte} value that, when treated as unsigned, is nearest
065 * in value to {@code value}.
066 *
067 * @param value any {@code long} value
068 * @return {@code (byte) 255} if {@code value >= 255}, {@code (byte) 0} if
069 * {@code value <= 0}, and {@code value} cast to {@code byte} otherwise
070 */
071 public static byte saturatedCast(long value) {
072 if (value > 255) {
073 return (byte) 255; // -1
074 }
075 if (value < 0) {
076 return (byte) 0;
077 }
078 return (byte) value;
079 }
080
081 /**
082 * Compares the two specified {@code byte} values, treating them as unsigned
083 * values between 0 and 255 inclusive. For example, {@code (byte) -127} is
084 * considered greater than {@code (byte) 127} because it is seen as having
085 * the value of positive {@code 129}.
086 *
087 * @param a the first {@code byte} to compare
088 * @param b the second {@code byte} to compare
089 * @return a negative value if {@code a} is less than {@code b}; a positive
090 * value if {@code a} is greater than {@code b}; or zero if they are equal
091 */
092 public static int compare(byte a, byte b) {
093 return toInt(a) - toInt(b);
094 }
095
096 /**
097 * Returns the least value present in {@code array}.
098 *
099 * @param array a <i>nonempty</i> array of {@code byte} values
100 * @return the value present in {@code array} that is less than or equal to
101 * every other value in the array
102 * @throws IllegalArgumentException if {@code array} is empty
103 */
104 public static byte min(byte... array) {
105 checkArgument(array.length > 0);
106 int min = toInt(array[0]);
107 for (int i = 1; i < array.length; i++) {
108 int next = toInt(array[i]);
109 if (next < min) {
110 min = next;
111 }
112 }
113 return (byte) min;
114 }
115
116 /**
117 * Returns the greatest value present in {@code array}.
118 *
119 * @param array a <i>nonempty</i> array of {@code byte} values
120 * @return the value present in {@code array} that is greater than or equal
121 * to every other value in the array
122 * @throws IllegalArgumentException if {@code array} is empty
123 */
124 public static byte max(byte... array) {
125 checkArgument(array.length > 0);
126 int max = toInt(array[0]);
127 for (int i = 1; i < array.length; i++) {
128 int next = toInt(array[i]);
129 if (next > max) {
130 max = next;
131 }
132 }
133 return (byte) max;
134 }
135
136 /**
137 * Returns a string containing the supplied {@code byte} values separated by
138 * {@code separator}. For example, {@code join(":", (byte) 1, (byte) 2,
139 * (byte) 255)} returns the string {@code "1:2:255"}.
140 *
141 * @param separator the text that should appear between consecutive values in
142 * the resulting string (but not at the start or end)
143 * @param array an array of {@code byte} values, possibly empty
144 */
145 public static String join(String separator, byte... array) {
146 checkNotNull(separator);
147 if (array.length == 0) {
148 return "";
149 }
150
151 // For pre-sizing a builder, just get the right order of magnitude
152 StringBuilder builder = new StringBuilder(array.length * 5);
153 builder.append(toInt(array[0]));
154 for (int i = 1; i < array.length; i++) {
155 builder.append(separator).append(toInt(array[i]));
156 }
157 return builder.toString();
158 }
159
160 /**
161 * Returns a comparator that compares two {@code byte} arrays
162 * lexicographically. That is, it compares, using {@link
163 * #compare(byte, byte)}), the first pair of values that follow any common
164 * prefix, or when one array is a prefix of the other, treats the shorter
165 * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x7F] <
166 * [0x01, 0x80] < [0x02]}. Values are treated as unsigned.
167 *
168 * <p>The returned comparator is inconsistent with {@link
169 * Object#equals(Object)} (since arrays support only identity equality), but
170 * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}.
171 *
172 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
173 * Lexicographical order</a> article at Wikipedia
174 * @since 2
175 */
176 public static Comparator<byte[]> lexicographicalComparator() {
177 return LexicographicalComparator.INSTANCE;
178 }
179
180 private enum LexicographicalComparator implements Comparator<byte[]> {
181 INSTANCE;
182
183 public int compare(byte[] left, byte[] right) {
184 int minLength = Math.min(left.length, right.length);
185 for (int i = 0; i < minLength; i++) {
186 int result = UnsignedBytes.compare(left[i], right[i]);
187 if (result != 0) {
188 return result;
189 }
190 }
191 return left.length - right.length;
192 }
193 }
194 }