Storage: Choose a Collection by Its Contract
Chapters
- Look something up
- Keep things in arrival order
- When an entry is a module
- One choice per module
Transcript
Look something up
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. 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. 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.
Keep things in arrival order
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. 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.
When an entry is a module
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. 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.
One choice per module
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. 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. 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.