use dizzy::DstNewtype;
#[derive(Debug, PartialEq)]
enum TryFromStrError {
Empty,
TooLarge(usize),
}
fn bounded_str_invariant(value: &str) -> Result<(), TryFromStrError> {
match value.len() {
0 => Err(TryFromStrError::Empty),
1..256 => Ok(()),
n => Err(TryFromStrError::TooLarge(n)),
}
}
#[derive(Debug, PartialEq, DstNewtype)]
#[repr(transparent)]
#[dizzy(invariant = bounded_str_invariant)]
#[dizzy(constructor = /** Fallibly converts from a [`str`] reference. */ pub try_from_str)]
#[dizzy(error = TryFromStrError)]
struct BoundedStr(str);
#[test]
fn constructor_errors() {
let mut buf = String::new();
assert_eq!(BoundedStr::try_from_str(&buf), Err(TryFromStrError::Empty));
for _ in 1..256 {
buf.push('.');
assert!(BoundedStr::try_from_str(&buf).is_ok());
}
buf.push('.');
assert_eq!(buf.len(), 256);
assert_eq!(
BoundedStr::try_from_str(&buf),
Err(TryFromStrError::TooLarge(256))
);
}