package com.google.common.hash;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.zip.Checksum;
@Immutable
final class ChecksumHashFunction extends AbstractHashFunction implements Serializable {
private final ImmutableSupplier<? extends Checksum> checksumSupplier;
private final int bits;
private final String toString;
ChecksumHashFunction(
ImmutableSupplier<? extends Checksum> checksumSupplier, int bits, String toString) {
this.checksumSupplier = checkNotNull(checksumSupplier);
checkArgument(bits == 32 || bits == 64, "bits (%s) must be either 32 or 64", bits);
this.bits = bits;
this.toString = checkNotNull(toString);
}
@Override
public int bits() {
return bits;
}
@Override
public Hasher newHasher() {
return new ChecksumHasher(checksumSupplier.get());
}
@Override
public String toString() {
return toString;
}
private final class ChecksumHasher extends AbstractByteHasher {
private final Checksum checksum;
private ChecksumHasher(Checksum checksum) {
this.checksum = checkNotNull(checksum);
}
@Override
protected void update(byte b) {
checksum.update(b);
}
@Override
protected void update(byte[] bytes, int off, int len) {
checksum.update(bytes, off, len);
}
@Override
public HashCode hash() {
long value = checksum.getValue();
if (bits == 32) {
return HashCode.fromInt((int) value);
} else {
return HashCode.fromLong(value);
}
}
}
private static final long serialVersionUID = 0L;
}