rocketmq_common/utils/
data_converter.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 */
17use std::sync::atomic::AtomicI32;
18use std::sync::atomic::Ordering;
19use std::sync::Arc;
20
21pub struct DataConverter;
22
23impl DataConverter {
24    pub const CHARSET_UTF8: &'static str = "UTF-8";
25
26    pub fn long_to_bytes(v: i64) -> Vec<u8> {
27        v.to_be_bytes().to_vec()
28    }
29
30    pub fn set_bit(value: i32, index: usize, flag: bool) -> i32 {
31        assert!(index < 32, "Bit index out of range. Must be < 32.");
32        if flag {
33            value | (1 << index)
34        } else {
35            value & !(1 << index)
36        }
37    }
38
39    pub fn get_bit(value: i32, index: usize) -> bool {
40        assert!(index < 32, "Bit index out of range. Must be < 32.");
41        (value & (1 << index)) != 0
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::DataConverter;
48
49    #[test]
50    fn long_to_bytes_converts_correctly() {
51        let value: i64 = 123456789;
52        let bytes = DataConverter::long_to_bytes(value);
53        assert_eq!(bytes, value.to_be_bytes().to_vec());
54    }
55
56    #[test]
57    fn set_bit_sets_bit_correctly() {
58        let value: i32 = 0b0000_0000;
59        let result = DataConverter::set_bit(value, 3, true);
60        assert_eq!(result, 0b0000_1000);
61    }
62
63    #[test]
64    fn set_bit_clears_bit_correctly() {
65        let value: i32 = 0b0000_1000;
66        let result = DataConverter::set_bit(value, 3, false);
67        assert_eq!(result, 0b0000_0000);
68    }
69
70    #[test]
71    fn get_bit_returns_true_when_bit_is_set() {
72        let value: i32 = 0b0000_1000;
73        let result = DataConverter::get_bit(value, 3);
74        assert!(result);
75    }
76
77    #[test]
78    fn get_bit_returns_false_when_bit_is_not_set() {
79        let value: i32 = 0b0000_0000;
80        let result = DataConverter::get_bit(value, 3);
81        assert!(!result);
82    }
83}