go-duration
A parsing and formatting library for Go-lang style time.Duration
.
Usage
Add go_duration
as a dependency in Cargo.toml
[dependencies]
go-duration = "0.2"
go-duration = { version = "0.2", features = ["serde"] }
Examples
Basic
use go_duration::GoDuration;
use std::str::FromStr;
fn main() {
let dur = GoDuration(0);
println!("{}", dur.nanoseconds()); println!("{}", dur);
let dur: GoDuration = 42.into();
println!("{}", dur.nanoseconds()); println!("{}", dur);
let dur = str::parse::<GoDuration>("0s");
println!("{:?}", dur); println!("{}", dur.unwrap());
let dur = GoDuration::from_str("4000ns");
println!("{:?}", dur); println!("{}", dur.unwrap());
let dur: Result<GoDuration, _> = "60m".try_into();
println!("{:?}", dur); println!("{}", dur.unwrap()); }
Serialization/Deserialization
use go_duration::GoDuration;
use serde::{Serialize, Deserialize};
fn main() {
#[derive(Debug, Serialize, Deserialize)]
struct DurationTest {
pub duration: GoDuration,
}
let input = r#"{"duration":"90s"}"#;
let dur_test: DurationTest = serde_json::from_str(input).unwrap();
let output = serde_json::to_string(&dur_test).unwrap();
let expected = r#"{"duration":"1m30s"}"#;
assert_eq!(expected, output);
#[derive(Debug, Serialize, Deserialize)]
struct DurationNanosTest {
#[serde(with = "go_duration::serde::nanoseconds")]
pub duration: GoDuration,
}
let input = r#"{"duration":9000000}"#;
let dur_test: DurationNanosTest = serde_json::from_str(input).unwrap();
let output = serde_json::to_string(&dur_test).unwrap();
let expected = r#"{"duration":9000000}"#;
assert_eq!(expected, output);
}
Nom parser
use go_duration::GoDuration;
use nom::{
bytes::complete::{tag, take_till},
combinator::opt,
multi::fold_many1,
sequence::terminated,
Parser,
};
fn main() {
let input = "1210ms";
let (_, dur) = go_duration::nom::go_duration.parse(input).unwrap();
println!("{:?}", dur); println!("{}", dur);
let input = "10ns 30ms 1m 1m30s";
let (_, arr) = fold_many1(
terminated(take_till(|c: char| c.is_ascii_whitespace()), opt(tag(" ")))
.and_then(go_duration::nom::go_duration),
Vec::new,
|mut arr, dur: GoDuration| {
arr.push(dur);
arr
},
)
.parse(input)
.unwrap();
arr.iter().for_each(|dur| println!("{dur:?}"));
}