Expand description
serde adapters, so a config or API struct can hold quantities.
uom’s own Serialize/Deserialize encodes the raw base-unit float: a
timeout as 30.0, and a size as 536870912.0. An operator does not write
that in YAML, and an admin API should not return it. Use these modules through
#[serde(with = ...)]. They give a choice of two encodings:
human— the operator-facing string form ("512MiB","30s","10MiB/s"), for config files.numeric— an exact integer in a named unit (30000milliseconds,536870912bytes), for JSON APIs and anything mirroring a Kafka wire field.
use krabka_units::{prelude::*, serde_units};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct TopicConfig {
#[serde(with = "serde_units::human::byte_size")]
segment_size: ByteSize,
#[serde(with = "serde_units::numeric::millis_i64")]
retention: Time,
}
let parsed: TopicConfig =
serde_json::from_str(r#"{"segment_size":"512MiB","retention":604800000}"#)?;
assert_eq!(parsed.segment_size, mebibytes(512));
assert_eq!(parsed.retention, days(7));A dimensioned field in human form must carry its unit. These modules
reject a bare number and never assume seconds or bytes, because that guess is
the failure this crate prevents. human::ratio is the exception. A
fraction’s unit is “none”, so it accepts 0.25 as well as "25%".