9 releases

0.1.8 Dec 30, 2022
0.1.7 Nov 14, 2022

#1484 in Procedural macros

Download history 4/week @ 2022-11-27 13/week @ 2022-12-04 6/week @ 2022-12-11 21/week @ 2022-12-18 32/week @ 2022-12-25 8/week @ 2023-01-01 9/week @ 2023-01-08 4/week @ 2023-01-15 8/week @ 2023-01-22 14/week @ 2023-01-29 12/week @ 2023-02-05 12/week @ 2023-02-12 31/week @ 2023-02-19 19/week @ 2023-02-26 4/week @ 2023-03-05 1/week @ 2023-03-12

56 downloads per month
Used in enum-ptr

MIT/Apache

7KB
91 lines

Enum Ptr

crates.io docs.rs

This crate provides a custom derive macro EnumPtr to automatically generate bridges between T and Compact<T> with the minimum cost. Compact<T> is the compact representation of T, and it is only one pointer wide.

For example, the following code

use enum_ptr::EnumPtr;

#[derive(EnumPtr)]
#[repr(C, usize)]
enum Foo<'a> {
    A(&'a i32),
    B(Option<Box<i32>>),
}

will generate

impl<'a> From<Foo<'a>> for enum_ptr::Compact<Foo<'a>> {
    // ...
}

impl<'a> From<enum_ptr::Compact<Foo<'a>>> for Foo<'a> {
    // ...
}

Since &i32 and Box<i32> are aligned by 4 bytes, the lowest 2 bits of them are always zeros. Compact<Foo<'a>> utilizes these bits to store the tag (discriminant value).

Features

  • No need to write unsafe pointer operations
  • Supports various pointer types and can be extended
  • Supports no_std
  • Minimum type conversion cost
  • Passes cargo +nightly miri test with strict provenance enabled.

Usage

Dependencies

[dependencies]
enum-ptr = "*"

With no_std support:

[dependencies]
enum-ptr = { version = "*", default-features = false }

Code

See docs.rs

Testing

$ cargo test
$ cargo test --no-default-features
$ cargo +nightly miri test
$ cargo +nightly miri test --no-default-features

Credits

  • Thanks to @oxalica for reviewing this crate and providing a lot of helpful suggestions.

License

This project is licensed under either of

at your option.

Dependencies

~0.6–1MB
~26K SLoC