Struct WithUnit

Source
pub struct WithUnit;
Expand description

Default deserializer for Durations, ByteSizes and EtherAmounts.

Values can be deserialized from 2 formats:

  • String consisting of a number, optional whitespace and a unit, such as “30 secs” or “500ms” (for Duration) / “4 MiB” (for ByteSize). The unit must correspond to a TimeUnit / SizeUnit / EtherUnit. Durations and EtherAmounts support decimal numbers, such as 3.5 sec or 1.5e-5 ether; ByteSizes only support integers.
  • Object with a single key and a numeric value, such as { "hours": 3 } (for Duration) / { "kb": 512 } (for SizeUnit). To prevent precision loss, decimal values may be enclosed in a string (e.g., { "ether": "0.000123456" }).

Thanks to nesting of object params, the second approach automatically means that a duration can be parsed from a param name suffixed with a unit. For example, a value latency_ms: 500 for parameter latency will be recognized as 500 ms.

§Examples

#[derive(DescribeConfig, DeserializeConfig)]
struct TestConfig {
    latency: Duration,
    disk: ByteSize,
    #[config(default)]
    fee: EtherAmount,
}

// Parsing from a string
let source = smart_config::config!(
    "latency": "30 secs",
    "disk": "256 MiB",
    "fee": "100 gwei",
);
let config: TestConfig = testing::test(source)?;
assert_eq!(config.latency, Duration::from_secs(30));
assert_eq!(config.disk, ByteSize(256 << 20));
assert_eq!(config.fee, EtherAmount(100_000_000_000));

// Parsing from an object
let source = smart_config::config!(
    "latency": serde_json::json!({ "hours": 3.5 }),
    "disk": serde_json::json!({ "gigabytes": 2 }),
    "fee": serde_json::json!({ "ether": "0.000125" }),
);
let config: TestConfig = testing::test(source)?;
assert_eq!(config.latency, Duration::from_secs(3_600 * 7 / 2));
assert_eq!(config.disk, ByteSize(2 << 30));
assert_eq!(config.fee, EtherAmount(125_000_000_000_000));

// Parsing from a suffixed parameter name
let source = Environment::from_iter("", [
    ("LATENCY_SEC", "1.5"),
    ("DISK_GB", "10"),
    ("FEE_IN_ETHER", "1.5e-5"),
]);
let config: TestConfig = testing::test(source)?;
assert_eq!(config.latency, Duration::from_millis(1_500));
assert_eq!(config.disk, ByteSize(10 << 30));
assert_eq!(config.fee, EtherAmount(15_000_000_000_000));

Trait Implementations§

Source§

impl Clone for WithUnit

Source§

fn clone(&self) -> WithUnit

Returns a copy 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 WithUnit

Source§

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

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

impl DeserializeParam<ByteSize> for WithUnit

Source§

const EXPECTING: BasicTypes = Self::EXPECTED_TYPES

Describes which parameter this deserializer is expecting.
Source§

fn describe(&self, description: &mut TypeDescription)

Additional info about the deserialized type, e.g., extended description.
Source§

fn deserialize_param( &self, ctx: DeserializeContext<'_>, param: &'static ParamMetadata, ) -> Result<ByteSize, ErrorWithOrigin>

Performs deserialization given the context and param metadata. Read more
Source§

fn serialize_param(&self, param: &ByteSize) -> Value

Serializes the provided parameter to the JSON model. Read more
Source§

impl DeserializeParam<Duration> for WithUnit

Source§

const EXPECTING: BasicTypes = Self::EXPECTED_TYPES

Describes which parameter this deserializer is expecting.
Source§

fn describe(&self, description: &mut TypeDescription)

Additional info about the deserialized type, e.g., extended description.
Source§

fn deserialize_param( &self, ctx: DeserializeContext<'_>, param: &'static ParamMetadata, ) -> Result<Duration, ErrorWithOrigin>

Performs deserialization given the context and param metadata. Read more
Source§

fn serialize_param(&self, param: &Duration) -> Value

Serializes the provided parameter to the JSON model. Read more
Source§

impl DeserializeParam<EtherAmount> for WithUnit

Source§

const EXPECTING: BasicTypes = Self::EXPECTED_TYPES

Describes which parameter this deserializer is expecting.
Source§

fn describe(&self, description: &mut TypeDescription)

Additional info about the deserialized type, e.g., extended description.
Source§

fn deserialize_param( &self, ctx: DeserializeContext<'_>, param: &'static ParamMetadata, ) -> Result<EtherAmount, ErrorWithOrigin>

Performs deserialization given the context and param metadata. Read more
Source§

fn serialize_param(&self, param: &EtherAmount) -> Value

Serializes the provided parameter to the JSON model. Read more
Source§

impl DeserializeParam<Option<ByteSize>> for WithUnit

Source§

const EXPECTING: BasicTypes = Self::EXPECTED_TYPES

Describes which parameter this deserializer is expecting.
Source§

fn describe(&self, description: &mut TypeDescription)

Additional info about the deserialized type, e.g., extended description.
Source§

fn deserialize_param( &self, ctx: DeserializeContext<'_>, param: &'static ParamMetadata, ) -> Result<Option<ByteSize>, ErrorWithOrigin>

Performs deserialization given the context and param metadata. Read more
Source§

fn serialize_param(&self, param: &Option<ByteSize>) -> Value

Serializes the provided parameter to the JSON model. Read more
Source§

impl DeserializeParam<Option<Duration>> for WithUnit

Source§

const EXPECTING: BasicTypes = Self::EXPECTED_TYPES

Describes which parameter this deserializer is expecting.
Source§

fn describe(&self, description: &mut TypeDescription)

Additional info about the deserialized type, e.g., extended description.
Source§

fn deserialize_param( &self, ctx: DeserializeContext<'_>, param: &'static ParamMetadata, ) -> Result<Option<Duration>, ErrorWithOrigin>

Performs deserialization given the context and param metadata. Read more
Source§

fn serialize_param(&self, param: &Option<Duration>) -> Value

Serializes the provided parameter to the JSON model. Read more
Source§

impl DeserializeParam<Option<EtherAmount>> for WithUnit

Source§

const EXPECTING: BasicTypes = Self::EXPECTED_TYPES

Describes which parameter this deserializer is expecting.
Source§

fn describe(&self, description: &mut TypeDescription)

Additional info about the deserialized type, e.g., extended description.
Source§

fn deserialize_param( &self, ctx: DeserializeContext<'_>, param: &'static ParamMetadata, ) -> Result<Option<EtherAmount>, ErrorWithOrigin>

Performs deserialization given the context and param metadata. Read more
Source§

fn serialize_param(&self, param: &Option<EtherAmount>) -> Value

Serializes the provided parameter to the JSON model. Read more
Source§

impl Copy for WithUnit

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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> 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, 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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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