Nutype 0.7.0: the newtype with guarantees now supports conditional `cfg_attr` derives

57 points greyblake 6 comments

Release notes: https://github.com/greyblake/nutype/releases/tag/v0.7.0

README: https://github.com/greyblake/nutype

What is nutype?

Nutype is a proc macro that adds sanitization and validation to newtypes, ensuring values always pass checks, even with serde deserialization or FromStr parsing. If a function takes a Username, you know it is a valid username, no defensive checks, no scattered assertions.

What's new in 0.7.0

  • cfg_attr for conditional derives (e.g. derive Serialize / Deserialize only behind a feature flag)
  • where clauses in generic newtypes, including Higher-Ranked Trait Bounds (HRTB)
  • Constructor visibility: constructor(visibility = pub(crate))
  • len_utf16_min / len_utf16_max validators (handy for JavaScript interop)
  • Derive Valuable (behind the valuable feature) for structured logging with tracing
  • [BREAKING] derive_unsafe was renamed to derive_unchecked

Example: conditional derives via cfg_attr

use nutype::nutype;

#[nutype(
    sanitize(trim, lowercase),
    validate(not_empty, len_char_max = 100),
    derive(Debug, Clone, PartialEq, AsRef),
    cfg_attr(feature = "serde", derive(Serialize, Deserialize))
)]
pub struct Email(String);

Serialize and Deserialize are only derived when the serde feature is enabled. Complex predicates like all(...), any(...), not(...) work, and you can stack multiple cfg_attr(..) lines.

Feedback, ideas and bug reports very welcome.