proomt

Search

Search posts, papers, and topics

All posts

Eli Bendersky6 min readintermediate

Rusty thoughts on "Parse, don't validate"

Summary

This post reviews the "Parse, don't validate" pattern in Rust, advocating for using the type system to enforce data invariants at compile time rather than relying on runtime checks. It demonstrates how custom types like NonEmpty<T>, AbsPathBuf, and NonZero prevent invalid states, improving code clarity and safety.

  • Use custom types (e.g., NonEmpty<T>) to encode invariants like "not empty" directly into the type system.
  • Type refinement allows gradual validation, transforming generic data into more specific, validated types (e.g., PathBuf -> Utf8PathBuf -> AbsPathBuf).
  • Rust's NonZero types prevent division by zero and enable Option optimizations by using zero as a sentinel.
  • Serde deserialization exemplifies "parse, don't validate" by mapping JSON to types that enforce schema and value constraints.

Rust developers can leverage the type system to build more robust and maintainable applications by shifting validation from runtime checks to compile-time guarantees.

7/10

Related reading

  1. Parse, Don't Validate

    The post argues for “parse, don’t validate”: instead of checking inputs and discarding the information, convert them into richer types that encode the validation result. Using Haskell’s NonEmpty type turns a partial head function into a total one, eliminating redundant runtime checks and catching bugs at compile time.

    Hall of Famegithub.io18 minHN642230
  2. Rust's derive often implies inline

    Rust's `#[derive]` macros automatically add `#[inline]` to generated trait implementations. While helpful for trivial code, large derived `Debug` impls can bloat binaries, and you can suppress this with a custom proc macro that uses `#[inline(never)]`.

    Lobstersyossarian.net2 minlobste.rs63
  3. Cylic trait implementations: motivation

    The post introduces the problem of cyclic trait implementations in Rust, showing how allowing certain cycles could enable “perfect derive” that derives traits based on field types rather than generic bounds. It also explains why naïvely accepting any cycle is unsound, especially with supertraits, and outlines the need for a principled solution.

    Mozilla Automation Teamsmallcultfollowing.com9 minHN1
  4. Eliminating AI Code Hallucinations with TypeScript Compiler Diagnostics and TDD Loops

    The article shows how to replace raw TypeScript compiler output with a programmatic JSON feedback loop that merges diagnostics and Vitest test failures, feeding the structured data back to an LLM coding agent for self‑correction. It provides concrete code for extracting, enriching, validating, and de‑duplicating errors, and demonstrates token savings and deterministic iteration until compilation…

    SitePointsitepoint.com15 min