add HumanDuration
This commit is contained in:
parent
016350a480
commit
321ab18890
3 changed files with 61 additions and 0 deletions
|
@ -59,3 +59,4 @@ color-eyre = { version = "0.6.5", optional = true }
|
|||
eyre = { version = "0.6.12" }
|
||||
num_cpus = { version = "1.17.0", optional = true }
|
||||
either = "1.15.0"
|
||||
humantime = "2.3.0"
|
||||
|
|
57
src/time/duration.rs
Normal file
57
src/time/duration.rs
Normal file
|
@ -0,0 +1,57 @@
|
|||
use std::{borrow::Cow, ops::Deref, time::Duration};
|
||||
|
||||
use compact_str::{CompactString, ToCompactString};
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::data;
|
||||
|
||||
#[repr(transparent)]
|
||||
#[data(crate = crate, copy, not(serde, schemars))]
|
||||
pub struct HumanDuration(pub Duration);
|
||||
|
||||
impl Deref for HumanDuration {
|
||||
type Target = Duration;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for HumanDuration {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
Cow::Borrowed("HumanDuration")
|
||||
}
|
||||
|
||||
fn schema_id() -> Cow<'static, str> {
|
||||
Cow::Borrowed(concat!(module_path!(), "::HumanDuration"))
|
||||
}
|
||||
|
||||
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
||||
String::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for HumanDuration {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let s = CompactString::deserialize(deserializer)?;
|
||||
humantime::parse_duration(&s)
|
||||
.map_err(|e| serde::de::Error::custom(e))
|
||||
.map(Self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for HumanDuration {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
humantime::format_duration(self.0)
|
||||
.to_compact_string()
|
||||
.serialize(serializer)
|
||||
}
|
||||
}
|
|
@ -30,6 +30,7 @@
|
|||
pub use self::{
|
||||
clock::{Clock, Mock, RealTime},
|
||||
date::{Date, Day, Leapness, LooseDate, Month, Year},
|
||||
duration::HumanDuration,
|
||||
time::{Hours, Mins, PreciseTime, Secs, SecsTime, SubsecNanos, Time},
|
||||
timestamp::Timestamp,
|
||||
};
|
||||
|
@ -38,6 +39,8 @@ pub mod ser;
|
|||
pub mod str;
|
||||
pub mod tz;
|
||||
|
||||
mod duration;
|
||||
|
||||
mod clock;
|
||||
mod date;
|
||||
mod time;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue