001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.primitives;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.primitives.UnsignedInts.INT_MASK;
020import static com.google.common.primitives.UnsignedInts.compare;
021import static com.google.common.primitives.UnsignedInts.toLong;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.annotations.J2ktIncompatible;
026import java.math.BigInteger;
027import org.checkerframework.checker.nullness.qual.Nullable;
028
029/**
030 * A wrapper class for unsigned {@code int} values, supporting arithmetic operations.
031 *
032 * <p>In some cases, when speed is more important than code readability, it may be faster simply to
033 * treat primitive {@code int} values as unsigned, using the methods from {@link UnsignedInts}.
034 *
035 * <p>See the Guava User Guide article on <a
036 * href="https://github.com/google/guava/wiki/PrimitivesExplained#unsigned-support">unsigned
037 * primitive utilities</a>.
038 *
039 * @author Louis Wasserman
040 * @since 11.0
041 */
042@GwtCompatible(emulated = true)
043public final class UnsignedInteger extends Number implements Comparable<UnsignedInteger> {
044  public static final UnsignedInteger ZERO = fromIntBits(0);
045  public static final UnsignedInteger ONE = fromIntBits(1);
046  public static final UnsignedInteger MAX_VALUE = fromIntBits(-1);
047
048  private final int value;
049
050  private UnsignedInteger(int value) {
051    // GWT doesn't consistently overflow values to make them 32-bit, so we need to force it.
052    this.value = value & 0xffffffff;
053  }
054
055  /**
056   * Returns an {@code UnsignedInteger} corresponding to a given bit representation. The argument is
057   * interpreted as an unsigned 32-bit value. Specifically, the sign bit of {@code bits} is
058   * interpreted as a normal bit, and all other bits are treated as usual.
059   *
060   * <p>If the argument is nonnegative, the returned result will be equal to {@code bits},
061   * otherwise, the result will be equal to {@code 2^32 + bits}.
062   *
063   * <p>To represent unsigned decimal constants, consider {@link #valueOf(long)} instead.
064   *
065   * @since 14.0
066   */
067  public static UnsignedInteger fromIntBits(int bits) {
068    return new UnsignedInteger(bits);
069  }
070
071  /**
072   * Returns an {@code UnsignedInteger} that is equal to {@code value}, if possible. The inverse
073   * operation of {@link #longValue()}.
074   */
075  public static UnsignedInteger valueOf(long value) {
076    checkArgument(
077        (value & INT_MASK) == value,
078        "value (%s) is outside the range for an unsigned integer value",
079        value);
080    return fromIntBits((int) value);
081  }
082
083  /**
084   * Returns a {@code UnsignedInteger} representing the same value as the specified {@link
085   * BigInteger}. This is the inverse operation of {@link #bigIntegerValue()}.
086   *
087   * @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^32}
088   */
089  public static UnsignedInteger valueOf(BigInteger value) {
090    checkNotNull(value);
091    checkArgument(
092        value.signum() >= 0 && value.bitLength() <= Integer.SIZE,
093        "value (%s) is outside the range for an unsigned integer value",
094        value);
095    return fromIntBits(value.intValue());
096  }
097
098  /**
099   * Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed as
100   * an unsigned {@code int} value.
101   *
102   * @throws NumberFormatException if the string does not contain a parsable unsigned {@code int}
103   *     value
104   */
105  public static UnsignedInteger valueOf(String string) {
106    return valueOf(string, 10);
107  }
108
109  /**
110   * Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed as
111   * an unsigned {@code int} value in the specified radix.
112   *
113   * @throws NumberFormatException if the string does not contain a parsable unsigned {@code int}
114   *     value
115   */
116  public static UnsignedInteger valueOf(String string, int radix) {
117    return fromIntBits(UnsignedInts.parseUnsignedInt(string, radix));
118  }
119
120  /**
121   * Returns the result of adding this and {@code val}. If the result would have more than 32 bits,
122   * returns the low 32 bits of the result.
123   *
124   * @since 14.0
125   */
126  public UnsignedInteger plus(UnsignedInteger val) {
127    return fromIntBits(this.value + checkNotNull(val).value);
128  }
129
130  /**
131   * Returns the result of subtracting this and {@code val}. If the result would be negative,
132   * returns the low 32 bits of the result.
133   *
134   * @since 14.0
135   */
136  public UnsignedInteger minus(UnsignedInteger val) {
137    return fromIntBits(value - checkNotNull(val).value);
138  }
139
140  /**
141   * Returns the result of multiplying this and {@code val}. If the result would have more than 32
142   * bits, returns the low 32 bits of the result.
143   *
144   * @since 14.0
145   */
146  @J2ktIncompatible
147  @GwtIncompatible // Does not truncate correctly
148  public UnsignedInteger times(UnsignedInteger val) {
149    // TODO(lowasser): make this GWT-compatible
150    return fromIntBits(value * checkNotNull(val).value);
151  }
152
153  /**
154   * Returns the result of dividing this by {@code val}.
155   *
156   * @throws ArithmeticException if {@code val} is zero
157   * @since 14.0
158   */
159  public UnsignedInteger dividedBy(UnsignedInteger val) {
160    return fromIntBits(UnsignedInts.divide(value, checkNotNull(val).value));
161  }
162
163  /**
164   * Returns this mod {@code val}.
165   *
166   * @throws ArithmeticException if {@code val} is zero
167   * @since 14.0
168   */
169  public UnsignedInteger mod(UnsignedInteger val) {
170    return fromIntBits(UnsignedInts.remainder(value, checkNotNull(val).value));
171  }
172
173  /**
174   * Returns the value of this {@code UnsignedInteger} as an {@code int}. This is an inverse
175   * operation to {@link #fromIntBits}.
176   *
177   * <p>Note that if this {@code UnsignedInteger} holds a value {@code >= 2^31}, the returned value
178   * will be equal to {@code this - 2^32}.
179   */
180  @Override
181  public int intValue() {
182    return value;
183  }
184
185  /** Returns the value of this {@code UnsignedInteger} as a {@code long}. */
186  @Override
187  public long longValue() {
188    return toLong(value);
189  }
190
191  /**
192   * Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening
193   * primitive conversion from {@code int} to {@code float}, and correctly rounded.
194   */
195  @Override
196  public float floatValue() {
197    return longValue();
198  }
199
200  /**
201   * Returns the value of this {@code UnsignedInteger} as a {@code double}, analogous to a widening
202   * primitive conversion from {@code int} to {@code double}, and correctly rounded.
203   */
204  @Override
205  public double doubleValue() {
206    return longValue();
207  }
208
209  /** Returns the value of this {@code UnsignedInteger} as a {@link BigInteger}. */
210  public BigInteger bigIntegerValue() {
211    return BigInteger.valueOf(longValue());
212  }
213
214  /**
215   * Compares this unsigned integer to another unsigned integer. Returns {@code 0} if they are
216   * equal, a negative number if {@code this < other}, and a positive number if {@code this >
217   * other}.
218   */
219  @Override
220  public int compareTo(UnsignedInteger other) {
221    checkNotNull(other);
222    return compare(value, other.value);
223  }
224
225  @Override
226  public int hashCode() {
227    return value;
228  }
229
230  @Override
231  public boolean equals(@Nullable Object obj) {
232    if (obj instanceof UnsignedInteger) {
233      UnsignedInteger other = (UnsignedInteger) obj;
234      return value == other.value;
235    }
236    return false;
237  }
238
239  /** Returns a string representation of the {@code UnsignedInteger} value, in base 10. */
240  @Override
241  public String toString() {
242    return toString(10);
243  }
244
245  /**
246   * Returns a string representation of the {@code UnsignedInteger} value, in base {@code radix}. If
247   * {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix {@code
248   * 10} is used.
249   */
250  public String toString(int radix) {
251    return UnsignedInts.toString(value, radix);
252  }
253}