tiny_multihash_derive/
lib.rs

1//! This proc macro derives a custom Multihash code table from a list of hashers.
2//!
3//! The digests are stack allocated with a fixed size. That size needs to be big enough to hold any
4//! of the specified hash digests. This cannot be determined reliably on compile-time, hence it
5//! needs to set manually via the `alloc_size` attribute. Also you might want to set it to bigger
6//! sizes then necessarily needed for backwards/forward compatibility.
7//!
8//! If you set `#mh(alloc_size = …)` to a too low value, you will get compiler errors. Please note
9//! the the sizes are checked only on a syntactic level and *not* on the type level. This means
10//! that digest need to have a size generic, which is a valid `typenum`, for example `U32` or
11//! `generic_array::typenum::U64`.
12//!
13//! You can disable those compiler errors with setting the `no_alloc_size_errors` attribute. This
14//! can be useful if you e.g. have specified type aliases for your hash digests and you are sure
15//! you use the correct value for `alloc_size`.
16//!
17//! # Example
18//!
19//! ```
20//! use tiny_multihash::derive::Multihash;
21//! use tiny_multihash::{U32, U64, MultihashCode};
22//!
23//! #[derive(Clone, Copy, Debug, Eq, Multihash, PartialEq)]
24//! #[mh(alloc_size = U64)]
25//! pub enum Code {
26//!     #[mh(code = 0x01, hasher = tiny_multihash::Sha2_256, digest = tiny_multihash::Sha2Digest<U32>)]
27//!     Foo,
28//!     #[mh(code = 0x02, hasher = tiny_multihash::Sha2_512, digest = tiny_multihash::Sha2Digest<U64>)]
29//!     Bar,
30//! }
31//!
32//! let hash = Code::Foo.digest(b"hello world!");
33//! println!("{:02x?}", hash);
34//! ```
35extern crate proc_macro;
36
37mod multihash;
38mod utils;
39
40use proc_macro::TokenStream;
41use proc_macro_error::proc_macro_error;
42use synstructure::{decl_derive, Structure};
43
44decl_derive!([Multihash, attributes(mh)] => #[proc_macro_error] multihash);
45fn multihash(s: Structure) -> TokenStream {
46    multihash::multihash(s).into()
47}