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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
//! DateTime types with specific serialization invariants.
use std::{
fmt,
num::{ParseIntError, TryFromIntError},
str::FromStr,
};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use chrono::{TimeZone, Utc};
use crate::serialization::{SerializationError, ZcashDeserialize, ZcashSerialize};
/// A date and time, represented by a 32-bit number of seconds since the UNIX epoch.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct DateTime32 {
timestamp: u32,
}
/// An unsigned time duration, represented by a 32-bit number of seconds.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Duration32 {
seconds: u32,
}
impl DateTime32 {
/// The earliest possible `DateTime32` value.
pub const MIN: DateTime32 = DateTime32 {
timestamp: u32::MIN,
};
/// The latest possible `DateTime32` value.
pub const MAX: DateTime32 = DateTime32 {
timestamp: u32::MAX,
};
/// Returns the number of seconds since the UNIX epoch.
pub fn timestamp(&self) -> u32 {
self.timestamp
}
/// Returns the equivalent [`chrono::DateTime`].
pub fn to_chrono(self) -> chrono::DateTime<Utc> {
self.into()
}
/// Returns the current time.
///
/// # Panics
///
/// If the number of seconds since the UNIX epoch is greater than `u32::MAX`.
pub fn now() -> DateTime32 {
chrono::Utc::now()
.try_into()
.expect("unexpected out of range chrono::DateTime")
}
/// Returns the duration elapsed between `earlier` and this time,
/// or `None` if `earlier` is later than this time.
pub fn checked_duration_since(&self, earlier: DateTime32) -> Option<Duration32> {
self.timestamp
.checked_sub(earlier.timestamp)
.map(Duration32::from)
}
/// Returns duration elapsed between `earlier` and this time,
/// or zero if `earlier` is later than this time.
pub fn saturating_duration_since(&self, earlier: DateTime32) -> Duration32 {
Duration32::from(self.timestamp.saturating_sub(earlier.timestamp))
}
/// Returns the duration elapsed since this time,
/// or if this time is in the future, returns `None`.
#[allow(clippy::unwrap_in_result)]
pub fn checked_elapsed(&self, now: chrono::DateTime<Utc>) -> Option<Duration32> {
DateTime32::try_from(now)
.expect("unexpected out of range chrono::DateTime")
.checked_duration_since(*self)
}
/// Returns the duration elapsed since this time,
/// or if this time is in the future, returns zero.
pub fn saturating_elapsed(&self, now: chrono::DateTime<Utc>) -> Duration32 {
DateTime32::try_from(now)
.expect("unexpected out of range chrono::DateTime")
.saturating_duration_since(*self)
}
/// Returns the time that is `duration` after this time.
/// If the calculation overflows, returns `None`.
pub fn checked_add(&self, duration: Duration32) -> Option<DateTime32> {
self.timestamp
.checked_add(duration.seconds)
.map(DateTime32::from)
}
/// Returns the time that is `duration` after this time.
/// If the calculation overflows, returns `DateTime32::MAX`.
pub fn saturating_add(&self, duration: Duration32) -> DateTime32 {
DateTime32::from(self.timestamp.saturating_add(duration.seconds))
}
/// Returns the time that is `duration` before this time.
/// If the calculation underflows, returns `None`.
pub fn checked_sub(&self, duration: Duration32) -> Option<DateTime32> {
self.timestamp
.checked_sub(duration.seconds)
.map(DateTime32::from)
}
/// Returns the time that is `duration` before this time.
/// If the calculation underflows, returns `DateTime32::MIN`.
pub fn saturating_sub(&self, duration: Duration32) -> DateTime32 {
DateTime32::from(self.timestamp.saturating_sub(duration.seconds))
}
}
impl Duration32 {
/// The earliest possible `Duration32` value.
pub const MIN: Duration32 = Duration32 { seconds: u32::MIN };
/// The latest possible `Duration32` value.
pub const MAX: Duration32 = Duration32 { seconds: u32::MAX };
/// Creates a new [`Duration32`] to represent the given amount of seconds.
pub const fn from_seconds(seconds: u32) -> Self {
Duration32 { seconds }
}
/// Creates a new [`Duration32`] to represent the given amount of minutes.
///
/// If the resulting number of seconds does not fit in a [`u32`], [`Duration32::MAX`] is
/// returned.
pub const fn from_minutes(minutes: u32) -> Self {
Duration32::from_seconds(minutes.saturating_mul(60))
}
/// Creates a new [`Duration32`] to represent the given amount of hours.
///
/// If the resulting number of seconds does not fit in a [`u32`], [`Duration32::MAX`] is
/// returned.
pub const fn from_hours(hours: u32) -> Self {
Duration32::from_minutes(hours.saturating_mul(60))
}
/// Creates a new [`Duration32`] to represent the given amount of days.
///
/// If the resulting number of seconds does not fit in a [`u32`], [`Duration32::MAX`] is
/// returned.
pub const fn from_days(days: u32) -> Self {
Duration32::from_hours(days.saturating_mul(24))
}
/// Returns the number of seconds in this duration.
pub fn seconds(&self) -> u32 {
self.seconds
}
/// Returns the equivalent [`chrono::Duration`].
pub fn to_chrono(self) -> chrono::Duration {
self.into()
}
/// Returns the equivalent [`std::time::Duration`].
pub fn to_std(self) -> std::time::Duration {
self.into()
}
/// Returns a duration that is `duration` longer than this duration.
/// If the calculation overflows, returns `None`.
pub fn checked_add(&self, duration: Duration32) -> Option<Duration32> {
self.seconds
.checked_add(duration.seconds)
.map(Duration32::from)
}
/// Returns a duration that is `duration` longer than this duration.
/// If the calculation overflows, returns `Duration32::MAX`.
pub fn saturating_add(&self, duration: Duration32) -> Duration32 {
Duration32::from(self.seconds.saturating_add(duration.seconds))
}
/// Returns a duration that is `duration` shorter than this duration.
/// If the calculation underflows, returns `None`.
pub fn checked_sub(&self, duration: Duration32) -> Option<Duration32> {
self.seconds
.checked_sub(duration.seconds)
.map(Duration32::from)
}
/// Returns a duration that is `duration` shorter than this duration.
/// If the calculation underflows, returns `Duration32::MIN`.
pub fn saturating_sub(&self, duration: Duration32) -> Duration32 {
Duration32::from(self.seconds.saturating_sub(duration.seconds))
}
}
impl fmt::Debug for DateTime32 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DateTime32")
.field("timestamp", &self.timestamp)
.field("calendar", &chrono::DateTime::<Utc>::from(*self))
.finish()
}
}
impl fmt::Debug for Duration32 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Duration32")
.field("seconds", &self.seconds)
.field("calendar", &chrono::Duration::from(*self))
.finish()
}
}
impl From<u32> for DateTime32 {
fn from(value: u32) -> Self {
DateTime32 { timestamp: value }
}
}
impl From<&u32> for DateTime32 {
fn from(value: &u32) -> Self {
(*value).into()
}
}
impl From<DateTime32> for chrono::DateTime<Utc> {
fn from(value: DateTime32) -> Self {
// chrono::DateTime is guaranteed to hold 32-bit values
Utc.timestamp_opt(value.timestamp.into(), 0)
.single()
.expect("in-range number of seconds and valid nanosecond")
}
}
impl From<&DateTime32> for chrono::DateTime<Utc> {
fn from(value: &DateTime32) -> Self {
(*value).into()
}
}
impl From<u32> for Duration32 {
fn from(value: u32) -> Self {
Duration32 { seconds: value }
}
}
impl From<&u32> for Duration32 {
fn from(value: &u32) -> Self {
(*value).into()
}
}
impl From<Duration32> for chrono::Duration {
fn from(value: Duration32) -> Self {
// chrono::Duration is guaranteed to hold 32-bit values
chrono::Duration::seconds(value.seconds.into())
}
}
impl From<&Duration32> for chrono::Duration {
fn from(value: &Duration32) -> Self {
(*value).into()
}
}
impl From<Duration32> for std::time::Duration {
fn from(value: Duration32) -> Self {
// std::time::Duration is guaranteed to hold 32-bit values
std::time::Duration::from_secs(value.seconds.into())
}
}
impl From<&Duration32> for std::time::Duration {
fn from(value: &Duration32) -> Self {
(*value).into()
}
}
impl TryFrom<chrono::DateTime<Utc>> for DateTime32 {
type Error = TryFromIntError;
/// Convert from a [`chrono::DateTime`] to a [`DateTime32`], discarding any nanoseconds.
///
/// Conversion fails if the number of seconds since the UNIX epoch is outside the `u32` range.
fn try_from(value: chrono::DateTime<Utc>) -> Result<Self, Self::Error> {
Ok(Self {
timestamp: value.timestamp().try_into()?,
})
}
}
impl TryFrom<&chrono::DateTime<Utc>> for DateTime32 {
type Error = TryFromIntError;
/// Convert from a [`chrono::DateTime`] to a [`DateTime32`], discarding any nanoseconds.
///
/// Conversion fails if the number of seconds since the UNIX epoch is outside the `u32` range.
fn try_from(value: &chrono::DateTime<Utc>) -> Result<Self, Self::Error> {
(*value).try_into()
}
}
impl TryFrom<chrono::Duration> for Duration32 {
type Error = TryFromIntError;
/// Convert from a [`chrono::Duration`] to a [`Duration32`], discarding any nanoseconds.
///
/// Conversion fails if the number of seconds since the UNIX epoch is outside the `u32` range.
fn try_from(value: chrono::Duration) -> Result<Self, Self::Error> {
Ok(Self {
seconds: value.num_seconds().try_into()?,
})
}
}
impl TryFrom<&chrono::Duration> for Duration32 {
type Error = TryFromIntError;
/// Convert from a [`chrono::Duration`] to a [`Duration32`], discarding any nanoseconds.
///
/// Conversion fails if the number of seconds in the duration is outside the `u32` range.
fn try_from(value: &chrono::Duration) -> Result<Self, Self::Error> {
(*value).try_into()
}
}
impl TryFrom<std::time::Duration> for Duration32 {
type Error = TryFromIntError;
/// Convert from a [`std::time::Duration`] to a [`Duration32`], discarding any nanoseconds.
///
/// Conversion fails if the number of seconds in the duration is outside the `u32` range.
fn try_from(value: std::time::Duration) -> Result<Self, Self::Error> {
Ok(Self {
seconds: value.as_secs().try_into()?,
})
}
}
impl TryFrom<&std::time::Duration> for Duration32 {
type Error = TryFromIntError;
/// Convert from a [`std::time::Duration`] to a [`Duration32`], discarding any nanoseconds.
///
/// Conversion fails if the number of seconds in the duration is outside the `u32` range.
fn try_from(value: &std::time::Duration) -> Result<Self, Self::Error> {
(*value).try_into()
}
}
impl FromStr for DateTime32 {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(DateTime32 {
timestamp: s.parse()?,
})
}
}
impl FromStr for Duration32 {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Duration32 {
seconds: s.parse()?,
})
}
}
impl ZcashSerialize for DateTime32 {
fn zcash_serialize<W: std::io::Write>(&self, mut writer: W) -> Result<(), std::io::Error> {
writer.write_u32::<LittleEndian>(self.timestamp)
}
}
impl ZcashDeserialize for DateTime32 {
fn zcash_deserialize<R: std::io::Read>(mut reader: R) -> Result<Self, SerializationError> {
Ok(DateTime32 {
timestamp: reader.read_u32::<LittleEndian>()?,
})
}
}