Why `Duration::as/from_millis()` uses different primitives?

Why Duration::as/from_millis() uses different primitives?

Duration::as_millis() returns as u128, while
Duration::from_millis(u64) takes an u64.
What's the cause for this that you can not do this...

let d = Duration::from_millis(Duration::from_secs(0).as_millis());
error[E0308]: mismatched types
   --> src/...
    |
20  |             let d = Duration::from_millis(Duration::from_secs(0).as_millis());
    |                     --------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u64`, found `u128`
    |                     |
    |                     arguments to this function are incorrect
    |
note: associated function defined here
   --> /.../toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/time.rs:245:18
    |
245 |     pub const fn from_millis(millis: u64) -> Duration {
    |                  ^^^^^^^^^^^
help: you can convert a `u128` to a `u64` and panic if the converted value doesn't fit
    |
20  |             let d = Duration::from_millis(Duration::from_secs(0).as_millis().try_into().unwrap());
    |                                                                             ++++++++++++++++++++

from_millis predates the addition of 128-bit integer types to the language.

u128 is available since 1.26.0 and both methods are added later (1.32.0/1.33.0).

I have no insight into actual reasons, but doing it the way they did allows both methods to be infallible. u128 is required to fit an arbitrary Duration, but am arbitrary u128 may not be a valid Duration. And 64 bits should be enough for anybody :slight_smile:

It is fallible, because you can not convert a return value of Duration back to a Duration. A mess of an API.

Duration::from_millis has been stable since 1.3.0: https://doc.rust-lang.org/stable/src/core/time.rs.html#241

1 Like

@sfackler Mmh. Is this a bug in rustdoc that it doesn't write this version (1.3.0) in the doc like with newer 2 digit minor versions?

It was made const in 1.32.0 which is what rustdoc displays for whatever reason.

1 Like

It shows 1.32 for when it was made const fn. The stabilization version of the method itself is omitted because it's the same as the struct as a whole.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.