Skip to main content

rocketmq_model/utils/
data_converter.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub struct DataConverter;
16
17impl DataConverter {
18    pub const CHARSET_UTF8: &'static str = "UTF-8";
19
20    pub fn long_to_bytes(v: i64) -> Vec<u8> {
21        v.to_be_bytes().to_vec()
22    }
23
24    pub fn set_bit(value: i32, index: usize, flag: bool) -> i32 {
25        assert!(index < 32, "Bit index out of range. Must be < 32.");
26        if flag {
27            value | (1 << index)
28        } else {
29            value & !(1 << index)
30        }
31    }
32
33    pub fn get_bit(value: i32, index: usize) -> bool {
34        assert!(index < 32, "Bit index out of range. Must be < 32.");
35        (value & (1 << index)) != 0
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::DataConverter;
42
43    #[test]
44    fn long_to_bytes_converts_correctly() {
45        let value: i64 = 123456789;
46        let bytes = DataConverter::long_to_bytes(value);
47        assert_eq!(bytes, value.to_be_bytes().to_vec());
48    }
49
50    #[test]
51    fn set_bit_sets_bit_correctly() {
52        let value: i32 = 0b0000_0000;
53        let result = DataConverter::set_bit(value, 3, true);
54        assert_eq!(result, 0b0000_1000);
55    }
56
57    #[test]
58    fn set_bit_clears_bit_correctly() {
59        let value: i32 = 0b0000_1000;
60        let result = DataConverter::set_bit(value, 3, false);
61        assert_eq!(result, 0b0000_0000);
62    }
63
64    #[test]
65    fn get_bit_returns_true_when_bit_is_set() {
66        let value: i32 = 0b0000_1000;
67        let result = DataConverter::get_bit(value, 3);
68        assert!(result);
69    }
70
71    #[test]
72    fn get_bit_returns_false_when_bit_is_not_set() {
73        let value: i32 = 0b0000_0000;
74        let result = DataConverter::get_bit(value, 3);
75        assert!(!result);
76    }
77}