Skip to content

ACP: Add non-panicking versions of Duration::from_{nanos_u128,mins,hours,days,weeks} #749

@Zorbatron

Description

@Zorbatron

Proposal

Problem statement

The Duration type has constructors to automatically convert from a number of minutes, hours, days, and weeks to a Duration which always stores the duration as seconds.

However, these functions will panic if the conversion would overflow a u64 which requires you to do a bounds check before calling these functions if you want to gracefully handle an overflow.

Motivating examples or use cases

Say you have an enum like:

#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
enum InputUnit {
    NS,
    US,
    MS,
    S,
    M,
    H,
}

Currently, if you were to implement a to_duration function, it'd look like:

impl InputUnit {
    fn to_duration(self, dur: u64) -> Option<Duration> {
        match self {
            InputUnit::NS => Some(Duration::from_nanos(dur)),
            InputUnit::US => Some(Duration::from_micros(dur)),
            InputUnit::MS => Some(Duration::from_millis(dur)),
            InputUnit::S => Some(Duration::from_secs(dur)),
            InputUnit::M => {
                if dur > (u64::MAX / 60) {
                    None
                } else {
                    Some(Duration::from_mins(dur))
                }
            }
            InputUnit::H => {
                if dur > (u64::MAX / (60 * 60)) {
                    None
                } else {
                    Some(Duration::from_hours(dur))
                }
            }
        }
    }
}

I believe it would be more convenient if Duration had versions of the conversion functions that didn't panic.

Solution sketch

impl Duration {
    pub const fn try_from_mins(mins: u64) -> Option<Duration> {
        if mins > u64::MAX / SECS_PER_MINUTE {
            None
        } else {
            Some(Duration::from_secs(mins * SECS_PER_MINUTE))
        }
    }
    
    pub const fn try_from_hours(hours: u64) -> Option<Duration> {
        if hours > u64::MAX / (SECS_PER_MINUTE * MINS_PER_HOUR) {
            None
        } else {
            Duration::from_secs(hours * MINS_PER_HOUR * SECS_PER_MINUTE)
        }
    }
    
    pub const fn try_from_days(days: u64) -> Option<Duration> {
        if days > u64::MAX / (SECS_PER_MINUTE * MINS_PER_HOUR * HOURS_PER_DAY) {
            None
        } else {
            Some(Duration::from_secs(days * MINS_PER_HOUR * SECS_PER_MINUTE * HOURS_PER_DAY))
        }
    }
    
    pub const fn try_from_weeks(weeks: u64) -> Option<Duration> {
        if weeks > u64::MAX / (SECS_PER_MINUTE * MINS_PER_HOUR * HOURS_PER_DAY * DAYS_PER_WEEK) {
            None
        } else {
            Some(Duration::from_secs(weeks * MINS_PER_HOUR * SECS_PER_MINUTE * HOURS_PER_DAY * DAYS_PER_WEEK))
        }
    }
    
    pub const fn try_from_nanos_u128(nanos: u128) -> Option<Duration> {
        const NANOS_PER_SEC: u128 = self::NANOS_PER_SEC as u128; // Perhaps make this constant from `from_nanos_u128` more public?
        let Ok(secs) = u64::try_from(nanos / NANOS_PER_SEC) else {
            return None;
        };
        
        let subsec_nanos = (nanos % NANOS_PER_SEC) as u32;
        // SAFETY: x % 1_000_000_000 < 1_000_000_000 also, subsec_nanos >= 0 since u128 >=0 and u32 >=0
        let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_nanos) };
        
        Some(Duration { secs: secs as u64, nanos: subsec_nanos })
    }
}

One thing I'm not sure about is the return type, would it be better as Result<Duration, DurationConversionError>?

Alternatives

The alternative would be to use a function as described in the 'Motivating examples or use cases' section.

Links and related work

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions