rocketmq_common/utils/
crc32_utils.rs

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