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