Deserialize a memory size from a human-readable string into any numeric type
(deserializer: D)
| 331 | |
| 332 | /// Deserialize a memory size from a human-readable string into any numeric type |
| 333 | pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> |
| 334 | where |
| 335 | D: Deserializer<'de>, |
| 336 | T: TryFrom<u64>, |
| 337 | T::Error: std::fmt::Display, |
| 338 | { |
| 339 | use serde::de::Visitor; |
| 340 | use std::fmt; |
| 341 | |
| 342 | struct MemorySizeVisitor<T>(std::marker::PhantomData<T>); |
| 343 | |
| 344 | impl<T> Visitor<'_> for MemorySizeVisitor<T> |
| 345 | where |
| 346 | T: TryFrom<u64>, |
| 347 | T::Error: std::fmt::Display, |
| 348 | { |
| 349 | type Value = T; |
| 350 | |
| 351 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 352 | formatter.write_str("a memory size string or number") |
| 353 | } |
| 354 | |
| 355 | fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> |
| 356 | where |
| 357 | E: Error, |
| 358 | { |
| 359 | let bytes = MemorySize::parse(value) |
| 360 | .map(|size| size.bytes()) |
| 361 | .map_err(E::custom)?; |
| 362 | |
| 363 | T::try_from(bytes) |
| 364 | .map_err(|e| E::custom(format!("memory size conversion error: {}", e))) |
| 365 | } |
| 366 | |
| 367 | fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> |
| 368 | where |
| 369 | E: Error, |
| 370 | { |
| 371 | T::try_from(value) |
| 372 | .map_err(|e| E::custom(format!("memory size conversion error: {}", e))) |
| 373 | } |
| 374 | |
| 375 | fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E> |
| 376 | where |
| 377 | E: Error, |
| 378 | { |
| 379 | T::try_from(value as u64) |
| 380 | .map_err(|e| E::custom(format!("memory size conversion error: {}", e))) |
| 381 | } |
| 382 | |
| 383 | fn visit_i32<E>(self, value: i32) -> Result<Self::Value, E> |
| 384 | where |
| 385 | E: Error, |
| 386 | { |
| 387 | if value < 0 { |
| 388 | return Err(E::custom("memory size cannot be negative")); |
| 389 | } |
| 390 | T::try_from(value as u64) |
no test coverage detected