Projects Blog Tools Music Contact
← All Posts
Tech March 17, 2026

Parse, Don't Validate: Type-Safe Design in Rust for Invulnerable Code

By: Evgeny Padezhnov

Parse, Don't Validate: Type-Safe Design in Rust for Invulnerable Code

Type-safe design transforms runtime checks into compile-time guarantees. Rust's type system makes this approach especially powerful.

The core principle: parse input data once into a type that represents valid data. After parsing, the type system guarantees data correctness throughout the entire codebase. No repeated checks. No defensive programming.

The Problem with Traditional Validation

Most validation approaches follow this pattern:

fn process_email(email: &str) -> Result<(), Error> {
    validate_email(email)?;
    // ... use the email
    send_welcome_email(email)?;
    // ... more code
    update_user_email(email)?;
    Ok(())
}

fn send_welcome_email(email: &str) -> Result<(), Error> {
    // Check again? Trust the caller?
    validate_email(email)?;
    // ... send the email
}

A common mistake: Functions either re-check the data (performance loss) or trust the caller (runtime errors).

The "Parse, Don't Validate" Pattern

Instead, we parse once into a new type:

#[derive(Debug, Clone)]
pub struct Email(String);

impl Email {
    pub fn parse(s: &str) -> Result<Self, ValidationError> {
        if s.contains('@') && s.len() > 3 {
            Ok(Email(s.to_string()))
        } else {
            Err(ValidationError::InvalidEmail)
        }
    }
    
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

fn process_email(email: Email) -> Result<(), Error> {
    // No validation needed - the type guarantees correctness
    send_welcome_email(&email)?;
    update_user_email(&email)?;
    Ok(())
}

Key point: After parsing, the Email type guarantees a valid email throughout the entire application.

Advanced Patterns with Phantom Types

For more complex validation, phantom types encode state in the type system:

use std::marker::PhantomData;

struct Validated;
struct Unvalidated;

struct User<State> {
    name: String,
    email: String,
    _state: PhantomData<State>,
}

impl User<Unvalidated> {
    fn new(name: String, email: String) -> Self {
        User {
            name,
            email,
            _state: PhantomData,
        }
    }
    
    fn validate(self) -> Result<User<Validated>, ValidationError> {
        // Validation logic
        if self.email.contains('@') {
            Ok(User {
                name: self.name,
                email: self.email,
                _state: PhantomData,
            })
        } else {
            Err(ValidationError::InvalidEmail)
        }
    }
}

impl User<Validated> {
    fn save_to_database(&self) -> Result<(), DbError> {
        // Only validated users can be saved
        // ...
    }
}

In practice: A compile error when attempting to save an unvalidated user. No runtime checks needed.

Real-World Example: Configuration Parsing

#[derive(Debug)]
pub struct Config {
    port: Port,
    database_url: DatabaseUrl,
    api_key: ApiKey,
}

#[derive(Debug, Clone)]
pub struct Port(u16);

impl Port {
    pub fn parse(s: &str) -> Result<Self, ParseError> {
        let port: u16 = s.parse()?;
        if port > 1024 {
            Ok(Port(port))
        } else {
            Err(ParseError::PrivilegedPort)
        }
    }
}

#[derive(Debug, Clone)]
pub struct DatabaseUrl(String);

impl DatabaseUrl {
    pub fn parse(s: &str) -> Result<Self, ParseError> {
        if s.starts_with("postgres://") || s.starts_with("mysql://") {
            Ok(DatabaseUrl(s.to_string()))
        } else {
            Err(ParseError::InvalidDatabaseUrl)
        }
    }
}

// Parse the configuration once at startup
fn load_config() -> Result<Config, ParseError> {
    Ok(Config {
        port: Port::parse(&env::var("PORT")?)?,
        database_url: DatabaseUrl::parse(&env::var("DATABASE_URL")?)?,
        api_key: ApiKey::parse(&env::var("API_KEY")?)?,
    })
}

Tested in production. Configuration parsing fails fast at startup. Runtime guarantees of configuration validity.

Benefits in Practice

  1. No defensive programming - Types guarantee validity
  2. Clear error boundaries - Parsing happens at system boundaries
  3. Better performance - Validate once, not repeatedly
  4. Compile-time safety - Invalid operations don't compile

Try it: Replace string parameters with newtypes in one module. Watch the runtime errors disappear.

Common Patterns and Anti-Patterns

Do this:

pub struct UserId(u64);
pub struct Temperature(f64);
pub struct Percentage(u8); // 0-100 enforced at parse time

Avoid this:

fn process_data(user_id: u64, temp: f64, percent: u8) {
    if percent > 100 { panic!("Invalid percentage"); }
    // ...
}

In simple terms: Make invalid states unrepresentable. The compiler becomes your validation mechanism.

Parse input data at the system boundaries - HTTP requests, configuration files, user input. Inside the application, work exclusively with parsed types. Runtime checks disappear.

This pattern extends beyond simple validation. Use it for state machines, protocol implementations, and any domain where certain states must be impossible. Rust's zero-cost abstractions mean no runtime overhead for this safety.

Information is accurate as of the publication date. Terms, prices, and regulations may change — verify with relevant professionals.

✦ Squeeze AI
  1. Валидация по месту вызова вынуждает каждую функцию либо перепроверять данные (потеря производительности), либо слепо доверять вызывающей стороне (риск runtime-ошибок) — оба варианта ненадёжны.
  2. Принцип «Parse, Don't Validate»: входные данные парсятся один раз в отдельный тип (например, Email), и после этого компилятор гарантирует корректность по всей кодовой базе — повторные проверки не нужны.
  3. Phantom types позволяют закодировать состояние валидации прямо в типе (User<Unvalidated> vs User<Validated>): попытка вызвать save_to_database() на невалидированном объекте даёт ошибку компиляции, а не runtime-сбой.

Powered by B1KEY