Skip to content

Commit 10898ee

Browse files
committed
Add byte transformes class and crc32 transformer
1 parent f98eb36 commit 10898ee

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package at.favre.lib.bytes;
2+
3+
import java.util.Objects;
4+
import java.util.zip.CRC32;
5+
import java.util.zip.Checksum;
6+
7+
public final class BytesTransformers {
8+
9+
private BytesTransformers() {
10+
}
11+
12+
public static BytesTransformer appendCrc32() {
13+
return new ChecksumTransformer(new CRC32(), ChecksumTransformer.Mode.APPEND, 4);
14+
}
15+
16+
/**
17+
* Adds or converts to arbitrary checksum
18+
*/
19+
final static class ChecksumTransformer implements BytesTransformer {
20+
enum Mode {
21+
/**
22+
* Appends checksum to given byte array
23+
*/
24+
APPEND,
25+
/**
26+
* Transforms byte array and returns only checksum
27+
*/
28+
TRANSFORM
29+
}
30+
31+
private final Checksum checksum;
32+
private final Mode mode;
33+
private final int checksumLengthByte;
34+
35+
public ChecksumTransformer(Checksum checksum, Mode mode, int checksumLengthByte) {
36+
if (checksumLengthByte < 0 || checksumLengthByte > 8)
37+
throw new IllegalArgumentException("checksumlength must be between 1 and 8 bytes");
38+
39+
Objects.requireNonNull(checksum, "checksum instance must not be null");
40+
this.checksum = checksum;
41+
this.mode = mode;
42+
this.checksumLengthByte = checksumLengthByte;
43+
}
44+
45+
@Override
46+
public byte[] transform(byte[] currentArray, boolean inPlace) {
47+
checksum.update(currentArray, 0, currentArray.length);
48+
byte[] checksumBytes = Bytes.from(checksum.getValue()).resize(checksumLengthByte).array();
49+
50+
if (mode == Mode.TRANSFORM) {
51+
return checksumBytes;
52+
} else {
53+
return Bytes.from(currentArray, checksumBytes).array();
54+
}
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)