1 /** 2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 * SPDX-License-Identifier: Apache-2.0. 4 */ 5 package software.amazon.awssdk.crt.checksums; 6 7 import software.amazon.awssdk.crt.CRT; 8 import java.util.zip.Checksum; 9 10 /** 11 * CRT implementation of the Java Checksum interface for making Crc32c checksum calculations 12 */ 13 public class CRC32C implements Checksum, Cloneable { 14 static { CRT()15 new CRT(); 16 }; 17 private int value = 0; 18 19 /** 20 * Default constructor 21 */ CRC32C()22 public CRC32C() { 23 } 24 CRC32C(int value)25 private CRC32C(int value) { 26 this.value = value; 27 } 28 29 @Override clone()30 public Object clone() { 31 return new CRC32C(value); 32 } 33 34 /** 35 * Returns the current checksum value. 36 * 37 * @return the current checksum value. 38 */ 39 @Override getValue()40 public long getValue() { 41 return (long) value & 0xffffffffL; 42 } 43 44 /** 45 * Resets the checksum to its initial value. 46 */ 47 @Override reset()48 public void reset() { 49 value = 0; 50 } 51 52 /** 53 * Updates the current checksum with the specified array of bytes. 54 * 55 * @param b the byte array to update the checksum with 56 * @param off the starting offset within b of the data to use 57 * @param len the number of bytes to use in the update 58 */ 59 @Override update(byte[] b, int off, int len)60 public void update(byte[] b, int off, int len) { 61 if (b == null) { 62 throw new NullPointerException(); 63 } 64 if (off < 0 || len < 0 || off > b.length - len) { 65 throw new ArrayIndexOutOfBoundsException(); 66 } 67 value = crc32c(b, value, off, len); 68 } 69 update(byte[] b)70 public void update(byte[] b) { 71 value = crc32c(b, value, 0, b.length); 72 } 73 74 @Override update(int b)75 public void update(int b) { 76 if (b < 0 || b > 0xff) { 77 throw new IllegalArgumentException(); 78 } 79 byte[] buf = { (byte) (b & 0x000000ff) }; 80 this.update(buf); 81 } 82 83 /******************************************************************************* 84 * native methods 85 ******************************************************************************/ crc32c(byte[] input, int previous, int offset, int length)86 private static native int crc32c(byte[] input, int previous, int offset, int length); 87 } 88