indexed_struct_macros/lib.rs
1pub(crate) mod derive;
2pub(crate) mod utils;
3
4use darling::FromDeriveInput;
5
6const DEFAULT_STRUCT_SUFFIX: &str = "Store";
7
8/// A derive macro that generates a store struct with index capabilities for the fields of a struct.
9///
10/// This macro generates a new struct with a `Store` suffix (configurable with the `name` attribute)
11/// that can store instances of the original struct with efficient indexing and querying capabilities.
12///
13/// ## Usage
14///
15/// The macro can be applied to a struct with optional attributes on the struct itself and its fields:
16///
17/// - On the struct:
18/// - `name = CustomStoreName`: Specify a custom name for the generated store struct
19/// - `key_type = Type`: Specify the default key type for the store (defaults to the type parameter)
20///
21/// - On fields:
22/// - `skip`: Skip this field in the generated store
23/// - `unique`: Enforce uniqueness constraint on this field
24/// - `index = "hash"`: Create a hash-based index for this field
25/// - `index = "btree"`: Create a B-tree based index for this field (ordered iteration)
26///
27/// ## Example
28///
29/// ```rs
30/// use indexed_struct::IndexedStruct;
31///
32/// #[derive(IndexedStruct)]
33/// struct Person {
34/// id: u32,
35/// #[indexed_struct(unique, index = "hash")]
36/// email: String,
37/// #[indexed_struct(index = "btree")]
38/// age: u32,
39/// #[indexed_struct(skip)]
40/// secret: String,
41/// }
42///
43/// // This generates a PersonStore struct with methods for inserting, querying, and managing Person instances
44/// ```
45#[proc_macro_derive(IndexedStruct, attributes(indexed_struct))]
46pub fn indexed_struct_derive2(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
47 let ast = syn::parse_macro_input!(input as syn::DeriveInput);
48
49 match derive::IndexedStructDerive::from_derive_input(&ast) {
50 Ok(mut derive) => match derive.init() {
51 Ok(derive) => derive.generate().into(),
52 Err(msg) => {
53 panic!("Error occurred while deriving IndexedStruct:\n\t{}", msg)
54 }
55 },
56 Err(e) => e.write_errors().into(),
57 }
58}