Skip to content

Commit 454bd01

Browse files
committed
add
1 parent fb312a3 commit 454bd01

File tree

1 file changed

+67
-26
lines changed

1 file changed

+67
-26
lines changed

rocketmq-common/src/utils/crc32_utils.rs

+67-26
Original file line numberDiff line numberDiff line change
@@ -15,30 +15,71 @@
1515
* limitations under the License.
1616
*/
1717

18-
use crc32fast::Hasher;
18+
use crc32fast::Hasher;
1919

20-
// Calculate the CRC32 checksum for the given byte array
21-
pub fn crc32(buf: &[u8]) -> u32 {
22-
//crc32fast::hash(buf)
23-
let mut hasher = Hasher::new();
24-
hasher.update(buf);
25-
let checksum = hasher.finalize();
26-
checksum & 0x7FFFFFFF
27-
}
28-
29-
#[cfg(test)]
30-
mod tests {
31-
use super::*;
32-
33-
#[test]
34-
fn test_crc32_negative() {
35-
let buf = [1, 2, 3, 4, 5];
36-
assert_ne!(crc32(&buf), 0xFFFFFFFF);
37-
}
38-
39-
#[test]
40-
fn test_crc32_empty_buffer() {
41-
let buf: [u8; 0] = [];
42-
assert_eq!(crc32(&buf), 0);
43-
}
44-
}
20+
// Calculate the CRC32 checksum for the given byte array
21+
pub fn crc32(buf: &[u8]) -> u32 {
22+
//crc32fast::hash(buf)
23+
let mut hasher = Hasher::new();
24+
hasher.update(buf);
25+
hasher.finalize()
26+
}
27+
28+
pub fn crc32_bytes_offset(array: &[u8], offset: usize, length: usize) -> u32 {
29+
if !array.is_empty() && offset < array.len() && offset + length <= array.len() {
30+
let mut hasher = Hasher::new();
31+
hasher.update(&array[offset..offset + length]);
32+
return hasher.finalize();
33+
}
34+
0
35+
}
36+
37+
pub fn crc32_bytebuffer(byte_buffer: &mut Vec<u8>) -> u32 {
38+
let mut hasher = Hasher::new();
39+
hasher.update(byte_buffer.as_slice());
40+
hasher.finalize()
41+
}
42+
43+
pub fn crc32_bytebuffers(byte_buffers: &mut Vec<Vec<u8>>) -> u32 {
44+
let mut hasher = Hasher::new();
45+
for buffer in byte_buffers {
46+
hasher.update(buffer.as_slice());
47+
}
48+
hasher.finalize()
49+
}
50+
51+
#[cfg(test)]
52+
mod tests {
53+
use super::*;
54+
55+
#[test]
56+
fn crc32_calculates_correct_checksum() {
57+
let buf = [1, 2, 3, 4, 5];
58+
assert_eq!(crc32(&buf), 1191942644);
59+
}
60+
61+
#[test]
62+
fn crc32_bytes_offset_calculates_correct_checksum() {
63+
let buf = [1, 2, 3, 4, 5];
64+
assert_eq!(crc32_bytes_offset(&buf, 1, 3), 3498416806);
65+
}
66+
67+
#[test]
68+
fn crc32_bytes_offset_returns_zero_for_empty_array() {
69+
let buf: [u8; 0] = [];
70+
assert_eq!(crc32_bytes_offset(&buf, 0, 0), 0);
71+
}
72+
73+
#[test]
74+
fn crc32_bytebuffer_calculates_correct_checksum() {
75+
let mut buf = vec![1, 2, 3, 4, 5];
76+
assert_eq!(crc32_bytebuffer(&mut buf), 1191942644);
77+
}
78+
79+
#[test]
80+
fn crc32_bytebuffers_calculates_correct_checksum() {
81+
let mut bufs = vec![vec![1, 2, 3], vec![4, 5]];
82+
assert_eq!(crc32_bytebuffers(&mut bufs), 1191942644);
83+
}
84+
}
85+

0 commit comments

Comments
 (0)