simple/
simple.rs

1use composable_indexes::{Collection, aggregations, indexes};
2
3fn main() {
4    let mut db = Collection::<Person, _>::new(indexes::zip3(
5        // A hashtable index is useful for fast lookups
6        indexes::premap(|p: &Person| p.name.clone(), indexes::hashtable()),
7        // A btree index can provide max/min queries
8        indexes::premap(|p: &Person| p.birth_year, indexes::btree()),
9        // A grouped index can provide a "filtering" view
10        indexes::grouped(|p: &Person| p.starsign.clone(), || aggregations::count()),
11    ));
12
13    db.insert(Person::new("Alice".to_string(), 1990, StarSign::Aries));
14    db.insert(Person::new("Bob".to_string(), 1992, StarSign::Taurus));
15    db.insert(Person::new("Charlie".to_string(), 1991, StarSign::Aries));
16    db.insert(Person::new("Dave".to_string(), 1993, StarSign::Gemini));
17    let eve = Person::new("Eve".to_string(), 1984, StarSign::Cancer);
18    db.insert(eve.clone());
19    db.insert(Person::new("Frank".to_string(), 1995, StarSign::Gemini));
20    db.insert(Person::new("Grace".to_string(), 1996, StarSign::Cancer));
21    db.insert(Person::new("Heidi".to_string(), 1997, StarSign::Aries));
22
23    let q = db.query();
24
25    // Find a person by name, using the first index
26    let found = q.0.get_one(&"Eve".to_string());
27    assert_eq!(found, Some(&eve));
28
29    // Find the youngest person, using the second index
30    let youngest = q.1.max_one();
31    assert_eq!(
32        youngest,
33        Some((
34            &1997,
35            &Person::new("Heidi".to_string(), 1997, StarSign::Aries)
36        ))
37    );
38
39    // Count the number of Gemini for each star sign, using the third index
40    let gemini_count = q.2.get(&StarSign::Gemini);
41    assert_eq!(gemini_count, 2);
42}
43
44//
45
46#[derive(Debug, Clone, Hash, PartialEq, Eq)]
47enum StarSign {
48    Aries,
49    Taurus,
50    Gemini,
51    Cancer,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55struct Person {
56    name: String,
57    birth_year: u16,
58    starsign: StarSign,
59}
60
61impl Person {
62    fn new(name: String, birth_year: u16, starsign: StarSign) -> Self {
63        Self {
64            name,
65            birth_year,
66            starsign,
67        }
68    }
69}