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 package org.apache.commons.imaging.formats.png;
18
19 // should just use ints, not longs
20 final class PngCrc {
21
22 /* Table of CRCs of all 8-bit messages. */
23 private final long[] crcTable = new long[256];
24
25 /* Flag: has the table been computed? Initially false. */
26 private boolean crcTableComputed;
27
28 public long continuePartialCrc(final long oldCrc, final byte[] buf, final int len) {
29 return updateCrc(oldCrc, buf);
30 }
31
32 /*
33 * Update a running CRC with the bytes buf[0..len-1]--the CRC should be initialized to all 1's, and the transmitted value is the 1's complement of the final
34 * running CRC (see the crc() routine below)).
35 */
36
37 /* Gets the CRC of the bytes buf[0..len-1]. */
38 public int crc(final byte[] buf, final int len) {
39 return (int) (updateCrc(0xffffffffL, buf) ^ 0xffffffffL);
40 }
41
42 public long finishPartialCrc(final long oldCrc) {
43 return oldCrc ^ 0xffffffffL;
44 }
45
46 /* Make the table for a fast CRC. */
47 private void makeCrcTable() {
48 long c;
49 int n;
50 int k;
51
52 for (n = 0; n < 256; n++) {
53 c = n;
54 for (k = 0; k < 8; k++) {
55 if ((c & 1) != 0) {
56 c = 0xedb88320L ^ c >> 1;
57 } else {
58 c = c >> 1;
59 }
60 }
61 crcTable[n] = c;
62 }
63 crcTableComputed = true;
64 }
65
66 public long startPartialCrc(final byte[] buf, final int len) {
67 return updateCrc(0xffffffffL, buf);
68 }
69
70 private long updateCrc(final long crc, final byte[] buf) {
71 long c = crc;
72 int n;
73
74 if (!crcTableComputed) {
75 makeCrcTable();
76 }
77 for (n = 0; n < buf.length; n++) {
78 // Debug.debug("crc[" + n + "]", c + " (" + Long.toHexString(c) +
79 // ")");
80
81 c = crcTable[(int) ((c ^ buf[n]) & 0xff)] ^ c >> 8;
82 }
83 return c;
84 }
85 }