Skip to main content

pcapfile_io/foundation/
utils.rs

1use chrono::{DateTime, Datelike, Local, Timelike, Utc};
2
3/// 字节数组扩展方法
4pub trait ByteArrayExtensions {
5    /// 获取字节数组的子数组
6    fn sub_array(
7        &self,
8        start_index: usize,
9        length: usize,
10    ) -> Result<Vec<u8>, String>;
11
12    /// 将字节数组转换为十六进制字符串
13    fn to_hex_string(&self, separator: &str) -> String;
14
15    /// 将字节数组转换为Base64字符串
16    fn to_base64_string(&self) -> String;
17
18    /// 将字节数组转换为UTF8字符串
19    fn to_utf8_string(&self) -> Result<String, String>;
20
21    /// 比较两个字节数组是否相等
22    fn equals(&self, other: &[u8]) -> bool;
23
24    /// 计算字节数组的哈希值
25    fn get_hash_code(&self) -> u32;
26}
27
28impl ByteArrayExtensions for [u8] {
29    fn sub_array(
30        &self,
31        start_index: usize,
32        length: usize,
33    ) -> Result<Vec<u8>, String> {
34        if start_index >= self.len() {
35            return Err("起始索引超出范围".to_string());
36        }
37
38        if start_index + length > self.len() {
39            return Err("长度超出范围".to_string());
40        }
41
42        Ok(self[start_index..start_index + length].to_vec())
43    }
44
45    fn to_hex_string(&self, separator: &str) -> String {
46        if self.is_empty() {
47            return String::new();
48        }
49
50        let mut result = String::with_capacity(
51            self.len() * (2 + separator.len()),
52        );
53        for (i, &byte) in self.iter().enumerate() {
54            if i > 0 && !separator.is_empty() {
55                result.push_str(separator);
56            }
57            result.push_str(&format!("{byte:02x}"))
58        }
59        result
60    }
61
62    fn to_base64_string(&self) -> String {
63        base64::Engine::encode(
64            &base64::engine::general_purpose::STANDARD,
65            self,
66        )
67    }
68
69    fn to_utf8_string(&self) -> Result<String, String> {
70        String::from_utf8(self.to_vec())
71            .map_err(|e| format!("UTF8解码失败: {e}"))
72    }
73
74    fn equals(&self, other: &[u8]) -> bool {
75        self.len() == other.len()
76            && self
77                .iter()
78                .zip(other.iter())
79                .all(|(a, b)| a == b)
80    }
81
82    fn get_hash_code(&self) -> u32 {
83        let mut hash = 17u32;
84        for &byte in self {
85            hash = hash
86                .wrapping_mul(31)
87                .wrapping_add(byte as u32);
88        }
89        hash
90    }
91}
92
93/// DateTime扩展方法
94pub trait DateTimeExtensions {
95    /// 将 DateTime 转换为 Unix 时间戳(毫秒)
96    fn to_unix_time_milliseconds(&self) -> i64;
97
98    /// 将 Unix 时间戳(毫秒)转换为 DateTime
99    fn from_unix_time_milliseconds(
100        milliseconds: i64,
101    ) -> DateTime<Utc>;
102
103    /// 将 DateTime 转换为 Unix 时间戳(秒)
104    fn to_unix_time_seconds(&self) -> u32;
105
106    /// 获取 DateTime 的纳秒部分
107    fn get_nanoseconds(&self) -> u32;
108
109    /// 将 Unix 时间戳(秒)和纳秒部分转换为 DateTime
110    fn from_unix_time_with_nanoseconds(
111        seconds: u32,
112        nanoseconds: u32,
113    ) -> DateTime<Utc>;
114
115    /// 将时间转换为文件名格式字符串
116    /// 格式: yyMMdd_HHmmss_nnnnnnnnn (9位纳秒)
117    fn to_filename_string(&self) -> String;
118}
119
120impl DateTimeExtensions for DateTime<Utc> {
121    #[inline]
122    fn to_unix_time_milliseconds(&self) -> i64 {
123        self.timestamp_millis()
124    }
125
126    #[inline]
127    fn from_unix_time_milliseconds(
128        milliseconds: i64,
129    ) -> DateTime<Utc> {
130        DateTime::from_timestamp_millis(milliseconds)
131            .unwrap_or_else(|| {
132                // 如果时间戳无效,返回当前时间
133                Utc::now()
134            })
135    }
136
137    #[inline]
138    fn to_unix_time_seconds(&self) -> u32 {
139        self.timestamp() as u32
140    }
141
142    #[inline]
143    fn get_nanoseconds(&self) -> u32 {
144        self.nanosecond()
145    }
146
147    fn from_unix_time_with_nanoseconds(
148        seconds: u32,
149        nanoseconds: u32,
150    ) -> DateTime<Utc> {
151        DateTime::from_timestamp(
152            seconds as i64,
153            nanoseconds,
154        )
155        .unwrap_or_else(|| {
156            // 如果时间戳无效,返回当前时间
157            Utc::now()
158        })
159    }
160
161    fn to_filename_string(&self) -> String {
162        let local_time: DateTime<Local> = (*self).into();
163
164        let year = local_time.year() % 100; // 取年份后两位
165        let month = local_time.month();
166        let day = local_time.day();
167        let hour = local_time.hour();
168        let minute = local_time.minute();
169        let second = local_time.second();
170        let nanosecond = local_time.nanosecond(); // 完整的9位纳秒
171
172        format!("{year:02}{month:02}{day:02}_{hour:02}{minute:02}{second:02}_{nanosecond:09}")
173    }
174}
175
176/// 计算CRC32校验和
177#[inline]
178pub fn calculate_crc32(data: &[u8]) -> u32 {
179    use crc32fast::Hasher;
180
181    let mut hasher = Hasher::new();
182    hasher.update(data);
183    hasher.finalize()
184}
185
186/// 二进制转换工具
187pub mod binary_converter {
188    /// 从字节数组读取小端序整数
189    pub fn read_le_u32(
190        bytes: &[u8],
191        offset: usize,
192    ) -> Result<u32, String> {
193        if offset + 4 > bytes.len() {
194            return Err("字节数组长度不足".to_string());
195        }
196
197        Ok(u32::from_le_bytes([
198            bytes[offset],
199            bytes[offset + 1],
200            bytes[offset + 2],
201            bytes[offset + 3],
202        ]))
203    }
204
205    /// 从字节数组读取小端序16位整数
206    pub fn read_le_u16(
207        bytes: &[u8],
208        offset: usize,
209    ) -> Result<u16, String> {
210        if offset + 2 > bytes.len() {
211            return Err("字节数组长度不足".to_string());
212        }
213
214        Ok(u16::from_le_bytes([
215            bytes[offset],
216            bytes[offset + 1],
217        ]))
218    }
219
220    /// 将整数写入字节数组(小端序)
221    pub fn write_le_u32(
222        bytes: &mut [u8],
223        offset: usize,
224        value: u32,
225    ) -> Result<(), String> {
226        if offset + 4 > bytes.len() {
227            return Err("字节数组长度不足".to_string());
228        }
229
230        let value_bytes = value.to_le_bytes();
231        bytes[offset..offset + 4]
232            .copy_from_slice(&value_bytes);
233        Ok(())
234    }
235
236    /// 将16位整数写入字节数组(小端序)
237    pub fn write_le_u16(
238        bytes: &mut [u8],
239        offset: usize,
240        value: u16,
241    ) -> Result<(), String> {
242        if offset + 2 > bytes.len() {
243            return Err("字节数组长度不足".to_string());
244        }
245
246        let value_bytes = value.to_le_bytes();
247        bytes[offset..offset + 2]
248            .copy_from_slice(&value_bytes);
249        Ok(())
250    }
251
252    /// 将字符串转换为UTF8字节数组
253    pub fn string_to_utf8_bytes(s: &str) -> Vec<u8> {
254        s.as_bytes().to_vec()
255    }
256
257    /// 从UTF8字节数组转换为字符串
258    pub fn utf8_bytes_to_string(
259        bytes: &[u8],
260    ) -> Result<String, String> {
261        String::from_utf8(bytes.to_vec())
262            .map_err(|e| format!("UTF8解码失败: {e}"))
263    }
264
265    /// 将字节数组转换为Base64字符串
266    pub fn bytes_to_base64(bytes: &[u8]) -> String {
267        base64::Engine::encode(
268            &base64::engine::general_purpose::STANDARD,
269            bytes,
270        )
271    }
272
273    /// 从Base64字符串转换为字节数组
274    pub fn base64_to_bytes(
275        base64_str: &str,
276    ) -> Result<Vec<u8>, String> {
277        base64::Engine::decode(
278            &base64::engine::general_purpose::STANDARD,
279            base64_str,
280        )
281        .map_err(|e| format!("Base64解码失败: {e}"))
282    }
283}