bilge_impl/
lib.rs

1use proc_macro::TokenStream;
2use proc_macro_error::proc_macro_error;
3
4mod bitsize;
5mod bitsize_internal;
6mod debug_bits;
7mod default_bits;
8mod fmt_bits;
9mod from_bits;
10mod try_from_bits;
11
12mod shared;
13
14/// Defines the bitsize of a struct or an enum.
15///
16/// e.g. `#[bitsize(4)]` represents the item as a u4, which is UInt<u8, 4> underneath.
17/// The size of structs is currently limited to 128 bits.
18/// The size of enums is limited to 64 bits.
19/// Please open an issue if you have a usecase for bigger bitfields.
20#[proc_macro_error]
21#[proc_macro_attribute]
22pub fn bitsize(args: TokenStream, item: TokenStream) -> TokenStream {
23    bitsize::bitsize(args.into(), item.into()).into()
24}
25
26/// This is internally used, not to be used by anything besides `bitsize`.
27/// No guarantees are given.
28#[proc_macro_error]
29#[proc_macro_attribute]
30pub fn bitsize_internal(args: TokenStream, item: TokenStream) -> TokenStream {
31    bitsize_internal::bitsize_internal(args.into(), item.into()).into()
32}
33
34/// Generate an `impl TryFrom<uN>` for unfilled bitfields.
35///
36/// This should be used when your enum or enums nested in
37/// a struct don't fill their given `bitsize`.
38#[proc_macro_error]
39#[proc_macro_derive(TryFromBits, attributes(bitsize_internal, fallback))]
40pub fn derive_try_from_bits(item: TokenStream) -> TokenStream {
41    try_from_bits::try_from_bits(item.into()).into()
42}
43
44/// Generate an `impl From<uN>` for filled bitfields.
45///
46/// This should be used when your enum or enums nested in
47/// a struct fill their given `bitsize` or if you're not
48/// using enums.
49#[proc_macro_error]
50#[proc_macro_derive(FromBits, attributes(bitsize_internal, fallback))]
51pub fn derive_from_bits(item: TokenStream) -> TokenStream {
52    from_bits::from_bits(item.into()).into()
53}
54
55/// Generate an `impl core::fmt::Debug` for bitfield structs.
56///
57/// Please use normal #[derive(Debug)] for enums.
58#[proc_macro_error]
59#[proc_macro_derive(DebugBits, attributes(bitsize_internal))]
60pub fn debug_bits(item: TokenStream) -> TokenStream {
61    debug_bits::debug_bits(item.into()).into()
62}
63
64/// Generate an `impl core::fmt::Binary` for bitfields.
65#[proc_macro_error]
66#[proc_macro_derive(BinaryBits)]
67pub fn derive_binary_bits(item: TokenStream) -> TokenStream {
68    fmt_bits::binary(item.into()).into()
69}
70
71/// Generate an `impl core::default::Default` for bitfield structs.
72#[proc_macro_error]
73#[proc_macro_derive(DefaultBits)]
74pub fn derive_default_bits(item: TokenStream) -> TokenStream {
75    default_bits::default_bits(item.into()).into()
76}