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;
019
020import com.google.common.annotations.GwtCompatible;
021import com.google.errorprone.annotations.CanIgnoreReturnValue;
022import java.io.Serializable;
023import java.math.BigInteger;
024import org.jspecify.annotations.Nullable;
025
026/**
027 * A wrapper class for unsigned {@code long} values, supporting arithmetic operations.
028 *
029 * <p>In some cases, when speed is more important than code readability, it may be faster simply to
030 * treat primitive {@code long} values as unsigned, using the methods from {@link UnsignedLongs}.
031 *
032 * <p>See the Guava User Guide article on <a
033 * href="https://github.com/google/guava/wiki/PrimitivesExplained#unsigned-support">unsigned
034 * primitive utilities</a>.
035 *
036 * @author Louis Wasserman
037 * @author Colin Evans
038 * @since 11.0
039 */
040@GwtCompatible(serializable = true)
041public final class UnsignedLong extends Number implements Comparable<UnsignedLong>, Serializable {
042
043  private static final long UNSIGNED_MASK = 0x7fffffffffffffffL;
044
045  public static final UnsignedLong ZERO = new UnsignedLong(0);
046  public static final UnsignedLong ONE = new UnsignedLong(1);
047  public static final UnsignedLong MAX_VALUE = new UnsignedLong(-1L);
048
049  private final long value;
050
051  private UnsignedLong(long value) {
052    this.value = value;
053  }
054
055  /**
056   * Returns an {@code UnsignedLong} corresponding to a given bit representation. The argument is
057   * interpreted as an unsigned 64-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^64 + bits}.
062   *
063   * <p>To represent decimal constants less than {@code 2^63}, consider {@link #valueOf(long)}
064   * instead.
065   *
066   * @since 14.0
067   */
068  public static UnsignedLong fromLongBits(long bits) {
069    // TODO(lowasser): consider caching small values, like Long.valueOf
070    return new UnsignedLong(bits);
071  }
072
073  /**
074   * Returns an {@code UnsignedLong} representing the same value as the specified {@code long}.
075   *
076   * @throws IllegalArgumentException if {@code value} is negative
077   * @since 14.0
078   */
079  @CanIgnoreReturnValue
080  public static UnsignedLong valueOf(long value) {
081    checkArgument(value >= 0, "value (%s) is outside the range for an unsigned long value", value);
082    return fromLongBits(value);
083  }
084
085  /**
086   * Returns a {@code UnsignedLong} representing the same value as the specified {@code BigInteger}.
087   * This is the inverse operation of {@link #bigIntegerValue()}.
088   *
089   * @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^64}
090   */
091  @CanIgnoreReturnValue
092  public static UnsignedLong valueOf(BigInteger value) {
093    checkNotNull(value);
094    checkArgument(
095        value.signum() >= 0 && value.bitLength() <= Long.SIZE,
096        "value (%s) is outside the range for an unsigned long value",
097        value);
098    return fromLongBits(value.longValue());
099  }
100
101  /**
102   * Returns an {@code UnsignedLong} holding the value of the specified {@code String}, parsed as an
103   * unsigned {@code long} value.
104   *
105   * @throws NumberFormatException if the string does not contain a parsable unsigned {@code long}
106   *     value
107   */
108  @CanIgnoreReturnValue
109  public static UnsignedLong valueOf(String string) {
110    return valueOf(string, 10);
111  }
112
113  /**
114   * Returns an {@code UnsignedLong} holding the value of the specified {@code String}, parsed as an
115   * unsigned {@code long} value in the specified radix.
116   *
117   * @throws NumberFormatException if the string does not contain a parsable unsigned {@code long}
118   *     value, or {@code radix} is not between {@link Character#MIN_RADIX} and {@link
119   *     Character#MAX_RADIX}
120   */
121  @CanIgnoreReturnValue
122  public static UnsignedLong valueOf(String string, int radix) {
123    return fromLongBits(UnsignedLongs.parseUnsignedLong(string, radix));
124  }
125
126  /**
127   * Returns the result of adding this and {@code val}. If the result would have more than 64 bits,
128   * returns the low 64 bits of the result.
129   *
130   * @since 14.0
131   */
132  public UnsignedLong plus(UnsignedLong val) {
133    return fromLongBits(this.value + checkNotNull(val).value);
134  }
135
136  /**
137   * Returns the result of subtracting this and {@code val}. If the result would have more than 64
138   * bits, returns the low 64 bits of the result.
139   *
140   * @since 14.0
141   */
142  public UnsignedLong minus(UnsignedLong val) {
143    return fromLongBits(this.value - checkNotNull(val).value);
144  }
145
146  /**
147   * Returns the result of multiplying this and {@code val}. If the result would have more than 64
148   * bits, returns the low 64 bits of the result.
149   *
150   * @since 14.0
151   */
152  public UnsignedLong times(UnsignedLong val) {
153    return fromLongBits(value * checkNotNull(val).value);
154  }
155
156  /**
157   * Returns the result of dividing this by {@code val}.
158   *
159   * @since 14.0
160   */
161  public UnsignedLong dividedBy(UnsignedLong val) {
162    return fromLongBits(UnsignedLongs.divide(value, checkNotNull(val).value));
163  }
164
165  /**
166   * Returns this modulo {@code val}.
167   *
168   * @since 14.0
169   */
170  public UnsignedLong mod(UnsignedLong val) {
171    return fromLongBits(UnsignedLongs.remainder(value, checkNotNull(val).value));
172  }
173
174  /** Returns the value of this {@code UnsignedLong} as an {@code int}. */
175  @Override
176  public int intValue() {
177    return (int) value;
178  }
179
180  /**
181   * Returns the value of this {@code UnsignedLong} as a {@code long}. This is an inverse operation
182   * to {@link #fromLongBits}.
183   *
184   * <p>Note that if this {@code UnsignedLong} holds a value {@code >= 2^63}, the returned value
185   * will be equal to {@code this - 2^64}.
186   */
187  @Override
188  public long longValue() {
189    return value;
190  }
191
192  /**
193   * Returns the value of this {@code UnsignedLong} as a {@code float}, analogous to a widening
194   * primitive conversion from {@code long} to {@code float}, and correctly rounded.
195   */
196  @Override
197  public float floatValue() {
198    if (value >= 0) {
199      return (float) value;
200    }
201    // The top bit is set, which means that the float value is going to come from the top 24 bits.
202    // So we can ignore the bottom 8, except for rounding. See doubleValue() for more.
203    return (float) ((value >>> 1) | (value & 1)) * 2f;
204  }
205
206  /**
207   * Returns the value of this {@code UnsignedLong} as a {@code double}, analogous to a widening
208   * primitive conversion from {@code long} to {@code double}, and correctly rounded.
209   */
210  @Override
211  public double doubleValue() {
212    if (value >= 0) {
213      return (double) value;
214    }
215    // The top bit is set, which means that the double value is going to come from the top 53 bits.
216    // So we can ignore the bottom 11, except for rounding. We can unsigned-shift right 1, aka
217    // unsigned-divide by 2, and convert that. Then we'll get exactly half of the desired double
218    // value. But in the specific case where the bottom two bits of the original number are 01, we
219    // want to replace that with 1 in the shifted value for correct rounding.
220    return (double) ((value >>> 1) | (value & 1)) * 2.0;
221  }
222
223  /** Returns the value of this {@code UnsignedLong} as a {@link BigInteger}. */
224  public BigInteger bigIntegerValue() {
225    BigInteger bigInt = BigInteger.valueOf(value & UNSIGNED_MASK);
226    if (value < 0) {
227      bigInt = bigInt.setBit(Long.SIZE - 1);
228    }
229    return bigInt;
230  }
231
232  @Override
233  public int compareTo(UnsignedLong o) {
234    checkNotNull(o);
235    return UnsignedLongs.compare(value, o.value);
236  }
237
238  @Override
239  public int hashCode() {
240    return Longs.hashCode(value);
241  }
242
243  @Override
244  public boolean equals(@Nullable Object obj) {
245    if (obj instanceof UnsignedLong) {
246      UnsignedLong other = (UnsignedLong) obj;
247      return value == other.value;
248    }
249    return false;
250  }
251
252  /** Returns a string representation of the {@code UnsignedLong} value, in base 10. */
253  @Override
254  public String toString() {
255    return UnsignedLongs.toString(value);
256  }
257
258  /**
259   * Returns a string representation of the {@code UnsignedLong} value, in base {@code radix}. If
260   * {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix {@code
261   * 10} is used.
262   */
263  public String toString(int radix) {
264    return UnsignedLongs.toString(value, radix);
265  }
266}