Storage: Choose a Collection by Its Contract

Audience task and outcome

  • Task Decide how a new saved field should be stored, for three real requirements.
  • Observable outcome The viewer can match a requirement to a collection from the documented list, convert incoming values into saved ones, state the size limit the app itself enforces, and say when a module should select the Hylix engine. They can explain the three choices in the examples in one sentence each.
  • Starting point Lesson 3 used Inventory's item table through its methods. This film opens its declaration.
  • Handoff Lesson 5 moves to the public side of the app, where saved types never appear.
  • Pacing Three and a half minutes. Each requirement is one scene.

The worked example

Three declarations from the checkout answer three different requirements. The Shop's Inventory looks items up by number and stores them in a Map<u64, Item> capped at 1024 entries. RRT Heavy16's admissions module records requests in arrival order in a Vec<Entry> with a cursor and caps of 16_384 receipts and 4096 pending. The Shop's Branches gives each branch a whole module through a ChildMap. A fourth excerpt shows a module that selects the Hylix engine. Inventory data · Inventory service · Heavy16 admissions data · Heavy16 admissions service · Branches data · Hylix counter declaration

The collections guide lists each collection with its operations, and the engine guide says how to choose between Nyxus and Hylix. The Minima sample supplies a separate case, a fixed-width lookup index that readers use between rebuilds. Collections · Storage engines · Minima index declaration

The story in one pass

Put the collection shelf on screen. Take the first requirement, lookup by key, and land on Inventory's map with its limit. Take the second, arrival order with a position, and land on Heavy16's receipt list. Show how an incoming value becomes a saved one. Take the third, an entry with its own lifetime, and land on a child module map. Then show the single place where a module chooses its engine and what that choice asks of the author.

Views and visual objects

Use the shared visual language. The new object is the Shelf, a row of small collection cards. Each card has the collection's name and one line taken from the guide's table.

Card Line on the card
Map<K, V> get, insert, remove, range, in key order
Set<T> membership, insert, remove, range
Vec<T> push, pop, index
Queue<T> push and pop at both ends
String saved text
Box, Rc, Weak one owned value, or shared ownership
ChildMap<K, M> one whole module per key

The first six cards are Nyxus collections from cdk_rsx_collections::nyxus. ChildMap belongs to the Store and sits at the end of the shelf with a module-card outline. A StateCard beside each declaration shows a few plain rows so the viewer sees values, never storage.

View Framing and anchor
shelf The Shelf across the top, empty stage below.
choice The Shelf on top, one EditorPane at left, one StateCard at right. A requirement note sits above the pane.
engine_choice Two EditorPane columns with one memory attribute each, and a two-row comparison beneath.

Scene by_key — Look something up

Enters with The Inventory card from lesson 3 with its drawer open.

Beat shelf — The list to choose from

View and focus shelf.

Show The seven Shelf cards. The import line use cdk_rsx_collections::nyxus::{Map, NyxusData}; from inventory/memory/v1.rs line 2 sits under the shelf.

Narration

For saved fields, start with the SDK's collections. Map looks up entries by key. Vec keeps a list you can index. Queue lets you add and remove at either end. These values can be kept between calls and across upgrades.

Cue and animation On “the SDK's collections”, reveal the cards and band the import line. On “looks up entries by key”, highlight Map. On “kept between calls”, give each card a small saved tab.

Leaves with The complete shelf.

Beat inventory_map — Items by number

View and focus choice. Requirement note reads find an item by its number.

Show src/inventory/memory/v1.rs lines 3 to 13.

#[repr(C)]
#[derive(Clone, Copy, NyxusData)]
pub(in crate::inventory) struct Item {
    pub price: u64,
    pub stock: u32,
}
#[repr(C)]
#[derive(NyxusData)]
pub struct Data {
    pub(in crate::inventory) items: Map<u64, Item>,
}

Narration

Inventory needs to find an item by its number, so it saves a map from item number to a small Item struct. The struct derives Nyxus data, which is what lets it be a saved value. Code under the module reads and changes entries with ordinary map methods.

Cue and animation On “find an item by its number”, light the Map card and draw a line to Map<u64, Item>. On “derives Nyxus data”, band NyxusData on both derives. On “ordinary map methods”, show the StateCard rows 44 → price 100, stock 5 and flash get, insert and get_mut beside it.

Leaves with The Map card linked to Inventory's declaration.

Beat own_limit — The app sets the size limit

View and focus choice, pane switches to src/inventory/mod.rs.

Show Line 4 and lines 30 to 34.

const MAX_ITEMS: usize = 1024;
        let mut data = self.memory.write()?;
        if !data.items.contains_key(&item) && data.items.len() >= MAX_ITEMS {
            return Ok(false);
        }

Narration

A map will keep growing if the code lets it. Inventory decides that a branch holds at most one thousand and twenty-four items and refuses a new one past that. The limit is the application's choice and the application's code.

Cue and animation On “keep growing”, add faint extra rows to the StateCard. On “at most one thousand and twenty-four”, band MAX_ITEMS and draw a cap line under the table labeled 1024. On “refuses a new one”, bounce a row off the cap and return false.

Hold or transition Hold after the bounce. Balloon on the if reads every growing collection needs a limit written by the app.

Leaves with A capped items table.

Scene in_order — Keep things in arrival order

Enters with The shelf with Map lit.

Beat receipt_list — A list with a cursor

View and focus choice. Requirement note reads record requests in the order they arrive, find one by its number.

Show benches/rrt/canister/src/admissions/memory/v1.rs lines 72 to 78, then admissions.rs lines 18 and 19.

#[repr(C)]
#[derive(NyxusData)]
pub struct Data {
    pub(in crate::admissions) owner: Principal,
    pub(in crate::admissions) entries: Vec<Entry>,
    pub(in crate::admissions) next_to_start: usize,
}
const MAX_RECEIPTS: usize = 16_384;
const MAX_PENDING: u64 = 4096;

Narration

A larger app has a different need. Heavy16 gives every accepted request a receipt number and starts them in arrival order. It saves a Vec of entries and one cursor for the next request to start. A receipt number is a position in the list. Two constants cap the total and the number waiting.

Cue and animation On “arrival order”, light the Vec card. On “a Vec of entries”, show a StateCard list with rows 1 Started, 2 Started, 3 Pending, 4 Pending. On “one cursor”, place a marker labeled next_to_start at row 3. On “a position in the list”, tick row 3's number. On “Two constants”, band both constants and draw two cap labels.

Leaves with The Vec card linked to a list with a cursor.

Beat convert_input — Incoming values are converted

View and focus choice, pane on benches/rrt/canister/src/config/mod.rs.

Show Line 81, with config/memory/v1.rs line 8 beside it.

        faults.rejected = cdk_rsx_collections::nyxus::Vec::from_transient(bytes);
    pub(in crate::config) rejected: Vec<u8>,

Narration

An ordinary Rust String or Vec is a transient value. To put one in saved data, convert it to a supported type. Here Heavy16 turns an ordinary byte vector into a saved one with from transient.

Cue and animation On “a transient value”, show a plain Vec<u8> chip with a dotted outline arriving from the request side. On “convert it”, band from_transient. On “a saved one”, redraw the chip with a solid outline and a saved tab and drop it into the field.

Hold or transition Hold on the solid chip. Balloon reads std collections are for the current call. Saved fields use the SDK's collections. This field belongs to Heavy16's test controls, so keep the pane cropped to these two lines.

Leaves with A dotted chip and a solid chip side by side.

Scene own_lifetime — When an entry is a module

Enters with The shelf with Map and Vec lit.

Beat child_map — A whole module per key

View and focus choice. Requirement note reads each branch has its own data, removed together when the branch closes.

Show src/branches/memory/v1.rs line 3.

 pub struct Children {pub(in crate::branches) items:cdk_rsx_store::ChildMap<u64,crate::inventory::memory::v1::Memory>}

Narration

The third case is from the last lesson. Each branch has its own inventory, with its own rules and its own limit, and it should vanish as a whole when the branch closes. That is a child module per key, and the type for it is Child Map.

Cue and animation On “its own inventory”, light the ChildMap card and show the rack from lesson 3 with one Inventory card. On “vanish as a whole”, lift the card out and fade it. On “Child Map”, band ChildMap<u64, …>.

Leaves with Three lit shelf cards, each linked to one requirement note.

Beat not_on_shelf — Page through an ordered map

View and focus shelf, with two short guide lines beneath.

Show Two paraphrased lines from the collections guide. Map and Set order by the key's Ord. Range iteration is for the current call. For paging, pass the last key and bound the work.

Narration

Map and Set keep their keys in order, so you can ask for a range. To page through a map, return a limited number of rows and the last key. The next call uses that key to start the next range.

Cue and animation On “keep their keys in order”, sort the rows of a small Map table. On “the last key”, end the first page on key 44 and pass after: 44 to the next request. On “start the next range”, highlight the first key greater than 44.

Leaves with The shelf and the starting point for the next page.

Scene engine — One choice per module

Enters with The shelf.

Beat hylix_option — Selecting the other engine

View and focus engine_choice.

Show Left, tests/canisters/shop/src/inventory/memory/v1.rs line 15. Right, tests/canisters/hylix-probe/src/counter/memory/v1.rs lines 1 to 3 and line 10, with the fixture's feature-gated field and its dependencies argument hidden.

#[cdk_rsx_store::memory(owner = crate::inventory)]
pub struct Memory;
#[derive(cdk_rsx_engine_hylix::Codec, cdk_rsx_engine_hylix::HylixValue)]
pub struct Data {
    pub(in crate::counter) value: u64,
}
#[cdk_rsx_store::memory(owner = crate::counter, hylix, children = Children)]
pub struct Memory;

Narration

Everything so far used the default engine, Nyxus, which keeps ordinary Rust values. A module can choose Hylix, which keeps its record in stable memory. The choice is one word on the memory attribute and it covers that module's whole Data record. Hylix has its own collections with the same names and different derives.

Cue and animation On “the default engine”, tag the left pane Nyxus · default. On “can choose Hylix”, band the word hylix on the right. On “whole Data record”, bracket the right Data struct. On “different derives”, band Codec and HylixValue.

Leaves with Two declarations tagged Nyxus and Hylix.

Beat what_it_asks — What each choice asks of the author

View and focus engine_choice, comparison rows beneath.

Show A two-row comparison written from the guides.

Nyxus Hylix
Using a value Ordinary Rust references and methods Reads give a decoded copy. Edits go through a guard
Replacing or removing a value Ordinary Rust ownership Move the removed value somewhere or retire it explicitly

Narration

The two engines ask different things of you. With Nyxus you write normal Rust. With Hylix, a read gives you a copy, and when you remove or replace a saved value you must move it or retire it yourself. One app can use both, each in its own module. Choose per module from how the data is used, and measure the real application before deciding on speed.

Cue and animation On “normal Rust”, light the Nyxus column. On “a read gives you a copy”, light the first Hylix cell. On “move it or retire it yourself”, light the second Hylix cell. On “One app can use both”, show two module cards under one App frame tagged Nyxus and Hylix. On “measure the real application”, show a small TestPanel outline labeled populated app.

Leaves with The comparison and an App frame with two tagged modules.

Beat frozen_index — Decide when an index is rebuilt

View and focus choice, with a frozen index beside the existing collection cards.

Show The hash field in benches/minima/src/tables/memory/v1.rs line 18. Use the app's declaration and the collection's documented rebuild rule. Minima tables · Collection choices

    pub(in crate::tables) hash: Option<Box<FrozenHashMap<u64, u64>>>,

Narration

The example on the right uses an experimental Minima collection for a fixed-width lookup index. Readers use one built index at a time. To publish changed entries, build a replacement index. That fits data you refresh as a set. For item stock you edit one entry at a time, keep the Shop's Map.

Cue and animation On “experimental Minima collection”, band FrozenHashMap<u64, u64>. On “build a replacement index”, bring a new StateCard into the index's position with one changed row. On “edit one entry at a time”, return to the Shop's inventory table and highlight one editable row.

Leaves with One example that replaces its index and one that updates entries individually.

Try it

Verify Open the three declarations linked above and write one sentence for each that names the requirement and the collection. Expected answers are lookup by item number with Map, arrival order with a position using Vec and a cursor, and one module per branch with ChildMap.

Change, adapted exercise Add a short history of sold items to the Shop's Inventory. Add recent: Queue<u64> to Data in inventory/memory/v1.rs, initialize it in inventory/memory/mod.rs, and in sell push the item number at the back and pop from the front once the length passes 16. Add a read method recent() that returns a Vec<u64>. Expected result in a native test is that after 17 successful sales of one unit each, recent() returns 16 numbers. This field is not in the checkout. It edits the v1.rs declaration, which is fine for an app that has never been deployed. For a deployed app the same change is a data revision, covered in lesson 7.

Source and review notes

Item shown Status
cdk_rsx_collections::nyxus::{Map, Set, Vec, Queue, String, Box, Rc, Weak}, NyxusData derive, Vec::from_transient Shipped SDK API. Nyxus collections
ChildMap Shipped Store API. Account for child ownership
hylix option, Codec, HylixValue Shipped SDK API. Hylix collections
FrozenHashMap Experimental Minima collection for fixed-width entries. The film shows its declaration and rebuild contract. Minima collection API
MAX_ITEMS, MAX_RECEIPTS, MAX_PENDING, the next_to_start cursor Application code in Shop and Heavy16.
Heavy16 config module and its rejected bytes Benchmark test control. Shown only for the from_transient call.
  • Minima requires explicit setup inside the Store ownership tree. The author selects a Minima collection type. The module's engine selection still follows the Nyxus or Hylix memory declaration. The shared immutable carriers, graph collections and Ashroot tables have their own API guides. Minima · Graphs · Ashroot
  • The status page calls Hylix ownership “a more demanding authoring model than native Rust ownership”. The comparison table paraphrases the collections guide. Do not add performance claims in either direction.
  • Do not describe how either engine stores values. “Ordinary Rust values” and “its record in stable memory” are the guide's own selection terms and are as far as this film goes.
  • The Hylix excerpt hides two fixture details, a feature-gated field on line 4 and a dependencies argument on line 10. Keep the Show note so an editor does not paste the full line.
  • Rc cycles can leak saved values, as in ordinary Rust. The guide says so. Mention it only if the Box, Rc, Weak card is discussed.