nova 0.2.3

Newtype macros for commonly reused types in Rust.
Documentation

nova

Documentation

Create newtypes with great convenience.

All types generated by the following macros implement Debug, Clone, Eq, PartialEq, Ord, PartialOrd and Hash. For Copy types, the newtype also implements Copy.

For convenience, each type is also generated with a conditional derive for serde serialisation and deserialisation. This is enabled with the serde feature in your own crate, if desired.

Example

In this example, we create a PhoneNumber newtype wrapper around a string. We use the macro to generate the type, then implement a new function for creating it. The inner field of the newtype is only accessible from the same module, so this ensures that the type can only be created by methods designed to validate and assert that the type is valid.

// Creates the PhoneNumber newtype here.
nova::string!(PhoneNumber);

impl PhoneNumber {
    pub fn new(input: String) -> PhoneNumber {
        // An extremely poorly implemented phone number validator.
        assert_eq!(input.len(), 10);

        Self(input)
    }
}

fn blah() {
    let n = PhoneNumber::new("1234567890".to_string());
    let m = PhoneNumber::new("1234567890".to_string());
    let o = PhoneNumber::new("1234567891".to_string());
    assert_eq!(n, m);
    assert_ne!(n, o);
    assert!(n < o);
    
    // Deref to get a &str
    let _s: &str = &*n;

    // into_inner to take back the String
    let _s = n.into_inner();     
}

Features

  • std (default): use std library
  • uuid: add support for uuid::Uuid type
  • heapless: use heapless to provide Vec and String implementations

Usage in no_std environments

Usually you'll want to enable heapless functionality when in a no_std environment. When declaring the crate in your Cargo.toml, do it like this:

nova = { version = "0.2", default-features = false, features = ["heapless"] }

License

This project is licensed under either of

at your option.