pipecircuit 0.0.2

Correct. Robust. Fast. Portable.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#![cfg(feature = "storage")]

use core::num::NonZeroU32;

use pipecircuit::storage::warp_table::{
    Capacity, WarpId, WarpTable, WarpTableGetOutcome, WarpTableInsertAllOutcome,
    WarpTableInsertOutcome, WarpTableInsertWithIdOutcome, WarpTableRow, WarpTableUpdateOutcome,
    WarpTableUpsertOutcome,
};
#[cfg(feature = "secondary-indexes")]
use pipecircuit::storage::warp_table::{
    RangeIndexKey, WarpTableRemoveOutcome, WarpTableRowRelocation,
};

#[derive(WarpTableRow)]
struct Pet {
    name: &'static str,
    age: u8,
}

#[derive(Debug, Eq, WarpTableRow, PartialEq)]
#[index(primary = u64)]
struct ImportedPet {
    name: &'static str,
}

#[cfg(feature = "secondary-indexes")]
#[derive(WarpTableRow)]
struct CategorizedPet {
    name: &'static str,
    #[index(secondary, range)]
    pub age: u8,
}

#[cfg(feature = "secondary-indexes")]
#[derive(WarpTableRow)]
#[index(primary = u64)]
struct ImportedCategorizedPet {
    name: &'static str,
    #[index(secondary)]
    pub age: u8,
}

#[cfg(feature = "secondary-indexes")]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, RangeIndexKey)]
struct Age(u8);

#[cfg(feature = "secondary-indexes")]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, RangeIndexKey)]
struct Temperature {
    degrees: i16,
}

#[cfg(feature = "secondary-indexes")]
#[derive(WarpTableRow)]
struct MeasuredPet {
    name: &'static str,
    #[index(range)]
    age: Age,
    #[index(range)]
    temperature: Temperature,
}

#[cfg(feature = "secondary-indexes")]
#[derive(WarpTableRow)]
struct Owner {
    name: &'static str,
}

#[cfg(feature = "secondary-indexes")]
#[derive(WarpTableRow)]
struct OwnedPet {
    name: &'static str,
    #[index(secondary)]
    owner: WarpId<Owner>,
}

#[test]
fn default_ids_are_typed_generated_and_directly_available() -> Result<(), &'static str> {
    let capacity = Capacity::new(NonZeroU32::new(2).ok_or("capacity was zero")?);
    let mut pets =
        WarpTable::<Pet>::try_new(capacity).map_err(|_| "pet storage was unavailable")?;

    let WarpTableInsertOutcome::Inserted { key: luna_id, .. } = pets.insert(Pet {
        name: "Luna",
        age: 4,
    }) else {
        return Err("Luna could not be inserted");
    };

    assert_eq!(luna_id, WarpId::<Pet>::MIN);
    let WarpTableGetOutcome::Present { row } = pets.get(luna_id) else {
        return Err("Luna was unavailable");
    };
    assert_eq!(*row.id, luna_id);
    assert_eq!(*row.name, "Luna");
    assert_eq!(row.age, &4);
    assert_eq!(
        pets.update(luna_id, |mut pet| {
            let previous = (*pet.name(), *pet.age());
            *pet.name_mut() = "Luna II";
            *pet.age_mut() = 5;
            previous
        }),
        WarpTableUpdateOutcome::Updated {
            key: luna_id,
            row: 0,
            output: ("Luna", 4),
        }
    );
    let WarpTableGetOutcome::Present { row } = pets.get(luna_id) else {
        return Err("updated Luna was unavailable");
    };
    assert_eq!((*row.name, *row.age), ("Luna II", 5));
    Ok(())
}

#[test]
fn an_existing_primary_id_slots_in_explicitly() -> Result<(), &'static str> {
    let capacity = Capacity::new(NonZeroU32::MIN);
    let mut pets = WarpTable::<ImportedPet>::try_new(capacity)
        .map_err(|_| "imported pet storage was unavailable")?;

    let WarpTableInsertWithIdOutcome::Inserted { key, .. } =
        pets.insert_with_id(42, ImportedPet { name: "Milo" })
    else {
        return Err("Milo could not be inserted");
    };
    assert_eq!(key, 42);
    let WarpTableGetOutcome::Present { row, .. } = pets.get(42) else {
        return Err("Milo was unavailable");
    };
    assert_eq!(*row.name, "Milo");
    Ok(())
}

#[test]
fn upsert_inserts_replaces_at_capacity_and_returns_rejected_rows() -> Result<(), &'static str> {
    let capacity = Capacity::new(NonZeroU32::MIN);
    let mut pets = WarpTable::<ImportedPet>::try_new(capacity)
        .map_err(|_| "imported pet storage was unavailable")?;

    assert_eq!(
        pets.upsert(42, ImportedPet { name: "Luna" }),
        WarpTableUpsertOutcome::Inserted { key: 42, row: 0 }
    );
    assert_eq!(
        pets.upsert(42, ImportedPet { name: "Luna II" }),
        WarpTableUpsertOutcome::Replaced {
            key: 42,
            row: 0,
            previous: ImportedPet { name: "Luna" },
        }
    );
    assert_eq!(
        pets.upsert(7, ImportedPet { name: "Milo" }),
        WarpTableUpsertOutcome::Full {
            key: 7,
            rejected: ImportedPet { name: "Milo" },
        }
    );
    let WarpTableGetOutcome::Present { row } = pets.get(42) else {
        return Err("upserted pet was unavailable");
    };
    assert_eq!(*row.name, "Luna II");
    Ok(())
}

#[cfg(feature = "secondary-indexes")]
#[test]
fn branded_ids_are_secondary_index_keys_across_tables() -> Result<(), &'static str> {
    let capacity = Capacity::new(NonZeroU32::MIN);
    let mut owners =
        WarpTable::<Owner>::try_new(capacity).map_err(|_| "owner storage was unavailable")?;
    let WarpTableInsertOutcome::Inserted { key: owner_id, .. } =
        owners.insert(Owner { name: "Ken" })
    else {
        return Err("owner could not be inserted");
    };
    let mut pets =
        WarpTable::<OwnedPet>::try_new(capacity).map_err(|_| "pet storage was unavailable")?;
    let WarpTableInsertOutcome::Inserted { .. } = pets.insert(OwnedPet {
        name: "Luna",
        owner: owner_id,
    }) else {
        return Err("pet could not be inserted");
    };

    let mut matches = pets.query().find_owner(owner_id).rows();
    let Some(pet) = matches.next() else {
        return Err("owned pet was unavailable");
    };
    assert_eq!((*pet.name, *pet.owner), ("Luna", owner_id));
    assert!(matches.next().is_none());
    Ok(())
}

#[test]
fn bulk_insertion_observes_every_generated_id_and_rejected_row() -> Result<(), &'static str> {
    let capacity = Capacity::new(NonZeroU32::new(2).ok_or("capacity was zero")?);
    let mut pets =
        WarpTable::<Pet>::try_new(capacity).map_err(|_| "pet storage was unavailable")?;
    let mut inserted = Vec::new();
    let mut rejected = Vec::new();

    let outcome = pets.insert_all(
        [
            Pet {
                name: "Luna",
                age: 4,
            },
            Pet {
                name: "Milo",
                age: 7,
            },
            Pet {
                name: "Suki",
                age: 9,
            },
        ],
        |outcome| match outcome {
            WarpTableInsertOutcome::Inserted { key, .. } => inserted.push(key),
            WarpTableInsertOutcome::Full { rejected: pet }
            | WarpTableInsertOutcome::IdentifiersExhausted { rejected: pet } => {
                rejected.push(pet.name);
            }
        },
    );

    assert_eq!(outcome, WarpTableInsertAllOutcome::Completed);
    assert_eq!(inserted.len(), 2);
    assert_eq!(rejected, ["Suki"]);
    assert_eq!(pets.len(), 2);
    Ok(())
}

#[test]
fn bulk_caller_ids_preserve_duplicate_and_capacity_outcomes() -> Result<(), &'static str> {
    let capacity = Capacity::new(NonZeroU32::new(2).ok_or("capacity was zero")?);
    let mut pets = WarpTable::<ImportedPet>::try_new(capacity)
        .map_err(|_| "imported pet storage was unavailable")?;
    let mut inserted = Vec::new();
    let mut rejected = Vec::new();

    let outcome = pets.insert_all_with_id(
        [
            (42, ImportedPet { name: "Luna" }),
            (42, ImportedPet { name: "Duplicate" }),
            (7, ImportedPet { name: "Milo" }),
            (9, ImportedPet { name: "Suki" }),
        ],
        |outcome| match outcome {
            WarpTableInsertWithIdOutcome::Inserted { key, .. } => inserted.push(key),
            WarpTableInsertWithIdOutcome::AlreadyPresent {
                key, rejected: pet, ..
            }
            | WarpTableInsertWithIdOutcome::Full { key, rejected: pet } => {
                rejected.push((key, pet.name));
            }
        },
    );

    assert_eq!(outcome, WarpTableInsertAllOutcome::Completed);
    assert_eq!(inserted, [42, 7]);
    assert_eq!(rejected, [(42, "Duplicate"), (9, "Suki")]);
    assert_eq!(pets.len(), 2);
    Ok(())
}

#[test]
fn logical_rows_scan_in_dense_order_with_identity() -> Result<(), &'static str> {
    let capacity = Capacity::new(NonZeroU32::new(2).ok_or("capacity was zero")?);
    let mut pets =
        WarpTable::<Pet>::try_new(capacity).map_err(|_| "pet storage was unavailable")?;
    let WarpTableInsertOutcome::Inserted { key: luna_id, .. } = pets.insert(Pet {
        name: "Luna",
        age: 4,
    }) else {
        return Err("Luna could not be inserted");
    };
    let WarpTableInsertOutcome::Inserted { key: milo_id, .. } = pets.insert(Pet {
        name: "Milo",
        age: 7,
    }) else {
        return Err("Milo could not be inserted");
    };

    let mut rows = pets.rows();
    assert_eq!(rows.len(), 2);
    let Some(first) = rows.next() else {
        return Err("first logical row was unavailable");
    };
    assert_eq!((*first.id, first.name, first.age), (luna_id, &"Luna", &4));
    assert_eq!(rows.len(), 1);
    let Some(second) = rows.next() else {
        return Err("second logical row was unavailable");
    };
    assert_eq!(
        (*second.id, second.name, second.age),
        (milo_id, &"Milo", &7)
    );
    assert_eq!(rows.len(), 0);
    assert!(rows.next().is_none());
    assert!(rows.next().is_none());
    Ok(())
}

#[cfg(feature = "secondary-indexes")]
#[test]
fn range_key_wrappers_preserve_their_inner_ordering() -> Result<(), &'static str> {
    assert_eq!(Age::BITS, u8::BITS);
    assert_eq!(Age(7).ordered_word(), 7);
    assert!(Temperature { degrees: -1 }.ordered_word() < Temperature { degrees: 1 }.ordered_word());

    let capacity = Capacity::new(NonZeroU32::new(2).ok_or("capacity was zero")?);
    let mut pets = WarpTable::<MeasuredPet>::try_new(capacity)
        .map_err(|_| "measured pet storage was unavailable")?;
    for (name, age, degrees) in [("Luna", 4, -2), ("Milo", 7, 3)] {
        let WarpTableInsertOutcome::Inserted { .. } = pets.insert(MeasuredPet {
            name,
            age: Age(age),
            temperature: Temperature { degrees },
        }) else {
            return Err("measured pet could not be inserted");
        };
    }

    let ages = pets
        .query()
        .find_age_in(Age(4)..=Age(6))
        .map_err(|_| "age range was unavailable")?;
    let Some(luna) = ages.rows().next() else {
        return Err("Luna was absent from the wrapped range");
    };
    assert_eq!((*luna.name, *luna.age), ("Luna", Age(4)));
    Ok(())
}

#[cfg(feature = "secondary-indexes")]
#[test]
fn a_secondary_field_generates_an_external_lookup_surface() -> Result<(), &'static str> {
    let capacity = Capacity::new(NonZeroU32::MIN);
    let mut pets = WarpTable::<CategorizedPet>::try_new(capacity)
        .map_err(|_| "categorized pet storage was unavailable")?;
    let WarpTableInsertOutcome::Inserted {
        key,
        row: dense_row,
    } = pets.insert(CategorizedPet {
        name: "Luna",
        age: 4,
    })
    else {
        return Err("categorized pet could not be inserted");
    };

    assert_eq!(dense_row, 0);
    let selection = pets.query().find_age(4);
    assert_eq!(selection.len(), 1);
    let Some(row) = selection.rows().next() else {
        return Err("age membership did not resolve to Luna");
    };
    assert_eq!(*row.id, key);
    assert_eq!((row.name, row.age), (&"Luna", &4));
    let ranged = pets
        .query()
        .find_age_in(3..5)
        .map_err(|_| "age range index was inconsistent")?;
    assert_eq!(ranged.len(), 1);
    let WarpTableGetOutcome::Present { row, .. } = pets.get(key) else {
        return Err("Luna was unavailable by primary key");
    };
    assert_eq!(row.name, &"Luna");
    assert_eq!(row.age, &4);
    Ok(())
}

#[cfg(feature = "secondary-indexes")]
#[test]
fn caller_owned_ids_flow_through_secondary_queries() -> Result<(), &'static str> {
    let capacity = Capacity::new(NonZeroU32::new(2).ok_or("capacity was zero")?);
    let mut pets = WarpTable::<ImportedCategorizedPet>::try_new(capacity)
        .map_err(|_| "imported pet storage was unavailable")?;
    for (id, name) in [(42, "Luna"), (9001, "Milo")] {
        let WarpTableInsertWithIdOutcome::Inserted { key, .. } =
            pets.insert_with_id(id, ImportedCategorizedPet { name, age: 4 })
        else {
            return Err("imported pet could not be inserted");
        };
        assert_eq!(key, id);
    }

    let selection = pets.query().find_age(4);
    let mut rows = selection.rows();
    assert_eq!(rows.size_hint(), (2, Some(2)));
    #[cfg(target_pointer_width = "64")]
    assert_eq!(rows.len(), 2);
    let Some(row) = rows.next_back() else {
        return Err("last imported pet was unavailable");
    };
    assert_eq!((*row.id, row.name), (9001, &"Milo"));
    assert_eq!(rows.size_hint(), (1, Some(1)));
    #[cfg(target_pointer_width = "64")]
    assert_eq!(rows.len(), 1);
    let Some(row) = rows.next() else {
        return Err("first imported pet was unavailable");
    };
    assert_eq!((*row.id, row.name), (42, &"Luna"));
    assert!(rows.next().is_none());
    assert!(rows.next_back().is_none());

    assert!(matches!(
        pets.remove(42),
        WarpTableRemoveOutcome::Removed {
            key: 42,
            relocation: WarpTableRowRelocation::Relocated {
                key: 9001,
                from: 1,
                to: 0,
            },
            ..
        }
    ));
    let selection = pets.query().find_age(4);
    let Some(row) = selection.rows().next() else {
        return Err("relocated imported pet was unavailable");
    };
    assert_eq!((*row.id, row.name), (9001, &"Milo"));
    Ok(())
}