pcapfile_io/foundation/
utils.rs1use chrono::{DateTime, Datelike, Local, Timelike, Utc};
2
3pub trait ByteArrayExtensions {
5 fn sub_array(
7 &self,
8 start_index: usize,
9 length: usize,
10 ) -> Result<Vec<u8>, String>;
11
12 fn to_hex_string(&self, separator: &str) -> String;
14
15 fn to_base64_string(&self) -> String;
17
18 fn to_utf8_string(&self) -> Result<String, String>;
20
21 fn equals(&self, other: &[u8]) -> bool;
23
24 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
93pub trait DateTimeExtensions {
95 fn to_unix_time_milliseconds(&self) -> i64;
97
98 fn from_unix_time_milliseconds(
100 milliseconds: i64,
101 ) -> DateTime<Utc>;
102
103 fn to_unix_time_seconds(&self) -> u32;
105
106 fn get_nanoseconds(&self) -> u32;
108
109 fn from_unix_time_with_nanoseconds(
111 seconds: u32,
112 nanoseconds: u32,
113 ) -> DateTime<Utc>;
114
115 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 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 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; 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(); format!("{year:02}{month:02}{day:02}_{hour:02}{minute:02}{second:02}_{nanosecond:09}")
173 }
174}
175
176#[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
186pub mod binary_converter {
188 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 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 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 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 pub fn string_to_utf8_bytes(s: &str) -> Vec<u8> {
254 s.as_bytes().to_vec()
255 }
256
257 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 pub fn bytes_to_base64(bytes: &[u8]) -> String {
267 base64::Engine::encode(
268 &base64::engine::general_purpose::STANDARD,
269 bytes,
270 )
271 }
272
273 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}