1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 package java.util.zip;
19 
20 import java.util.Arrays;
21 
22 /**
23  * The CRC32 class is used to compute a CRC32 checksum from data provided as
24  * input value. See also {@link Adler32} which is almost as good, but cheaper.
25  */
26 public class CRC32 implements Checksum {
27 
28     private long crc = 0L;
29 
30     long tbytes = 0L;
31 
32     /**
33      * Returns the CRC32 checksum for all input received.
34      *
35      * @return The checksum for this instance.
36      */
getValue()37     public long getValue() {
38         return crc;
39     }
40 
41     /**
42      * Resets the CRC32 checksum to it initial state.
43      */
reset()44     public void reset() {
45         tbytes = crc = 0;
46 
47     }
48 
49     /**
50      * Updates this checksum with the byte value provided as integer.
51      *
52      * @param val
53      *            represents the byte to update the checksum.
54      */
update(int val)55     public void update(int val) {
56         crc = updateByteImpl((byte) val, crc);
57     }
58 
59     /**
60      * Updates this checksum with the bytes contained in buffer {@code buf}.
61      *
62      * @param buf
63      *            the buffer holding the data to update the checksum with.
64      */
update(byte[] buf)65     public void update(byte[] buf) {
66         update(buf, 0, buf.length);
67     }
68 
69     /**
70      * Update this {@code CRC32} checksum with the contents of {@code buf},
71      * starting from {@code offset} and reading {@code byteCount} bytes of data.
72      */
update(byte[] buf, int offset, int byteCount)73     public void update(byte[] buf, int offset, int byteCount) {
74         Arrays.checkOffsetAndCount(buf.length, offset, byteCount);
75         tbytes += byteCount;
76         crc = updateImpl(buf, offset, byteCount, crc);
77     }
78 
updateImpl(byte[] buf, int offset, int byteCount, long crc1)79     private native long updateImpl(byte[] buf, int offset, int byteCount, long crc1);
80 
updateByteImpl(byte val, long crc1)81     private native long updateByteImpl(byte val, long crc1);
82 }
83