dizzy 0.2.0

Macros for safely interacting with DST newtypes
Documentation
use dizzy::DstNewtype;

#[derive(Debug, PartialEq)]
enum TryFromStrError {
    Empty,
    TooLarge(usize),
}

/// Checks that the given string is at least 1 and at most 255 bytes in length.
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))
    );
}