2 unstable releases
0.1.1 | Apr 16, 2024 |
---|---|
0.0.1 | Apr 5, 2024 |
#1862 in Rust patterns
52KB
1.5K
SLoC
#[strongly::typed]
A proc macro to create strongly-typed primitives.
[!CAUTION] Work in progress. Do not use yet. More details to follow.
Usage
Add the #[strongly::typed]
attribute to your newtype struct to turn
it into a strongly-typed primitive. Supports all integers and floats, plus
bool
and char
.
#[strongly::typed]
struct MyType(u8);
The attribute will also add all nine possible default derives (Copy
, Clone
,
Default
, etc.) and set #[repr(transparent)]
.
Parameters
- convert: Generate implemetations of
From
/Into
between inner and outer types. Also add implementation ofBorrow
of all inner primitives except floats. Provideconst
helper method to access inner primitive. Without this there's no way to access the wrapped primitive (Except formem::transmute
or viaDisplay
/FromStr
, etc.). - serde: Generate implementations of
Serialize
andDeserialize
to and from the representation of the primitive. - deref: Generate implementations of
Deref
andDerefMut
.
#[strongly::typed(convert, serde)]
pub struct MyType(pub usize);
Purpose
The types generated by this crate are meant to fill the gap between using an untyped primitive and a specialized newtype struct. They're meant to be used as drop-in replacements for the primitives while providing the same isolation as newtype structs.
The generated types implement all the traits and provide (almost) all the constants, functions and methods of the wrapped primitives. They are a very thin layer and will disappear during compilation.
Caveats
- It's not possible to loop over strongly-typed integer ranges because the
Step
trait is unstable. Instead, the macro generates helper methods to create (strongly-typed) iterators. - Strongly-typed
bool
s cannot be directly used asif
condition expressions nor can they be directly used in&&
and||
(short-circuit) operations as these operators are not implementable. (TODO: OfferDeref<Target=bool>
via feature for convenience.) - Doc comments are largely missing, except for trait impls. (TODO: Generate links to doc comments of primitives.)
Crate Features
- Default: std
- std: Doesn't do anything at the moment. None of the generated code requires
std
.
Dependencies
~225–670KB
~16K SLoC