nulid_derive
Derive macros for types that wrap Nulid.
This crate provides procedural macros to automatically implement common traits for newtype wrappers around Nulid, eliminating boilerplate code.
Features
The Id derive macro automatically implements:
TryFrom<String>- Parse from owned StringTryFrom<&str>- Parse from string sliceFrom<Nulid>- Create wrapper from NulidFrom<WrapperType> for Nulid- Extract inner NulidAsRef<Nulid>- Borrow inner Nulidstd::fmt::Display- Format as Base32 stringstd::fmt::Debug- Debug formattingstd::str::FromStr- Parse from string using.parse()Copy- Value semantics (automatically providesClone)PartialEqandEq- Equality comparisonPartialOrdandOrd- Ordering comparisonHash- Hashing support for collections
Usage
Add this to your Cargo.toml:
[]
= { = "0.5", = ["derive"] }
Then use the derive macro on your wrapper types:
use ;
;
;
Requirements
The derive macro requires:
- The type must be a tuple struct
- It must have exactly one field
- That field must be of type
Nulid
Valid examples:
; // ✓ Private field
; // ✓ Public field
Invalid examples:
; // ✗ Multiple fields
; // ✗ Wrong type
Type Safety
Using wrapper types provides type safety by preventing accidental mixing of different ID types:
use ;
;
;
let user_id = from;
let order_id = from;
process_user; // ✓ Correct type
// process_user(order_id); // ✗ Compile error: expected UserId, found OrderId
Error Handling
All parsing methods return Result<T, nulid::Error>, allowing proper error handling:
use ;
;
match try_from
Integration with Other Traits
The derive macro works well with other derive macros:
use ;
;
// Standard traits are automatically implemented!
// UserId now has: Debug, Copy (Clone), PartialEq, Eq, Hash, PartialOrd, Ord
// You can also add serde support if the serde feature is enabled in nulid
;
Examples
See the examples directory in the nulid repository for more usage examples.
License
This project is licensed under the MIT License - see the LICENSE file for details.