Re: [PATCH] rust: time: New module for timekeeping functions

From: Heghedus Razvan
Date: Tue Feb 21 2023 - 16:33:54 EST


On Tuesday, February 21st, 2023 at 8:45 PM, Thomas Gleixner <tglx@xxxxxxxxxxxxx> wrote:


> On Wed, Feb 22 2023 at 01:31, Asahi Lina wrote:
>
> > On 22/02/2023 01.02, Thomas Gleixner wrote:
> >
> > > I'm not rusty enough, but you really want two types:
> > >
> > > timestamp and timedelta
> > >
> > > timestamp is an absolute time on a specific clock which is read via
> > > now() and you can add time deltas to it. The latter is required for
> > > arming an absolute timer on the clock.
> > >
> > > timedelta is a relative time and completely independent of any
> > > clock. That's what you get when you subtract two timestamps, but you can
> > > also initialize it from a constant or some other source. timedelta can
> > > be used to arm a relative timer on any clock.
> >
> > If all clocks end up as the same `timestamp` though, then this isn't
> > fully safe, because you could subtract `timestamp`s that came from
> > different clocks and the result would be meaningless. That's why the
> > Rust std Instant is specifically tied to one and only one system clock
> > on each platform.
>
>
> Fine, but do you agree that:
>
> ts1 = tboot.now()
> ...
> ts2 = tboot.now()
>
> xb = ts2 - ts1
>
> then the result x1 cannot be the same data type as ts1, ts2.
>
> From a typesafety perspective
>
> ts1 = treal.now()
> ...
> ts2 = tboot.now()
>
> x = ts2 - ts1
>
> would be an invalid operation, but
>
> ts1 = treal.now()
> ...
> ts2 = treal.now()
>
> xr = ts2 - ts1
>
> is obviously valid.
>
> But xb abd xr are the same datatype because they represent a time delta.
>
> That's the same the Rust std time semantics:
>
> Duration = Instance - Instance valid
> Duration = Systemtime - SystemTime valid
> Duration = Systemtime - Instance invalid
>
> No?
>
I agree with Thomas on this one. The Rust type system is really powerful and we should take advantage of it. Time deltas can be enforced to be from the same clock at compile time.
Just for the sake of it, I wrote a small example on how this can be achieve: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1d0f70bb5329b181f203ce7270e2957a


-- Heghedus Razvan (heghedus.razvan@xxxxxxxxxxxxxx)

> Thanks,
>
> tglx