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.jspecify.annotations.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
043public final class UnsignedInteger extends Number implements Comparable<UnsignedInteger> {
044  /** An {@code UnsignedInteger} constant holding the value 0. */
045  public static final UnsignedInteger ZERO = fromIntBits(0);
046
047  /** An {@code UnsignedInteger} constant holding the value 1. */
048  public static final UnsignedInteger ONE = fromIntBits(1);
049
050  /** An {@code UnsignedInteger} constant holding the maximum value, 2^32 - 1. */
051  public static final UnsignedInteger MAX_VALUE = fromIntBits(-1);
052
053  private final int value;
054
055  private UnsignedInteger(int value) {
056    // GWT doesn't consistently overflow values to make them 32-bit, so we need to force it.
057    this.value = value & 0xffffffff;
058  }
059
060  /**
061   * Returns an {@code UnsignedInteger} corresponding to a given bit representation. The argument is
062   * interpreted as an unsigned 32-bit value. Specifically, the sign bit of {@code bits} is
063   * interpreted as a normal bit, and all other bits are treated as usual.
064   *
065   * <p>If the argument is nonnegative, the returned result will be equal to {@code bits},
066   * otherwise, the result will be equal to {@code 2^32 + bits}.
067   *
068   * <p>To represent unsigned decimal constants, consider {@link #valueOf(long)} instead.
069   *
070   * @since 14.0
071   */
072  public static UnsignedInteger fromIntBits(int bits) {
073    return new UnsignedInteger(bits);
074  }
075
076  /**
077   * Returns an {@code UnsignedInteger} that is equal to {@code value}, if possible. The inverse
078   * operation of {@link #longValue()}.
079   */
080  public static UnsignedInteger valueOf(long value) {
081    checkArgument(
082        (value & INT_MASK) == value,
083        "value (%s) is outside the range for an unsigned integer value",
084        value);
085    return fromIntBits((int) value);
086  }
087
088  /**
089   * Returns a {@code UnsignedInteger} representing the same value as the specified {@link
090   * BigInteger}. This is the inverse operation of {@link #bigIntegerValue()}.
091   *
092   * @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^32}
093   */
094  public static UnsignedInteger valueOf(BigInteger value) {
095    checkNotNull(value);
096    checkArgument(
097        value.signum() >= 0 && value.bitLength() <= Integer.SIZE,
098        "value (%s) is outside the range for an unsigned integer value",
099        value);
100    return fromIntBits(value.intValue());
101  }
102
103  /**
104   * Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed as
105   * an unsigned {@code int} value.
106   *
107   * @throws NumberFormatException if the string does not contain a parsable unsigned {@code int}
108   *     value
109   */
110  public static UnsignedInteger valueOf(String string) {
111    return valueOf(string, 10);
112  }
113
114  /**
115   * Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed as
116   * an unsigned {@code int} value in the specified radix.
117   *
118   * @throws NumberFormatException if the string does not contain a parsable unsigned {@code int}
119   *     value
120   */
121  public static UnsignedInteger valueOf(String string, int radix) {
122    return fromIntBits(UnsignedInts.parseUnsignedInt(string, radix));
123  }
124
125  /**
126   * Returns the result of adding this and {@code val}. If the result would have more than 32 bits,
127   * returns the low 32 bits of the result.
128   *
129   * @since 14.0
130   */
131  public UnsignedInteger plus(UnsignedInteger val) {
132    return fromIntBits(this.value + checkNotNull(val).value);
133  }
134
135  /**
136   * Returns the result of subtracting this and {@code val}. If the result would be negative,
137   * returns the low 32 bits of the result.
138   *
139   * @since 14.0
140   */
141  public UnsignedInteger minus(UnsignedInteger val) {
142    return fromIntBits(value - checkNotNull(val).value);
143  }
144
145  /**
146   * Returns the result of multiplying this and {@code val}. If the result would have more than 32
147   * bits, returns the low 32 bits of the result.
148   *
149   * @since 14.0
150   */
151  @J2ktIncompatible
152  @GwtIncompatible // Does not truncate correctly
153  public UnsignedInteger times(UnsignedInteger val) {
154    // TODO(lowasser): make this GWT-compatible
155    return fromIntBits(value * checkNotNull(val).value);
156  }
157
158  /**
159   * Returns the result of dividing this by {@code val}.
160   *
161   * @throws ArithmeticException if {@code val} is zero
162   * @since 14.0
163   */
164  public UnsignedInteger dividedBy(UnsignedInteger val) {
165    return fromIntBits(UnsignedInts.divide(value, checkNotNull(val).value));
166  }
167
168  /**
169   * Returns this mod {@code val}.
170   *
171   * @throws ArithmeticException if {@code val} is zero
172   * @since 14.0
173   */
174  public UnsignedInteger mod(UnsignedInteger val) {
175    return fromIntBits(UnsignedInts.remainder(value, checkNotNull(val).value));
176  }
177
178  /**
179   * Returns the value of this {@code UnsignedInteger} as an {@code int}. This is an inverse
180   * operation to {@link #fromIntBits}.
181   *
182   * <p>Note that if this {@code UnsignedInteger} holds a value {@code >= 2^31}, the returned value
183   * will be equal to {@code this - 2^32}.
184   */
185  @Override
186  public int intValue() {
187    return value;
188  }
189
190  /** Returns the value of this {@code UnsignedInteger} as a {@code long}. */
191  @Override
192  public long longValue() {
193    return toLong(value);
194  }
195
196  /**
197   * Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening
198   * primitive conversion from {@code int} to {@code float}, and correctly rounded.
199   */
200  @Override
201  public float floatValue() {
202    return longValue();
203  }
204
205  /**
206   * Returns the value of this {@code UnsignedInteger} as a {@code double}, analogous to a widening
207   * primitive conversion from {@code int} to {@code double}, and correctly rounded.
208   */
209  @Override
210  public double doubleValue() {
211    return longValue();
212  }
213
214  /** Returns the value of this {@code UnsignedInteger} as a {@link BigInteger}. */
215  public BigInteger bigIntegerValue() {
216    return BigInteger.valueOf(longValue());
217  }
218
219  /**
220   * Compares this unsigned integer to another unsigned integer. Returns {@code 0} if they are
221   * equal, a negative number if {@code this < other}, and a positive number if {@code this >
222   * other}.
223   */
224  @Override
225  public int compareTo(UnsignedInteger other) {
226    checkNotNull(other);
227    return compare(value, other.value);
228  }
229
230  @Override
231  public int hashCode() {
232    return value;
233  }
234
235  @Override
236  public boolean equals(@Nullable Object obj) {
237    if (obj instanceof UnsignedInteger) {
238      UnsignedInteger other = (UnsignedInteger) obj;
239      return value == other.value;
240    }
241    return false;
242  }
243
244  /** Returns a string representation of the {@code UnsignedInteger} value, in base 10. */
245  @Override
246  public String toString() {
247    return toString(10);
248  }
249
250  /**
251   * Returns a string representation of the {@code UnsignedInteger} value, in base {@code radix}. If
252   * {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix {@code
253   * 10} is used.
254   */
255  public String toString(int radix) {
256    return UnsignedInts.toString(value, radix);
257  }
258}