23 * questions. |
23 * questions. |
24 */ |
24 */ |
25 |
25 |
26 package java.util.zip; |
26 package java.util.zip; |
27 |
27 |
|
28 import java.nio.ByteBuffer; |
|
29 import sun.nio.ch.DirectBuffer; |
|
30 |
28 /** |
31 /** |
29 * A class that can be used to compute the CRC-32 of a data stream. |
32 * A class that can be used to compute the CRC-32 of a data stream. |
|
33 * |
|
34 * <p> Passing a {@code null} argument to a method in this class will cause |
|
35 * a {@link NullPointerException} to be thrown. |
30 * |
36 * |
31 * @see Checksum |
37 * @see Checksum |
32 * @author David Connelly |
38 * @author David Connelly |
33 */ |
39 */ |
34 public |
40 public |
73 public void update(byte[] b) { |
79 public void update(byte[] b) { |
74 crc = updateBytes(crc, b, 0, b.length); |
80 crc = updateBytes(crc, b, 0, b.length); |
75 } |
81 } |
76 |
82 |
77 /** |
83 /** |
|
84 * Updates the checksum with the bytes from the specified buffer. |
|
85 * |
|
86 * The checksum is updated using |
|
87 * buffer.{@link java.nio.Buffer#remaining() remaining()} |
|
88 * bytes starting at |
|
89 * buffer.{@link java.nio.Buffer#position() position()} |
|
90 * Upon return, the buffer's position will |
|
91 * be updated to its limit; its limit will not have been changed. |
|
92 * |
|
93 * @param buffer the ByteBuffer to update the checksum with |
|
94 * @since 1.8 |
|
95 */ |
|
96 public void update(ByteBuffer buffer) { |
|
97 int pos = buffer.position(); |
|
98 int limit = buffer.limit(); |
|
99 assert (pos <= limit); |
|
100 int rem = limit - pos; |
|
101 if (rem <= 0) |
|
102 return; |
|
103 if (buffer instanceof DirectBuffer) { |
|
104 crc = updateByteBuffer(crc, ((DirectBuffer)buffer).address(), pos, rem); |
|
105 } else if (buffer.hasArray()) { |
|
106 crc = updateBytes(crc, buffer.array(), pos + buffer.arrayOffset(), rem); |
|
107 } else { |
|
108 byte[] b = new byte[rem]; |
|
109 buffer.get(b); |
|
110 crc = updateBytes(crc, b, 0, b.length); |
|
111 } |
|
112 buffer.position(limit); |
|
113 } |
|
114 |
|
115 /** |
78 * Resets CRC-32 to initial value. |
116 * Resets CRC-32 to initial value. |
79 */ |
117 */ |
80 public void reset() { |
118 public void reset() { |
81 crc = 0; |
119 crc = 0; |
82 } |
120 } |
88 return (long)crc & 0xffffffffL; |
126 return (long)crc & 0xffffffffL; |
89 } |
127 } |
90 |
128 |
91 private native static int update(int crc, int b); |
129 private native static int update(int crc, int b); |
92 private native static int updateBytes(int crc, byte[] b, int off, int len); |
130 private native static int updateBytes(int crc, byte[] b, int off, int len); |
|
131 |
|
132 private native static int updateByteBuffer(int adler, long addr, |
|
133 int off, int len); |
93 } |
134 } |