Skip to main content

sword_core/config/
utils.rs

1use byte_unit::Byte;
2use duration_str::parse as parse_duration;
3use serde::{Deserialize, Serialize};
4use std::str::FromStr;
5use std::time::Duration;
6
7/// Time duration configuration with raw string representation
8///
9/// This type allows deserializing human-readable time durations from configuration files.
10///
11/// # Examples
12///
13/// ```toml
14/// timeout = "30s"
15/// interval = "1h 30m"
16/// ```
17#[derive(Debug, Clone, Serialize)]
18pub struct TimeConfig {
19    pub parsed: Duration,
20    pub raw: String,
21}
22
23impl<'de> Deserialize<'de> for TimeConfig {
24    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
25    where
26        D: serde::Deserializer<'de>,
27    {
28        use serde::de::Error;
29
30        let raw = String::deserialize(deserializer)?;
31        let parsed = parse_duration(&raw).map_err(Error::custom)?;
32
33        Ok(TimeConfig { parsed, raw })
34    }
35}
36
37/// Byte size configuration with raw string representation
38///
39/// This type allows deserializing human-readable byte sizes from configuration files.
40///
41/// # Examples
42///
43/// ```toml
44/// max_size = "10MB"
45/// buffer_size = "4KiB"
46/// ```
47#[derive(Debug, Clone, Serialize)]
48pub struct ByteConfig {
49    pub parsed: usize,
50    pub raw: String,
51}
52
53impl<'de> Deserialize<'de> for ByteConfig {
54    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
55    where
56        D: serde::Deserializer<'de>,
57    {
58        use serde::de::Error;
59
60        let raw = String::deserialize(deserializer)?;
61        let byte = Byte::from_str(&raw).map_err(Error::custom)?;
62        let parsed = byte.as_u64() as usize;
63
64        Ok(ByteConfig { parsed, raw })
65    }
66}