Enforce Non-Empty Newtypes With TryFrom

Implement TryFrom<&str> and TryFrom<String> for trimmed non-empty domain newtypes, rejecting blank or oversized inputs with typed validation errors.

RustForm Validation

Code

rustsnippet
57 lines
use std::fmt;

#[derive(Debug, Clone, PartialEq, Eq)]
struct TenantSlug(String);

#[derive(Debug, PartialEq, Eq)]
enum SlugError {
    Empty,
    TooLong(usize),
    InvalidChar(char),
}

impl fmt::Display for SlugError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "slug cannot be empty"),
            Self::TooLong(n) => write!(f, "slug length {n} exceeds 24 chars"),
            Self::InvalidChar(c) => write!(f, "invalid character {c:?}"),
        }
    }
}

impl TryFrom<&str> for TenantSlug {
    type Error = SlugError;
    fn try_from(raw: &str) -> Result<Self, Self::Error> {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            return Err(SlugError::Empty);
        }
        if trimmed.len() > 24 {
            return Err(SlugError::TooLong(trimmed.len()));
        }
        if let Some(bad) = trimmed.chars().find(|c| !c.is_ascii_alphanumeric() && *c != '-') {
            return Err(SlugError::InvalidChar(bad));
        }
        Ok(Self(trimmed.to_ascii_lowercase()))
    }
}

impl TryFrom<String> for TenantSlug {
    type Error = SlugError;
    fn try_from(raw: String) -> Result<Self, Self::Error> { Self::try_from(raw.as_str()) }
}

fn register<T: TryInto<TenantSlug, Error = SlugError>>(candidate: T) {
    match candidate.try_into() {
        Ok(slug) => println!("accepted: {}", slug.0),
        Err(err) => println!("rejected: {err}"),
    }
}

fn main() {
    for slug in ["  Acme-Corp  ", "   ", "bad/slug", "this-tenant-identifier-is-far-too-long"] {
        register(slug);
    }
    register(String::from("dev-team-01"));
}

Logic trace — Enforce Non-Empty Newtypes With TryFrom

Dynamic execution steps belong inside routines fmt, try_from, register and main.

for slug in [" Acme-Corp ", " ", "bad/slug", "this-tenant-identifier-is-far-too-long"] performs sequential per-item processing inside this block. Errors ride back inside Result, forcing an explicit decision at every call site. Pattern matching via match forces each shape of the value to be handled.

Points of care

  • External package surface remains empty; standard library primitives power all steps.
  • Error handling is typed — each Result must be matched or forwarded with ?.

Applying it

The entry-point signature is fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result

The run emits 2 labeled sections — accepted:, rejected: — one per step.

Start the program and main runs register one after another.

Statements that matter

return Err(SlugError::TooLong(trimmed.len()));
return Err(SlugError::InvalidChar(bad));
return Err(SlugError::Empty);

Interactive Tools for This Topic

FAQ

How do errors reach the caller?
Each fallible operation returns `Result`; nothing is silently discarded.
What does Enforce Non-Empty Newtypes With TryFrom print when run?
The script runs standalone; its 2 labeled outputs include `accepted:`, `rejected:`.