staquia
Short lexicographic positions for ordered lists: moving an item writes one row.
- Zero dependencies, no
unsafe, nothing panics. - Positions are
Copyvalues that never allocate. - The same positions as the JavaScript library, checked with more than 20,000 recorded operations.
Staquia is a configurable, zero dependency, lexicographic position algorithm. It solves the reinsertion and sorting problem of long lists: every item stores a short string position, and sorting those strings gives the order of the list.
When an item is moved, only its own position changes, the surrounding items never need to be updated. This makes it ideal for lists and tables stored in a database, where reordering one row should mean writing one row.
To have a full detailed explanation you can go to the documentation site, which opens with every example in Rust.
This crate is the Rust version of the staquia JavaScript library (0.6.0). For the same system and operations both create the same positions, so a Rust service can read and write the positions stored by a JavaScript app. The tests of the repository replay more than 20,000 operations recorded with the JavaScript library and assert the same strings.
- Install
- Quick start
- How positions work
- Creating a system (and presets)
- Positions
- Errors
- Lexical list
- Differences with JavaScript
- Running the tests
- License
Install
The crate has no dependencies and no unsafe code, and needs Rust 1.85 or later (the first version with the 2024 edition). The API documentation is on docs.rs, and the guides (how positions work, using them in a database, error handling) are on the documentation site, with Rust examples.
Quick start
use ;
More in the examples/ folder: cargo run --example basic and cargo run --example list.
How positions work
A system has a zero character and a range of characters from first to last: they are the digits of a number system of base (last - first) + 2. A position is a number written with those digits, split in two sections:
N, of a fixed lengthln: stacking an item before or after the list adds or subtracts1here, so positions never get longer.Z, of up tolzdigits: moving an item between two adjacent positions takes the middle value here, one digit longer.
Positions compare exactly as their strings, so a database sorts them with a plain ORDER BY position. Moving items again and again into the same gap makes positions grow: the system warns at the threshold length and fails at the overflow length, and the list can then be rebalanced (every position spaced again).
Creating a system
use ;
// The alphabet: "!" is 0, "a" is 1 and "z" is 26, a base 27 system
let alphabet = create?;
// The default system, the same one as `Staquia.default()` in JavaScript:
// "!", from "°" (U+00B0) to "ұ" (U+04B1), base 1027, ln = 5, lz = 15, threshold 0.15
let system = default;
// Only some options changed
let longer = create_with_options?;
# Ok::
create validates the configuration (cheap checks) and returns a CreateError when:
- the characters are not
zero < first <= last, - a character is above
U+FFFF, or the range includes the surrogates (U+D800toU+DFFF), so Rust, JavaScript, UTF-8 and UTF-16 compare them in the same order, lnorlzis0, orln + lzis aboveMAX_LENGTH(32),- the threshold factor is not from
0to1.
A Staquia is a small Copy value.
Presets
Ready to use systems, no parameters to choose. Change their lengths with the same Options constructors:
Staquia::create_with_options(Options { ln: 6, ..Options::url_safe() }).
| Preset | Characters | Base | Start | Pick it when |
|---|---|---|---|---|
Staquia::ascii() |
! + printable ASCII from # to ~ without ', \ and ` |
90 | PPPPP! |
you want plain ASCII: the most compact per byte, nothing to escape in JSON, SQL or logs |
Staquia::url_safe() |
-, 0-9, A-Z, _, a-z |
64 | VVVVV- |
positions go in URLs, file names or HTML ids |
Staquia::base36() |
0-9, a-z |
36 | iiiii0 |
the column is case insensitive (MySQL's default) or keys must be alphanumeric |
Staquia::alphabet() |
! + a-z |
27 | mmmmm! |
you want to read them in logs and docs (every example here uses it) |
Staquia::default() |
! + ° to ұ |
1027 | ʰʰʰʰʰ! |
the shortest in characters (PostgreSQL varchar(n) counts characters) |
The characters of url_safe are the ones of URL safe base64, but sorted by their code instead of the base64 order: positions are sort keys, not encoded data, so they keep the order a database compares them in.
Any other set of characters works too, not only a range: Staquia::from_characters(&"...", ln, lz, threshold) takes the zero followed by every digit, sorted by their code. It is a reference to a static string (written &"..."), so positions keep only a pointer to it.
use Staquia;
// The digits without the vowels: "0" is the zero, base 22
let system = from_characters?;
assert_eq!;
# Ok::
Why 32. The JavaScript library has no fixed limit, but a Rust Position keeps its digits in a fixed array (32 digits, plus one so an overflow error can show the position that caused it), so it is a Copy value (88 bytes) that never allocates. 32 is more than lists need: the default system uses 20 (ln = 5, lz = 15), N stacks about 5.7 × 10¹⁴ items in each direction, and a longer Z only allows more moves into the same gap (121 with 20 digits, 242 with 32) before the list has to be rebalanced, which happens with any limit. Longer positions also cost space in the database and its index (up to 3 bytes per digit in UTF-8).
Positions
use Staquia;
let system = create?;
let start = system.start?; // "mmmmm!": the middle digit, as much room before as after
let next = system.next?; // "mmmmn!"
let previous = system.previous?; // "mmmml!"
let core = system.core?; // "mmmmmn": between both, the order of the arguments doesn't matter
// From a stored string; shorter strings are completed with zeroes to the right
let stored = system.forge?; // "xy!!!!"
// Positions implement Ord, Eq and Hash with the same order as their strings
assert!;
assert_eq!;
# Ok::
A Position is a Copy value that lives on the stack: its digits in a fixed array (MAX_LENGTH plus one, for the position of an overflow error) and the signature of the system that created it (its characters and ln), with no reference to the system. Display writes its string, the value to store. n(), z() and digits() give its digits, and Staquia::from_digits creates a position back from them.
Errors
Nothing panics: every operation that can fail returns a Result with an error enum.
| Error | When |
|---|---|
PositionError::InvalidCharacter |
forge found a character that is not a digit of the system |
PositionError::Overflow |
the position would be longer than ln + lz: the error has that position, to log it |
PositionError::EdgeReached |
next of the last value of N, or previous of the first one |
PositionError::ThresholdReached |
the position reached the threshold: it is still valid (the error has it) but the list should be rebalanced |
PositionError::SystemMismatch |
the position was created by a system with another configuration |
CreateError |
create received an invalid configuration |
LexicalError<K> |
an operation of a list failed, see below |
staquia::Error<K> combines all of them with From implementations, so ? works with every operation in the same function without boxing the errors. The helpers is_overflow(), is_dangerous(), is_mismatch() and is_invalid() mirror the JavaScript error classes.
Lexical list
LexicalList keeps the order of your values and their positions in sync, as a doubly linked list of ids in a HashMap (no pointers, no Rc). Implement Item for your type: an id, the stored position string, and set_position, which receives every new position.
| Method | |
|---|---|
push(value) / unshift(value) |
adds at the end / start |
move_to(&id, previous, next) |
moves between two neighbors (None for an end), only the moved item changes |
delete(&id) |
removes the item and gives its value back |
set(values) |
loads rows already sorted by position, verified and not changed |
set_untrusted(values) |
loads rows and repairs them: sorted, duplicates and invalid positions given new ones |
sort_by(compare) |
sorts and spaces every position again from the start |
rebalance() |
spaces every position again keeping the order, to retry after a gap is exhausted |
head() / tail() |
the position a new item would get at the start / end |
first(), last(), find(&id), find_mut(&id), at(index), iter(), len() |
reading |
select(&id), selected(), deselect() |
the selected item, cleared when it is deleted |
When an operation fails, neither the list nor your values are changed. push, unshift, set and set_untrusted take ownership of the values, so on failure they return a Rejected with the error and the values given back (rejected.into_value()), for example to retry after rebalance():
# use ;
#
#
# let mut list = new;
# list.push?;
let task = Task ;
match list.push
# Ok::
The operations that change many positions (set_untrusted, sort_by, rebalance) return the affected items, the only rows to save.
Differences with JavaScript
The logic and the positions are the same; the API follows Rust conventions:
Result<T, E>with error enums instead of theOk/Errclasses, and?instead of chaining results intonext/core.Staquia::create_with_options(Options)andStaquia::default(). The JavaScript option to replace the position and number classes has no equivalent: add methods toPositionwith a trait of your own.Staquia::from_digits(&[u16])instead offrom(IDigits), the digits most significant first.move_toinstead ofmove(a keyword),sort_bywith a comparison of your values,iter()instead oftoArray(),at(usize).deletegives the value back.setandset_untrustedare two methods instead of theuntrustedoption.sort_byandrebalancework like JavaScript'ssortandrebalance(0.5.1 and later): all or nothing, the room for every position is verified first, so a failure leaves the list unchanged.- Ids can't be
null, so there is no invalid id error, and the list can't contain a cycle, so there is no map overflow error. InvalidCharacter.indexcounts characters; JavaScript counts UTF-16 units. They are the same for every valid string, as systems only use characters up toU+FFFF.Position::len()is the length of the stored string ("mmmmm!"is 6); JavaScript'sposition.lengthis the length measured when the position was created, which doesn't count the zeroes that complete it (5). The checks (has_overflow,is_threshold_reachedand the errors) use that measured length in both libraries.- An
Overflowkeeps the position that caused it, like JavaScript. When a string or digits given toforgeorfrom_digitsare longer than one digit past the limit, the position is cut there and the error'slengthhas the full length.
Running the tests
The 219 tests of the JavaScript library are ported with the same names: the ones of the internal numbers and
algorithms (number.test.ts, algorithms.test.ts, composer.test.ts, forger.test.ts) are unit tests inside
src/, staquia.spec.ts is tests/staquia.rs (its presets group is tests/rust_presets.rs) and lexical-list.spec.ts is tests/list.rs. The tests of the
Rust-only API are in tests/rust_*.rs.
tests/cross_language.rs replays the operations recorded in tests/fixtures/*.tsv with the JavaScript library. These fixtures (1.5 MB) are only in the repository, not in the published crate, whose other tests still run with cargo test. To record them again, from the javascript/ folder of the staquia repository:
License
MIT (see LICENCE), the same as the JavaScript library.