indexed-struct 0.1.0

A derive macro for creating indexed data structure with efficient query capabilities
Documentation

indexed-struct

A Rust derive macro for creating indexed data structure with efficient query capabilities

Usage

use indexed_struct::IndexedStruct;

#[derive(IndexedStruct)]
struct Cat {
    #[indexed_struct(unique, index = "hash")]
    name: String,

    #[indexed_struct(index = "btree")]
    age: u16,

    birthday: u64,  // Not indexed
}

fn main() {
    let mut store: CatStore<usize> = CatStore::new();

    // Insert a record with primary key 1
    store.insert(1, Cat {
        name: "Fluffy".to_string(),
        age: 3,
        birthday: 1000,
    }).unwrap();

    // Query by primary key
    let cat = store.query(&1);

    // Query by indexed field
    let cat_by_name = store.query_name(&"Fluffy".to_string());

    // Query by non-unique indexed field (returns iterator)
    let cats_by_age = store.query_age(&3);
}

The generated struct will look like this:

#[derive(Default)]
struct CatStore<KeyType> {
    rows: HashMap<KeyType, Cat>,
    index_name: HashMap<String, KeyType>,
    index_age: BTreeMap<u16,HashSet<KeyType>>,
}

Macro Attributes

Struct Attributes

The IndexedStruct derive macro supports the following attributes on the struct itself:

  • #[indexed_struct(name = CustomName)]: Customize the name of the generated storage struct. By default, it appends "Store" to the original struct name.
  • #[indexed_struct(key_type = KeyType)]: Customize the default key type used for the primary key. By default, no default is provided and you must specify it when using the store.

Example with struct attributes:

use indexed_struct::IndexedStruct;

#[derive(IndexedStruct)]
#[indexed_struct(name = Pets, key_type = u32)]
struct Pet {
    #[indexed_struct(unique, index = "hash")]
    name: String,
    #[indexed_struct(index = "btree")]
    age: u16,
}

// This will generate a Pets<u32> struct with u32 as the default key type

Generated Methods

The macro generates various methods for efficient data access:

  • insert, remove: Basic CRUD operations
  • query_{field}: Query by indexed field values
  • contain_{field}: Check if indexed field value exists
  • update_{field}: Update specific field values
  • iter_by_{field}: Iterate ordered by indexed field
  • rows_by_{field}: Get rows by indexed field

Field Attributes

attr type default description
unique bool false Enforces value uniqueness constraint
index enum "none" Index type for efficient queries ("none", "hash", "btree")
skip bool false Ignore this field

Index Types:

  • none: No index: Linear search through all records O(n)
  • hash: Hash map index for O(1) average lookup time using hashbrown HashMap
  • btree: B-tree index for O(log n) lookup time with ordered iteration using std BTreeMap