1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.compression;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.util.ByteProcessor;
20 import io.netty.util.internal.ObjectUtil;
21
22 import java.nio.ByteBuffer;
23 import java.util.zip.Adler32;
24 import java.util.zip.CRC32;
25 import java.util.zip.Checksum;
26
27
28
29
30
31
32
33 abstract class ByteBufChecksum implements Checksum {
34 private final ByteProcessor updateProcessor = new ByteProcessor() {
35 @Override
36 public boolean process(byte value) throws Exception {
37 update(value);
38 return true;
39 }
40 };
41
42 static ByteBufChecksum wrapChecksum(Checksum checksum) {
43 ObjectUtil.checkNotNull(checksum, "checksum");
44 if (checksum instanceof ByteBufChecksum) {
45 return (ByteBufChecksum) checksum;
46 }
47 return new JdkByteBufChecksum(checksum);
48 }
49
50
51
52
53 public void update(ByteBuf b, int off, int len) {
54 if (b.hasArray()) {
55 update(b.array(), b.arrayOffset() + off, len);
56 } else {
57 b.forEachByte(off, len, updateProcessor);
58 }
59 }
60
61 private static class JdkByteBufChecksum extends ByteBufChecksum {
62 protected final Checksum checksum;
63
64 JdkByteBufChecksum(Checksum checksum) {
65 this.checksum = checksum;
66 }
67
68 @Override
69 public void update(int b) {
70 checksum.update(b);
71 }
72
73 @Override
74 public void update(ByteBuf b, int off, int len) {
75 if (b.hasArray()) {
76 update(b.array(), b.arrayOffset() + off, len);
77 } else if (checksum instanceof CRC32) {
78 ByteBuffer byteBuffer = CompressionUtil.safeNioBuffer(b, off, len);
79 ((CRC32) checksum).update(byteBuffer);
80 } else if (checksum instanceof Adler32) {
81 ByteBuffer byteBuffer = CompressionUtil.safeNioBuffer(b, off, len);
82 ((Adler32) checksum).update(byteBuffer);
83 } else {
84 super.update(b, off, len);
85 }
86 }
87
88 @Override
89 public void update(byte[] b, int off, int len) {
90 checksum.update(b, off, len);
91 }
92
93 @Override
94 public long getValue() {
95 return checksum.getValue();
96 }
97
98 @Override
99 public void reset() {
100 checksum.reset();
101 }
102 }
103 }