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