From 42ba4cd39953cb8efee2055810ac8cf9782fa902 Mon Sep 17 00:00:00 2001 From: Thomas Lamprecht Date: Sat, 20 Nov 2021 18:21:53 +0100 Subject: [PATCH] human byte: make proper proxmox API type Signed-off-by: Thomas Lamprecht --- pbs-api-types/src/human_byte.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/pbs-api-types/src/human_byte.rs b/pbs-api-types/src/human_byte.rs index e8ea27d0..142a0d4e 100644 --- a/pbs-api-types/src/human_byte.rs +++ b/pbs-api-types/src/human_byte.rs @@ -1,5 +1,7 @@ use anyhow::{bail, Error}; +use proxmox_schema::{ApiStringFormat, ApiType, Schema, StringSchema, UpdaterType}; + /// Size units for byte sizes #[derive(Debug, Copy, Clone, PartialEq)] pub enum SizeUnit { @@ -118,6 +120,7 @@ fn strip_unit(v: &str) -> (&str, SizeUnit) { } /// Byte size which can be displayed in a human friendly way +#[derive(Debug, Copy, Clone, UpdaterType)] pub struct HumanByte { /// The siginficant value, it does not includes any factor of the `unit` size: f64, @@ -125,6 +128,22 @@ pub struct HumanByte { unit: SizeUnit, } +fn verify_human_byte(s: &str) -> Result<(), Error> { + match s.parse::() { + Ok(_) => Ok(()), + Err(err) => bail!("byte-size parse error for '{}': {}", s, err), + } +} +impl ApiType for HumanByte { + const API_SCHEMA: Schema = StringSchema::new( + "Byte size with optional unit (B, KB (base 10), MB, GB, ..., KiB (base 2), MiB, Gib, ...).", + ) + .format(&ApiStringFormat::VerifyFn(verify_human_byte)) + .min_length(1) + .max_length(64) + .schema(); +} + impl HumanByte { /// Create instance with size and unit (size must be positive) pub fn with_unit(size: f64, unit: SizeUnit) -> Result { @@ -197,6 +216,9 @@ impl std::str::FromStr for HumanByte { } } +proxmox::forward_deserialize_to_from_str!(HumanByte); +proxmox::forward_serialize_to_display!(HumanByte); + #[test] fn test_human_byte_parser() -> Result<(), Error> { assert!("-10".parse::().is_err()); // negative size