1use std::borrow::Cow;
4use std::fmt;
5use std::fmt::Write as _;
6use std::time::Duration;
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::Serializer;
10use serde::de::{self, Deserializer, Visitor};
11
12#[cfg(test)]
13mod tests;
14
15#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
17pub enum UnitError {
18 #[error("`{0}` is not a duration (use e.g. `500ms`, `30s`, `5m`, `1h30m`, `2d`)")]
20 Duration(String),
21 #[error("`{0}` is not a size (use e.g. `512B`, `64KiB`, `4MiB`, `1GiB`)")]
23 Size(String),
24 #[error("`{0}` is not a memory reserve (use e.g. `25%`, at most `90%`, or a size like `1GiB`)")]
26 Reserve(String),
27}
28
29pub fn parse_duration(s: &str) -> Result<Duration, UnitError> {
37 const UNITS: [(&str, u64); 5] = [
38 ("d", 86_400_000),
39 ("h", 3_600_000),
40 ("m", 60_000),
41 ("s", 1_000),
42 ("ms", 1),
43 ];
44 let error = || UnitError::Duration(s.to_owned());
45 let mut rest = s;
46 let mut total_ms: u64 = 0;
47 let mut last_unit = None;
48 while !rest.is_empty() {
49 let digits = rest.find(|c: char| !c.is_ascii_digit()).ok_or_else(error)?;
50 if digits == 0 {
51 return Err(error());
52 }
53 let number: u64 = rest[..digits].parse().map_err(|_| error())?;
54 rest = &rest[digits..];
55 let unit_len = rest
56 .find(|c: char| c.is_ascii_digit())
57 .unwrap_or(rest.len());
58 let unit = &rest[..unit_len];
59 let index = UNITS
60 .iter()
61 .position(|(name, _)| *name == unit)
62 .ok_or_else(error)?;
63 if last_unit.is_some_and(|last| index <= last) {
64 return Err(error());
65 }
66 last_unit = Some(index);
67 let part = number.checked_mul(UNITS[index].1).ok_or_else(error)?;
68 total_ms = total_ms.checked_add(part).ok_or_else(error)?;
69 rest = &rest[unit_len..];
70 }
71 if last_unit.is_none() {
72 return Err(error());
73 }
74 Ok(Duration::from_millis(total_ms))
75}
76
77pub fn parse_size(s: &str) -> Result<u64, UnitError> {
84 const UNITS: [(&str, u64); 4] = [
85 ("B", 1),
86 ("KiB", 1 << 10),
87 ("MiB", 1 << 20),
88 ("GiB", 1 << 30),
89 ];
90 let error = || UnitError::Size(s.to_owned());
91 let digits = s.find(|c: char| !c.is_ascii_digit()).ok_or_else(error)?;
92 if digits == 0 {
93 return Err(error());
94 }
95 let number: u64 = s[..digits].parse().map_err(|_| error())?;
96 let factor = UNITS
97 .iter()
98 .find(|(name, _)| *name == &s[digits..])
99 .map(|(_, f)| *f)
100 .ok_or_else(error)?;
101 number.checked_mul(factor).ok_or_else(error)
102}
103
104pub fn deserialize_duration<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
110 struct DurationVisitor;
111
112 impl Visitor<'_> for DurationVisitor {
113 type Value = Duration;
114
115 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 f.write_str("a duration string such as `30s` or `1h30m`")
117 }
118
119 fn visit_str<E: de::Error>(self, s: &str) -> Result<Duration, E> {
120 parse_duration(s).map_err(E::custom)
121 }
122 }
123
124 d.deserialize_str(DurationVisitor)
125}
126
127pub fn deserialize_mode_text<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
135 struct ModeVisitor;
136
137 impl Visitor<'_> for ModeVisitor {
138 type Value = String;
139
140 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 f.write_str("a file mode in octal such as \"0640\"")
142 }
143
144 fn visit_str<E: de::Error>(self, s: &str) -> Result<String, E> {
145 Ok(s.to_owned())
146 }
147
148 fn visit_u64<E: de::Error>(self, n: u64) -> Result<String, E> {
149 Ok(format!("0{n}"))
150 }
151
152 fn visit_i64<E: de::Error>(self, n: i64) -> Result<String, E> {
153 Ok(format!("0{n}"))
154 }
155 }
156
157 d.deserialize_any(ModeVisitor)
158}
159
160pub fn deserialize_size<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
166 struct SizeVisitor;
167
168 impl Visitor<'_> for SizeVisitor {
169 type Value = u64;
170
171 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 f.write_str("a size string such as `4MiB` or `10GiB`")
173 }
174
175 fn visit_str<E: de::Error>(self, s: &str) -> Result<u64, E> {
176 parse_size(s).map_err(E::custom)
177 }
178 }
179
180 d.deserialize_str(SizeVisitor)
181}
182
183pub fn deserialize_optional_duration<'de, D: Deserializer<'de>>(
189 d: D,
190) -> Result<Option<Duration>, D::Error> {
191 deserialize_duration(d).map(Some)
192}
193
194pub fn deserialize_optional_size<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
200 deserialize_size(d).map(Some)
201}
202
203#[must_use]
206pub fn format_duration(duration: Duration) -> String {
207 const UNITS: [(&str, u128); 5] = [
208 ("d", 86_400_000),
209 ("h", 3_600_000),
210 ("m", 60_000),
211 ("s", 1_000),
212 ("ms", 1),
213 ];
214 let mut rest = duration.as_millis();
215 if rest == 0 {
216 return "0s".to_owned();
217 }
218 let mut text = String::new();
219 for (name, ms) in UNITS {
220 if rest >= ms {
221 let _ = write!(text, "{}{name}", rest / ms);
222 rest %= ms;
223 }
224 }
225 text
226}
227
228#[must_use]
231pub fn format_size(bytes: u64) -> String {
232 const UNITS: [(&str, u64); 3] = [("GiB", 1 << 30), ("MiB", 1 << 20), ("KiB", 1 << 10)];
233 UNITS
234 .iter()
235 .find(|(_, factor)| bytes != 0 && bytes.is_multiple_of(*factor))
236 .map_or_else(
237 || format!("{bytes}B"),
238 |(name, factor)| format!("{}{name}", bytes / factor),
239 )
240}
241
242pub fn serialize_duration<S: Serializer>(duration: &Duration, s: S) -> Result<S::Ok, S::Error> {
248 s.serialize_str(&format_duration(*duration))
249}
250
251pub fn serialize_optional_duration<S: Serializer>(
257 duration: &Option<Duration>,
258 s: S,
259) -> Result<S::Ok, S::Error> {
260 match duration {
261 Some(duration) => s.serialize_some(&format_duration(*duration)),
262 None => s.serialize_none(),
263 }
264}
265
266pub fn serialize_optional_size<S: Serializer>(size: &Option<u64>, s: S) -> Result<S::Ok, S::Error> {
272 match size {
273 Some(bytes) => s.serialize_some(&format_size(*bytes)),
274 None => s.serialize_none(),
275 }
276}
277
278pub fn serialize_size<S: Serializer>(size: &u64, s: S) -> Result<S::Ok, S::Error> {
284 s.serialize_str(&format_size(*size))
285}
286
287#[derive(Debug)]
289pub struct DurationText;
290
291impl JsonSchema for DurationText {
292 fn schema_name() -> Cow<'static, str> {
293 "Duration".into()
294 }
295
296 fn json_schema(_: &mut SchemaGenerator) -> Schema {
297 json_schema!({
298 "type": "string",
299 "format": "duration",
300 "description": "A duration such as `500ms`, `30s`, `5m`, `1h30m` or `2d`."
301 })
302 }
303}
304
305#[derive(Debug)]
307pub struct SizeText;
308
309impl JsonSchema for SizeText {
310 fn schema_name() -> Cow<'static, str> {
311 "Size".into()
312 }
313
314 fn json_schema(_: &mut SchemaGenerator) -> Schema {
315 json_schema!({
316 "type": "string",
317 "format": "size",
318 "description": "A size such as `512B`, `64KiB`, `4MiB` or `1GiB`."
319 })
320 }
321}
322
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub enum MemoryReserve {
326 Percent(u8),
328 Size(u64),
330}
331
332pub fn parse_reserve(s: &str) -> Result<MemoryReserve, UnitError> {
338 let error = || UnitError::Reserve(s.to_owned());
339 match s.strip_suffix('%') {
340 Some(number) => match number.parse::<u8>() {
341 Ok(percent) if percent <= 90 => Ok(MemoryReserve::Percent(percent)),
342 _ => Err(error()),
343 },
344 None => parse_size(s).map(MemoryReserve::Size).map_err(|_| error()),
345 }
346}
347
348#[must_use]
350pub fn format_reserve(reserve: MemoryReserve) -> String {
351 match reserve {
352 MemoryReserve::Percent(percent) => format!("{percent}%"),
353 MemoryReserve::Size(bytes) => format_size(bytes),
354 }
355}
356
357impl<'de> serde::Deserialize<'de> for MemoryReserve {
358 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
359 let text = String::deserialize(d)?;
360 parse_reserve(&text).map_err(de::Error::custom)
361 }
362}
363
364impl serde::Serialize for MemoryReserve {
365 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
366 s.serialize_str(&format_reserve(*self))
367 }
368}
369
370impl JsonSchema for MemoryReserve {
371 fn schema_name() -> Cow<'static, str> {
372 "MemoryReserve".into()
373 }
374
375 fn json_schema(_: &mut SchemaGenerator) -> Schema {
376 json_schema!({
377 "type": "string",
378 "format": "reserve",
379 "description": "A percentage of the pod's memory limit (`25%`, at most `90%`) or a size (`1GiB`)."
380 })
381 }
382}