1 unstable release
0.1.0 | Jul 7, 2024 |
---|
#1544 in Data structures
11KB
107 lines
We generally use the 64-bit type to represent second-level UNIX timestamps. This provides an extremely large range, exceeding 29.2 billion years. This is a waste in scenarios sensitive to memory usage. Using a 32-bit type, however, allows for a range of 136 years, which is sufficient for most applications. Yet, considering UNIX timestamps start from 1970, this range spans from 1970 to 2106. The year 2106 doesn't seem very distant, potentially causing overflow issues.
If we can specify a starting time, such as the release time of the application, we can bypass the limitation of 1970. For example, if an application releases in 2024 and we only need timestamps from 2024 onwards, then by using 2024 as the starting point, we can represent a range from 2024 to 2160. Here 2160 seems much more distant and safe.
This crate provides such a simple encapsulation by specifying a starting year and using a 32-bit type to represent timestamps.
As time passes, the value of this crate will become increasingly evident.
Examples
use epoch32::Epoch32;
type MyEpoch = Epoch32<2024>; // 2024-2160
assert_eq!(std::mem::size_of::<MyEpoch>(), 4); // 32-bits
println!("{}", MyEpoch::now()); // get current time, and show as UNIX Epoch
let ts1 = MyEpoch::try_from_unix_epoch(1719403339).unwrap(); // convert from UNIX Epoch
assert_eq!(ts1.to_unix_epoch(), 1719403339); // convert to UNIX Epoch
let ts2 = MyEpoch::try_from_unix_epoch(1719403349).unwrap();
let tensecs = std::time::Duration::from_secs(10);
assert!(ts1 < ts2); // compare
assert_eq!(ts1 + tensecs, ts2); // add duration
assert_eq!(ts2.duration_since(ts1), Some(tensecs)); // calulate diff duration
println!("{} {}", ts1, ts2);
Features
serde
enables serde traits integration (Serialize
/Deserialize
)
Dependencies
~165KB