fast_able/
fasttime.rs

1// fasttime module, extending chrono time functionality
2// fasttime 模块,扩展 chrono 时间功能
3
4/// Microsecond related constants and utility functions
5/// 微秒相关的常量和工具函数
6pub mod a8_micros {
7    /// Microseconds per millisecond
8    /// 一毫秒的微秒数
9    pub const MICROS_PER_MILLIS: u64 = 1_000;
10}
11
12/// Extension methods for NaiveTime
13/// 为 NaiveTime 添加扩展方法
14pub mod b2_time {
15    use chrono::{Timelike, NaiveTime};
16    
17    /// Extension methods for NaiveTime
18    /// 为 NaiveTime 添加的扩展方法
19    pub trait TimeExt {
20        /// Get microseconds of the day
21        /// 获取微秒值
22        fn micros_of_day(&self) -> u64;
23        
24        /// Create time from microseconds
25        /// 从微秒创建时间
26        fn from_micros_day_unsafe(micros: u64) -> NaiveTime;
27        
28        /// Create time from hours, minutes, seconds, milliseconds
29        /// 从小时、分钟、秒、毫秒创建时间
30        fn from_hmsi_friendly_unsafe(millis: u64) -> NaiveTime;
31
32        fn hour_minute(&self) -> u32;
33        
34        fn to_string6(&self) -> String;
35
36        fn to_string3(&self) -> String;
37    }
38    
39    impl TimeExt for NaiveTime {
40        fn micros_of_day(&self) -> u64 {
41            // 计算当日微秒数,使用 Timelike trait 的公开方法
42            let hour = self.hour() as u64;
43            let minute = self.minute() as u64;
44            let second = self.second() as u64;
45            let nano = self.nanosecond() as u64; // 公开的 nanosecond 方法
46            let micro = nano / 1000; // 纳秒转微秒
47            
48            (hour * 3600 + minute * 60 + second) * 1_000_000 + micro
49        }
50        
51        fn from_micros_day_unsafe(micros: u64) -> NaiveTime {
52            let seconds = (micros / 1_000_000) as u32;
53            let micros_remainder = (micros % 1_000_000) as u32;
54            let nanos = micros_remainder * 1000; // 微秒转纳秒
55            
56            let hours = seconds / 3600;
57            let minutes = (seconds % 3600) / 60;
58            let seconds = seconds % 60;
59            
60            NaiveTime::from_hms_nano_opt(hours, minutes, seconds, nanos).unwrap_or_default()
61        }
62        
63        fn from_hmsi_friendly_unsafe(millis: u64) -> NaiveTime {
64            let micros = millis * crate::fasttime::a8_micros::MICROS_PER_MILLIS;
65            Self::from_micros_day_unsafe(micros)
66        }
67
68        fn hour_minute(&self) -> u32 {
69            self.hour() * 100 + self.minute()
70        }
71
72        fn to_string6(&self) -> String {
73            self.format("%H:%M:%S.%6f").to_string()
74        }
75        
76        fn to_string3(&self) -> String {
77            self.format("%H:%M:%S.%3f").to_string()
78        }
79    }
80}