Crate id_newtype

Crate id_newtype 

Source
Expand description

Implements logic for a Cow<'static, str> newtype where only [A-Za-z0-9_] are valid characters.

Implementations are provided for:

  • IdType::new
  • IdType::new_unchecked (with #[doc(hidden)])
  • IdType::is_valid_id
  • IdType::into_inner
  • std::borrow::Borrow<str>
  • std::convert::AsRef<str>
  • std::convert::TryFrom<String>
  • std::convert::TryFrom<&'static str>
  • std::fmt::Display
  • std::ops::Deref
  • std::ops::DerefMut
  • std::str::FromStr

A separate error type is also generated, which indicates an invalid value when the ID type is instantiated with new.

§Usage

In Cargo.toml:

id_newtype = "0.2.0" # or
id_newtype = { version = "0.2.0", features = ["macros"] }

In code:

// in lib.rs
#[macro_use]
extern crate id_newtype;

// in your ID module, e.g. `my_id.rs`
use std::borrow::Cow;

// Rename your ID type
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct MyId(Cow<'static, str>);

id_newtype::id_newtype!(
    MyId,           // Name of the ID type
    MyIdInvalidFmt  // Name of the invalid value error
);

If you have a procedural macro that checks for ID validity1 at compile time, you may pass in its name as follows:

#[macro_use]
extern crate id_newtype;

use std::borrow::Cow;

// Either use `id_newtype::id`, or replace this with your own proc macro.
use id_newtype::id;
// use my_crate_static_check_macros::my_id;

// Rename your ID type
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct MyId(Cow<'static, str>);

id_newtype::id_newtype!(
    MyId,           // Name of the ID type
    MyIdInvalidFmt, // Name of the invalid value error
    my_id           // Name of the proc macro
);

1 You can either enable the "macros" feature and have access to the id! macro, or implement your own proc macro. See id_newtype_macros for an example.

§Features

  • "macros" This feature enables the id! compile-time checked proc macro for safe construction of IDs at compile time.

    #[macro_use]
    extern crate id_newtype;
    use id_newtype::id;
    
    // Define a new ID type
    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
    pub struct MyId(Cow<'static, str>);
    id_newtype::id_newtype!(MyId, MyIdInvalidFmt, id);
    
    // ok!
    let id = id!("my_id");
    
    // `id` is not a valid `Id`
    // `Id`s must begin with a letter or underscore, and contain only
    // letters, numbers, or underscores.
    let id = id!("invalid id");

Macros§

id_newtype