Skip to main content

Crate duration_flex

Crate duration_flex 

Source
Expand description

§Duration Flex

Helper to make it easier to specify duration files. Specially useful in configuration files.

Example:

  • 1 hour and 23 minutes: 1h23m
  • 1 week, 6 days, 23 hours, 49 minutes andd 50 seconds: 1w6d23h49m59s

Supported Time Units

  • Weeks: 2w (2 weeks).
  • Days: 3d (3 days).
  • Hours: 15h (15 hours).
  • Minutes: 5m (5 minutes).
  • Seconds: 30s (30 seconds).

§Usage

Simply call one of the from methods to create an instance:

use duration_flex::DurationFlex;

let df = DurationFlex::try_from("1w6d23h49m59s").unwrap();
println!("{df}");

§Features

  • clap: enable clap support, so it can be used as application arguments.
  • serde: enable serde support.
  • utoipa: enable support for the [utoipa] crate, allowing it to be used with the ToSchema derivation.
  • validator: enable support for the [validator] crate, allowing it to be used with the range validator.

§Validator Example:

You can specify the range using the fully qualified type (extended version):

use duration_flex::DurationFlex;
use validator::Validate;

#[derive(Validate)]
struct Config {
	#[validate(range(
		min = "DurationFlex::try_from(\"1h\").unwrap()",
		max = "DurationFlex::try_from(\"2h\").unwrap()"
	))]
	timeout: DurationFlex,
}

Or using string literals (string version). Note the escaped inner quotes, which are required because the macro parses the arguments as Rust expressions:

use duration_flex::DurationFlex;
use validator::Validate;

#[derive(Validate)]
struct Config {
	#[validate(range(min = "\"1h\"", max = "\"2h\""))]
	timeout: DurationFlex,
}

Or using numbers (number version), which represent the amount of seconds:

use duration_flex::DurationFlex;
use validator::Validate;

#[derive(Validate)]
struct Config {
	#[validate(range(min = 3600, max = 7200))]
	timeout: DurationFlex,
}

Structs§

DurationFlex
Type to conveniently specify durations and interoperate with chrono::Duration.

Enums§

DurationFlexError
Errors returned by the different methods.