Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion core/src/block_size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -56,7 +57,7 @@ impl<C: Constraint> BlockSize<C> {

/// 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.
Expand Down Expand Up @@ -109,6 +110,26 @@ impl<C: Constraint> fmt::Debug for BlockSize<C> {
}
}

/// Formats the block size as a decimal byte count.
impl<C: Constraint> fmt::Display for BlockSize<C> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.bytes.fmt(formatter)
}
}

impl<C: Constraint> FromStr for BlockSize<C> {
type Err = io::Error;

/// Parses a decimal byte count using the same constraints as `from_bytes`.
fn from_str(text: &str) -> Result<Self, Self::Err> {
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<C: Constraint> PartialEq for BlockSize<C> {
fn eq(&self, other: &Self) -> bool {
self.bytes == other.bytes
Expand Down
13 changes: 13 additions & 0 deletions core/tests/block_size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Restricted> = 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::<BlockSize<Restricted>>().is_err(), "{text}");
}
}

#[derive(Debug)]
enum Restricted {}

Expand Down
Loading