Struct Span

Source
pub struct Span {
    pub seconds: u64,
}
Expand description

Timespan (Duration)

Simply an unsigned count of seconds. Debug, Display and FromStr implementations break this number, which is often incomprehensibly large, down into understandable units. So instead of Span { seconds: 108030 } you get 1d6h30s.

These are the units used:

Scaleunitseconds
Yearsy31556952
Monthsmo2629746
Weeksw604800
Daysd86400
Hoursh3600
Minutesm60
Secondss1

As explained in the documentation for Scale, the amount of seconds for y and mo is the average for each of these scales.

The Span can be parsed from the terse duration format using parse or try_parse. These methods are also const, so they can be used to define constants.

use greg::Span;

const TIMEOUT: Span = Span::parse("30s");

assert_eq!(Span::parse("0s"), Span::from_seconds(0));
assert_eq!(Span::parse("1m30s"), Span::MINUTE + Span::SECOND * 30);
assert_eq!(Span::parse("1d10h"), Span::DAY + Span::HOUR * 10);
assert_eq!(Span::try_parse("48h"), Ok(Span::DAY * 2));
assert_eq!(
    Span::parse("3w2h10m30s"),
    Span::WEEK * 3 + Span::HOUR * 2 + Span::MINUTE * 10 + Span::SECOND * 30
);

The alternate form for Display (with {:#}) produces a string where each number/unit pair is separated by a space. Additionally, if a precision is specified (with {:.2}), at most the requested number of number/unit pairs are printed, truncating smaller units.

use greg::Span;
let span = Span::parse("1w2d8h33m12s");

assert_eq!(span.to_string(), "1w2d8h33m12s");
assert_eq!(format!("{span:#}"), "1w 2d 8h 33m 12s");
assert_eq!(format!("{span:#.2}"), "1w 2d");

Fields§

§seconds: u64

Duration in seconds

Implementations§

Source§

impl Span

Source

pub const fn from_seconds(seconds: u64) -> Self

Same as constructing Span {seconds} directly

Source§

impl Span

Source

pub const SCALES: [(u64, &'static str, Scale); 7]

Source

pub const WEEK: Self

Source

pub const DAY: Self

Source

pub const HOUR: Self

Source

pub const MINUTE: Self

Source

pub const SECOND: Self

Source

pub const ZERO: Self

Source

pub const MAX: Self

The largest possible Span

Source§

impl Span

Source

pub const fn checked_add(self, other: Self) -> Option<Self>

Checked addition: computes self + other, returning None if overflow occurred.

Source

pub const fn checked_sub(self, other: Self) -> Option<Self>

Checked subtraction: computes self - other, returning None if overflow occurred.

Source

pub const fn saturating_add(self, other: Self) -> Self

Saturating addition: computes self + other, saturating at the numeric bounds instead of overflowing.

Source

pub const fn saturating_sub(self, other: Self) -> Self

Saturating subtraction: computes self - other, saturating at the numeric bounds instead of overflowing.

Source

pub fn scale_div(self) -> (Scale, u64)

Break down into a Scale and count

Returns the biggest Scale that divides the Span without a remainder as well as the result of this division. One exception is the empty Span::ZERO, because the count is 0 for every Scale. Instead of returning (Scale::Years, 0), which would be counter-intuitive, the zero-second Span always returns the more natural (Scale::Seconds, 0).

Remember that Scale::Years and Scale::Months are special, because they represent an average, they do not cleanly divide into weeks, days or even minutes! See the Scale documentation for details.

use greg::{Span, Scale};

assert_eq!(Span::from_seconds(600).scale_div(), (Scale::Minutes, 10));
assert_eq!(Span::ZERO.scale_div(), (Scale::Seconds, 0));
let one_and_a_half: Span = "1h30m".parse().unwrap();
assert_eq!(one_and_a_half.scale_div(), (Scale::Minutes, 90));
Source§

impl Span

Source

pub const fn parse(from: &str) -> Self

Try to parse terse duration format and panic if invalid

 use greg::Span;
 const CHILIAD: Span = Span::parse("1000y");

 assert_eq!(Span::parse("0s"), Span::ZERO);
 assert_eq!(Span::parse("10s").seconds, 10);
 assert_eq!(Span::parse("1m30s").seconds, 90);
 let _ = Span::parse("3mo2h10m30s");

This is mainly useful in const contexts, since the panic gets caught at compile-time.

 use greg::Span;
 const DECADE: Span = Span::parse("10t"); // typo: "t" instead of "y"
Source

pub const fn try_parse(from: &str) -> Result<Self, ParseSpanError>

Try to parse terse duration format

 use greg::Span;

 assert_eq!(Span::try_parse("0s"), Ok(Span::ZERO));
 assert_eq!(Span::try_parse("1w"), Ok(Span::WEEK));
 assert_eq!(Span::try_parse("1m30s"), Ok(Span::MINUTE + Span::SECOND * 30));
 let _ = Span::try_parse("3mo2h10m30s").unwrap();

 assert!(Span::try_parse("10 hours").is_err(), "long-form units don't work");

Trait Implementations§

Source§

impl Add<Span> for Point

Source§

type Output = Point

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Span) -> Self::Output

Performs the + operation. Read more
Source§

impl Add for Span

Source§

type Output = Span

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Span) -> Self::Output

Performs the + operation. Read more
Source§

impl Clone for Span

Source§

fn clone(&self) -> Span

Returns a duplicate of the value. Read more
1.0.0 · Source§

const fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Span

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Span

Available on crate feature serde only.
Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Span

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Div<Scale> for Span

Source§

type Output = u64

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Scale) -> Self::Output

Performs the / operation. Read more
Source§

impl Div<u64> for Span

Source§

type Output = u64

The resulting type after applying the / operator.
Source§

fn div(self, rhs: u64) -> Self::Output

Performs the / operation. Read more
Source§

impl From<Scale> for Span

Source§

fn from(scale: Scale) -> Self

Converts to this type from the input type.
Source§

impl FromSql for Span

Available on crate feature rusqlite only.
Source§

fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self>

Converts SQLite value into Rust value.
Source§

impl FromStr for Span

Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parse terse duration format

See try_parse for a const method and some more details.

Source§

type Err = ParseSpanError

The associated error which can be returned from parsing.
Source§

impl Hash for Span

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Mul<u64> for Span

Source§

type Output = Span

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: u64) -> Self::Output

Performs the * operation. Read more
Source§

impl Ord for Span

Source§

fn cmp(&self, other: &Span) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Span

Source§

fn eq(&self, other: &Span) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

const fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Span

Source§

fn partial_cmp(&self, other: &Span) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Rem<Scale> for Span

Source§

type Output = Span

The resulting type after applying the % operator.
Source§

fn rem(self, rhs: Scale) -> Self::Output

Performs the % operation. Read more
Source§

impl Serialize for Span

Available on crate feature serde only.
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Sub<Span> for Point

Source§

type Output = Point

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Span) -> Self::Output

Performs the - operation. Read more
Source§

impl Sub for Span

Source§

type Output = Span

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Span) -> Self::Output

Performs the - operation. Read more
Source§

impl ToSql for Span

Available on crate feature rusqlite only.
Source§

fn to_sql(&self) -> SqlResult<ToSqlOutput<'_>>

Converts Rust value to SQLite value
Source§

impl Copy for Span

Source§

impl Eq for Span

Source§

impl StructuralPartialEq for Span

Auto Trait Implementations§

§

impl Freeze for Span

§

impl RefUnwindSafe for Span

§

impl Send for Span

§

impl Sync for Span

§

impl Unpin for Span

§

impl UnwindSafe for Span

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,