tailhook / humantime

A parser and formatter for std::time::{SystemTime, Duration}
Apache License 2.0
283 stars 34 forks source link

suggestion: support a const initializer #29

Open sbromling opened 2 years ago

sbromling commented 2 years ago

Since Durations can be created with const fns, it would be nice if humantime::Duration could also.

It would be ideal if From and Into could be const. Since I don't believe that's possible, perhaps the following added to humantime::Duration:

    pub const fn new(std: StdDuration) -> Self {
        Self(std)
    }

Alternatively, would it be feasible to make the inner StdDuration public (i.e. pub struct Duration(pub StdDuration))? Then the const initializer wouldn't be strictly necessary, and it would give other convenient ways to access the inner duration (i.e. without using the Into or Deref+Copy impls).

I was excited to discover this crate today, because it is a pretty good fit for clap derive-style argument parsing, thanks to the addition of FromStr and Display, plus making the command line fields "unit-less" and less error-prone.

lilyball commented 2 years ago

Another option is to just move the <Duration as From<StdDuration>>::from method into an inherent impl instead (and then have the trait just call the inherent method), which would have the effect of making a call to Duration::from() become constant.

Personally I like the idea of making the inner field public, because it feels simpler to say Duration(StdDuration::from_secs(2)) instead of Duration::from(StdDuration::from_secs(2)) and there doesn't seem to be any obvious reason why it would ever need a new field, it's just a newtype wrapper and does not impose any constraints on its wrapped value.