diff --git a/core/src/block_size.rs b/core/src/block_size.rs index 4aad23a..3a125f7 100644 --- a/core/src/block_size.rs +++ b/core/src/block_size.rs @@ -6,6 +6,7 @@ use std::fmt; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use std::num::NonZero; +use std::{io, str::FromStr}; use crate::{Constraint, General}; @@ -56,7 +57,7 @@ impl BlockSize { /// Returns the base-two exponent of the block size. pub const fn exponent(self) -> u32 { - self.bytes.get().trailing_zeros() + self.bytes.trailing_zeros() } /// Converts this block size to another constraint. @@ -109,6 +110,26 @@ impl fmt::Debug for BlockSize { } } +/// Formats the block size as a decimal byte count. +impl fmt::Display for BlockSize { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.bytes.fmt(formatter) + } +} + +impl FromStr for BlockSize { + type Err = io::Error; + + /// Parses a decimal byte count using the same constraints as `from_bytes`. + fn from_str(text: &str) -> Result { + let bytes = text + .parse() + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + Self::from_bytes(bytes) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid block size")) + } +} + impl PartialEq for BlockSize { fn eq(&self, other: &Self) -> bool { self.bytes == other.bytes diff --git a/core/tests/block_size.rs b/core/tests/block_size.rs index 2d67561..408f295 100644 --- a/core/tests/block_size.rs +++ b/core/tests/block_size.rs @@ -5,6 +5,19 @@ use std::num::NonZero; use devmap_core::{BlockSize, Constraint, General}; +#[test] +fn text_representation_uses_constrained_bytes() { + for bytes in [512, 4096, 524_288] { + let text = bytes.to_string(); + let size: BlockSize = text.parse().unwrap(); + assert_eq!(size.bytes().get(), bytes); + assert_eq!(size.to_string(), text); + } + for text in ["", "0", "256", "513", "1048576", "4294967296", "4KiB"] { + assert!(text.parse::>().is_err(), "{text}"); + } +} + #[derive(Debug)] enum Restricted {}