Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft sp-time #3298

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,7 @@ members = [
"substrate/primitives/std",
"substrate/primitives/storage",
"substrate/primitives/test-primitives",
"substrate/primitives/time",
"substrate/primitives/timestamp",
"substrate/primitives/tracing",
"substrate/primitives/transaction-pool",
Expand Down
32 changes: 32 additions & 0 deletions substrate/primitives/time/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[package]
name = "sp-time"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
repository.workspace = true
license.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
sp-arithmetic = { path = "../arithmetic", default-features = false }
sp-runtime = { path = "../runtime", default-features = false }
sp-std = { path = "../std", default-features = false }

[lints]
workspace = true

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]

[features]
default = ["std"]
std = [
"sp-runtime/std",
"sp-std/std",
"codec/std",
"scale-info/std",
"sp-arithmetic/std"
]
125 changes: 125 additions & 0 deletions substrate/primitives/time/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![cfg_attr(not(feature = "std"), no_std)]

//! Substrate time and duration types.
//!
//! Main design goal of this API is to KISS (Keep It Simple and Stupid) and to still fulfill our
//! needs. This means to rely on already existing conventions as much as possible.

use codec::{EncodeLike, FullCodec};
use core::fmt;
use sp_arithmetic::traits::{CheckedAdd, CheckedSub, Saturating, Zero};
use sp_runtime::traits::Member;

/// Provides the current time.
pub trait InstantProvider<I: Instant> {
/// Monotonicity assumptions about `now()`.
///
/// Some pallets may restrict themselves to only work with monotonic clocks.
const MONOTIC: Monotonicity;

/// Returns the current time.
fn now() -> I;
}

/// What to assume about two directly consecutive calls to a function `f`.
pub enum Monotonicity {
/// No implied correlation between two calls to `f`.
None,
/// `f() <= f()` always holds.
MonotonicIncrease,
/// `f() < f()` always holds.
StrictMonotonicIncrease,
}

/// An instant or "time point".
pub trait Instant:
Member
+ FullCodec
+ EncodeLike
+ fmt::Debug
+ scale_info::TypeInfo
+ core::cmp::PartialOrd
+ core::cmp::Eq
+ Since<<Self as Instant>::Delta>
+ Until<<Self as Instant>::Delta>
// If it turns out that our API is bad, then people can still use UNIX formats:
+ TryFrom<UnixInstant>
+ TryInto<UnixInstant>
{
type Delta: Duration;

/// Dial time forward by `delta`.
fn checked_forward(&self, delta: &Self::Delta) -> Option<Self>;

/// Dial time backward by `delta`.
fn checked_rewind(&self, delta: &Self::Delta) -> Option<Self>;
}

/// A duration or "time interval".
///
/// Durations MUST always be positive.
pub trait Duration:
Member
+ FullCodec
+ EncodeLike
+ fmt::Debug
+ scale_info::TypeInfo
+ core::cmp::PartialOrd
+ core::cmp::Eq
+ CheckedAdd
+ CheckedSub
+ Saturating
+ Zero
+ TryFrom<UnixDuration>
+ TryInto<UnixDuration>
{
/// Scale the duration by a factor.
fn checked_scale(&self, other: u32) -> Option<Self>;
}

/// Calculates the time since a given instant.
pub trait Since<D: Duration> {
Copy link
Contributor

@gpestana gpestana Feb 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expecting this to be highly WIP but IMO a Duration trait should expose both fn since and fn until, which probably can be implemented by default given CheckedAd and CheckedSub. In any case, I'm not seeing any case where having a representation of a duration without being able to "traverse time" is useful.

Copy link
Member Author

@ggwpez ggwpez Feb 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expecting this to be highly WIP

Yes thanks for the feedback 😄

I would also rather like to use CheckedAdd and CheckedSub, but they can only operate on (Instant, Instant) and not (Instant, Duration). So I think that we need new traits for this.
These Since and Until are currently used to glue together the Instant and the Duration types.

The Add trait can specify the right-hand operand, but the Checked* traits somehow dont: https://docs.rs/num/latest/num/trait.CheckedAdd.html

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah kinda sucks that they don't.

what about Instant and Duration being the same type/trait? Can you give some examples of why there needs to be two traits for these two concepts?

Copy link
Member Author

@ggwpez ggwpez Feb 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I put some points down here: #3298 (comment)
I think if we use the same type, then we can only ever have Duration. Since what should it return when we subtract two Instants?
And that duration would need to be anchored somewhere, maybe at genesis time. But then we only ever have relative time and not absolute. It seems a bit weird to me, and the fact that Rust, C++ and other major ecosystems all split it into two types makes me think that they are onto something.

/// How long it has been since `past`.
///
/// `None` is returned if the time is in the future.
fn since(&self, past: &Self) -> Option<D>;
}

/// Calculates the time until a given instant.
pub trait Until<D: Duration> {
/// How long it is until `future`.
///
/// `None` is returned if the time is in the past.
fn until(&self, future: &Self) -> Option<D>;
}

/// A UNIX duration.
pub struct UnixDuration {
/// Nano seconds.
pub ns: u128,
}

/// A UNIX compatible instant.
///
/// Note that UNIX often uses seconds or milliseconds instead of nanoseconds.
pub struct UnixInstant {
/// Time since 00:00:00 UTC on 1 January 1970.
pub since_epoch: UnixDuration,
}
Loading