Struct Duration

Source
pub struct Duration(/* private fields */);
Expand description

GEP-2257-compliant Duration type for Gateway API

gateway_api::Duration is a duration type where parsing and formatting obey GEP-2257. It is based on std::time::Duration and uses kube::core::Duration for the heavy lifting of parsing.

See https://gateway-api.sigs.k8s.io/geps/gep-2257 for the complete specification.

Per GEP-2257, when parsing a gateway_api::Duration from a string, the string must match

^([0-9]{1,5}(h|m|s|ms)){1,4}$

and is otherwise parsed the same way that Go’s time.ParseDuration parses durations. When formatting a gateway_api::Duration as a string, zero-valued durations must always be formatted as 0s, and non-zero durations must be formatted to with only one instance of each applicable unit, greatest unit first.

The rules above imply that gateway_api::Duration cannot represent negative durations, durations with sub-millisecond precision, or durations larger than 99999h59m59s999ms. Since there’s no meaningful way in Rust to allow string formatting to fail, these conditions are checked instead when instantiating gateway_api::Duration.

Implementations§

Source§

impl Duration

Source

pub fn new(secs: u64, nanos: u32) -> Result<Self, String>

Create a new gateway_api::Duration from seconds and nanoseconds, while requiring that the resulting duration is valid according to GEP-2257.

use gateway_api::Duration;

let duration = Duration::new(7200, 600_000_000);
Source

pub fn from_secs(secs: u64) -> Result<Self, String>

Create a new gateway_api::Duration from seconds, while requiring that the resulting duration is valid according to GEP-2257.

use gateway_api::Duration;
let duration = Duration::from_secs(3600);
Source

pub fn from_micros(micros: u64) -> Result<Self, String>

Create a new gateway_api::Duration from microseconds, while requiring that the resulting duration is valid according to GEP-2257.

use gateway_api::Duration;
let duration = Duration::from_micros(1_000_000);
Source

pub fn from_millis(millis: u64) -> Result<Self, String>

Create a new gateway_api::Duration from milliseconds, while requiring that the resulting duration is valid according to GEP-2257.

use gateway_api::Duration;
let duration = Duration::from_millis(1000);
Source

pub fn as_secs(&self) -> u64

The number of whole seconds in the entire duration.

use gateway_api::Duration;

let duration = Duration::from_secs(3600);     // 1h
let seconds = duration.unwrap().as_secs();    // 3600

let duration = Duration::from_millis(1500);   // 1s500ms
let seconds = duration.unwrap().as_secs();    // 1
Source

pub fn as_millis(&self) -> u128

The number of milliseconds in the whole duration. GEP-2257 doesn’t support sub-millisecond precision, so this is always exact.

use gateway_api::Duration;

let duration = Duration::from_millis(1500);   // 1s500ms
let millis = duration.unwrap().as_millis();   // 1500
Source

pub fn as_nanos(&self) -> u128

The number of nanoseconds in the whole duration. This is always exact.

use gateway_api::Duration;

let duration = Duration::from_millis(1500);   // 1s500ms
let nanos = duration.unwrap().as_nanos();     // 1_500_000_000
Source

pub fn subsec_nanos(&self) -> u32

The number of nanoseconds in the part of the duration that’s not whole seconds. Since GEP-2257 doesn’t support sub-millisecond precision, this will always be 0 or a multiple of 1,000,000.

use gateway_api::Duration;

let duration = Duration::from_millis(1500);          // 1s500ms
let subsec_nanos = duration.unwrap().subsec_nanos(); // 500_000_000
Source

pub fn is_zero(&self) -> bool

Checks whether the duration is zero.

use gateway_api::Duration;

let duration = Duration::from_secs(0);
assert!(duration.unwrap().is_zero());

let duration = Duration::from_secs(1);
assert!(!duration.unwrap().is_zero());

Trait Implementations§

Source§

impl Clone for Duration

Source§

fn clone(&self) -> Duration

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Duration

Formatting a gateway_api::Duration for debug is the same as formatting it for display.

Source§

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

Format a gateway_api::Duration for debug, following GEP-2257 rules.

Source§

impl Display for Duration

Formatting a gateway_api::Duration for display is defined only for valid durations, and must follow the GEP-2257 rules for formatting:

  • zero-valued durations must always be formatted as 0s
  • non-zero durations must be formatted with only one instance of each applicable unit, greatest unit first.
use gateway_api::Duration;
use std::fmt::Display;

// Zero-valued durations are always formatted as "0s".
let duration = Duration::from_secs(0);
assert_eq!(format!("{}", duration.unwrap()), "0s");

// Non-zero durations are formatted with only one instance of each
// applicable unit, greatest unit first.
let duration = Duration::from_secs(3600);
assert_eq!(format!("{}", duration.unwrap()), "1h");

let duration = Duration::from_millis(1500);
assert_eq!(format!("{}", duration.unwrap()), "1s500ms");

let duration = Duration::from_millis(9005500);
assert_eq!(format!("{}", duration.unwrap()), "2h30m5s500ms");
Source§

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

Format a gateway_api::Duration for display, following GEP-2257 rules.

Source§

impl FromStr for Duration

Parsing a gateway_api::Duration from a string requires that the input string obey GEP-2257:

  • input strings must match ^([0-9]{1,5}(h|m|s|ms)){1,4}$
  • durations are parsed the same way that Go’s time.ParseDuration does

If the input string is not valid according to GEP-2257, an error is returned explaining what went wrong.

use gateway_api::Duration;
use std::str::FromStr;

let duration = Duration::from_str("1h");

// This should output "Parsed duration: 1h".
match duration {
   Ok(d) => println!("Parsed duration: {}", d),
  Err(e) => eprintln!("Error: {}", e),
}

let duration = Duration::from_str("1h30m500ns");

// This should output "Error: Cannot express sub-millisecond
// precision in GEP-2257".
match duration {
   Ok(d) => println!("Parsed duration: {}", d),
  Err(e) => eprintln!("Error: {}", e),
}
Source§

type Err = String

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

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

Parses a string s to return a value of this type. Read more
Source§

impl PartialEq for Duration

Source§

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

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

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 TryFrom<Duration> for Duration

Converting from std::time::Duration to gateway_api::Duration is allowed, but we need to make sure that the incoming duration is valid according to GEP-2257.

use gateway_api::Duration;
use std::convert::TryFrom;
use std::time::Duration as stdDuration;

// A one-hour duration is valid according to GEP-2257.
let std_duration = stdDuration::from_secs(3600);
let duration = Duration::try_from(std_duration);

// This should output "Duration: 1h".
match duration {
   Ok(d) => println!("Duration: {}", d),
  Err(e) => eprintln!("Error: {}", e),
}

// A 600-nanosecond duration is not valid according to GEP-2257.
let std_duration = stdDuration::from_nanos(600);
let duration = Duration::try_from(std_duration);

// This should output "Error: Cannot express sub-millisecond
// precision in GEP-2257".
match duration {
   Ok(d) => println!("Duration: {}", d),
  Err(e) => eprintln!("Error: {}", e),
}
Source§

type Error = String

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

fn try_from(duration: stdDuration) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<Duration> for Duration

Converting from k8s::time::Duration to gateway_api::Duration is allowed, but we need to make sure that the incoming duration is valid according to GEP-2257.

use gateway_api::Duration;
use std::convert::TryFrom;
use std::str::FromStr;
use kube::core::Duration as k8sDuration;

// A one-hour duration is valid according to GEP-2257.
let k8s_duration = k8sDuration::from_str("1h").unwrap();
let duration = Duration::try_from(k8s_duration);

// This should output "Duration: 1h".
match duration {
   Ok(d) => println!("Duration: {}", d),
  Err(e) => eprintln!("Error: {}", e),
}

// A 600-nanosecond duration is not valid according to GEP-2257.
let k8s_duration = k8sDuration::from_str("600ns").unwrap();
let duration = Duration::try_from(k8s_duration);

// This should output "Error: Cannot express sub-millisecond
// precision in GEP-2257".
match duration {
   Ok(d) => println!("Duration: {}", d),
  Err(e) => eprintln!("Error: {}", e),
}

// kube::core::Duration can also express negative durations, which are not
// valid according to GEP-2257.
let k8s_duration = k8sDuration::from_str("-5s").unwrap();
let duration = Duration::try_from(k8s_duration);

// This should output "Error: Cannot express sub-millisecond
// precision in GEP-2257".
match duration {
   Ok(d) => println!("Duration: {}", d),
  Err(e) => eprintln!("Error: {}", e),
}
Source§

type Error = String

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

fn try_from(duration: k8sDuration) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl Copy for Duration

Source§

impl Eq for Duration

Source§

impl StructuralPartialEq for Duration

Auto Trait Implementations§

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<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

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<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

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

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
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> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more