Skip to content

ACP: Add Instant::epoch() #850

Description

@orlp

Proposal

Problem statement

It's a common need to store or transfer durations (as timestamps or otherwise) in a program. Often an API only accepts an Instant (or it is based on Instant::now()) in which case you need a reference point. Currently Rust provides no such reference point.

Motivating examples or use cases

There are 167 matches on Github for LazyLock<Instant>, most of which consist of some kind of hand-rolled epoch. However some of these are subtly incorrect.

Unless you are very sure that your epoch gets initialized before the Instant in question, you've now got a timestamp before your instant. So EPOCH.elapsed() is fine, but some_instant - EPOCH is not.

Solution sketch

We add a new function to Instant, which is guaranteed to return a historic instant:

impl Instant {
    /// Return an instant which occurs no later than any other.
    ///
    /// This instant may differ from one program invocation to the next,
    /// but is always the same within one process.
    pub fn epoch() -> Self { ... }
}

No further guarantees are given. It would be nice if the library developers make this Instant as late as feasibly possible, such that any timestamps like epoch().elapsed() are as small as reasonably possible (so that they may e.g. be stored in u64 nanosecond timestamps).

Alternatives

There is the mentioned LazyLock alternative, but with the mentioned pitfall of being initialized too late.

Open problems

I'm not 100% certain this function can be implemented on all platforms, when also taking into account dynamic linking, at least not without slowing down Instant::now() itself with a check to see if the epoch is initialized.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-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