2 unstable releases

0.1.1 Apr 16, 2024
0.0.1 Apr 5, 2024

#1465 in Rust patterns

31 downloads per month

MIT/Apache

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 of Borrow of all inner primitives except floats. Provide const helper method to access inner primitive. Without this there's no way to access the wrapped primitive (Except for mem::transmute or via Display/FromStr, etc.).
  • serde: Generate implementations of Serialize and Deserialize to and from the representation of the primitive.
  • deref: Generate implementations of Deref and DerefMut.
#[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 bools cannot be directly used as if condition expressions nor can they be directly used in && and || (short-circuit) operations as these operators are not implementable. (TODO: Offer Deref<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

~270–720KB
~17K SLoC