JFLib

base#

UTF-8, command line, settings files, numbers and text -- crate root lib/base/lib.rs

base -- portable basics above the runtime and the platform     [src/core/str.s, args.s, ini.s]

  utf8_decode(s, i) -> (codepoint, next)    an invalid sequence decodes as U+FFFD, next = i + 1
  Args: value(name) / flag(name) / int(name, default) over the command line
  num:  f64_parse / f64_format (bit-identical to ASMLIB), parse_i64
  ini:  Ini -- settings files (load / parse / save / get* / set* / remove)
  settings: Key / Schema / Settings -- typed settings over an Ini (versions, migrations)
  rng:  Pcg32 / SplitMix64 -- deterministic pseudo-random numbers (simulations, tests)
  metrics: Counter / Gauge / Hist (log-linear) / Window (n slots, quantiles without the
        values) -- measurements of running systems
  cmdtree: Tree / Parsed / Help -- IOS-like command trees (abbreviations, ?, Tab, "no", modes)
  hashring: Ring / hash64 -- consistent hashing with virtual nodes (shards, sticky balancing)
  lru:  Lru -- a map that forgets the least recently used entries (count and weight limits)
  pattern: glob / has_glob -- shell wildcards; Regex -- POSIX basic and extended regular
        expressions without back-references (a Pike VM: no exponential cases)
  xml, encoding: re-exports of formats::{xml, encoding} (here until 0.3.0; new code names
        formats)

Strings and formatting are Rust's own (str, String, format!); the thread pool, cpu
features and files are in plat (they need unsafe).

base crate root#

Re-exports: formats::encoding

Re-exports: formats::xml

  • fn utf8_decode(s: &[u8], i: usize) -> (u32, usize) UTF-8 decoding: (codepoint, index after it); an invalid / overlong / surrogate / too large sequence decodes as U+FFFD and advances one byte [src/core/str.s utf8_decode]

  • struct Args(pub Vec<String>) the command line (argument 0 is the program)

impl Args

  • fn value(&self, name: &str) -> Option<&str> the argument after name (--shot FILE); argument 0 (the program) is skipped
  • fn flag(&self, name: &str) -> bool
  • fn int(&self, name: &str, def: i32) -> i32 a decimal value, def when missing or invalid

base/ini.rs#

Source: lib/base/ini.rs

ini -- settings files: UTF-8 "[section]" / "key=value" text              [src/core/ini.s]

  Ini::new() / Ini::load(path) / Ini::parse(bytes)    a missing or unreadable file is empty
  ini.save(path) -> bool       plat::write_file, creates missing directories
  ini.to_bytes()               the text save writes
  ini.get(sec, key) -> Option<&str>   (get_bytes for values that are not UTF-8)
  ini.get_int(sec, key, def)   decimal (+/-), 0x hex, true/false/yes/no/on/off; else def
  ini.get_f64(sec, key, def)   '.' decimal point only; else def
  ini.set(sec, key, value) / set_int / set_f64 -> bool   add or replace (false: a bad name,
                                or a line longer than LINE_MAX: it would not read back)
  ini.remove(sec, key) -> bool
  ini.section(sec) -> Vec<(&str, &str)>   the keys of a section and their values, in order
  ini.sections() -> Vec<&str>   the section names in file order (each once; not "")
  ini.items() -> Vec<Item>      headers, keys and malformed lines with their line numbers
                                (files that are checked: a theme names a mistake's line)

Format: one entry per line; sec "" = the keys before the first [section].  Section and
key names compare ASCII case-insensitively; values are stored as written (blanks around
names and values trimmed; no quoting, no inline comments, so values may contain ';' and
'#').  Lines starting with ';' or '#', blank lines and malformed lines (no '=', "[" without
"]", NUL bytes, longer than LINE_MAX) are kept verbatim and written back unchanged, as are
all lines not touched by set (the original spacing survives).  New keys go after the
last key of their section, new sections to the end.  A UTF-8 BOM is skipped.  Files are
read up to FILE_MAX bytes; after LINES_MAX lines the rest is kept as one verbatim block.
Line ends: LF, CRLF (any number of CRs before the LF are dropped) when reading; written as
CRLF on Windows, LF on Linux.  Key names must not contain '=', NUL, CR or LF nor start with
';' '#' '['; section names must not contain ']', NUL, CR or LF; neither may start or end with
a blank (set -> false).  CR / LF / NUL inside a value are written as blanks and blanks around
a value are dropped (reading drops them too): get after set gives what a reload gives.
  • struct Ini a settings object (one thread at a time)

  • enum Item<'a> a line of the file as Ini::items lists it (line numbers from 1)

    • Section { line: usize, name: &'a str } -- a "[name]" header
    • Key { line: usize, sec: &'a str, key: &'a str, value: &'a str } -- "key = value" of section sec ("" before the first header)
    • Bad { line: usize, text: &'a [u8] } -- neither blank, a comment, a header nor a key (or not UTF-8)

impl Ini

  • fn new() -> Ini
  • fn load(path: &str) -> Ini the parsed file; empty when it is missing or unreadable [ini_load]
  • fn load_checked(path: &str) -> Option<Ini> like load, but None when the file could not be read completely (unreadable, its size unknown, longer than FILE_MAX, or whether it exists is unknown: refused, an I/O error, a folder there); a missing or empty file gives an empty Ini
  • fn parse(data: &[u8]) -> Ini parse settings text [ini_parse]
  • fn to_bytes(&self) -> Vec<u8> the text save writes
  • fn save(&self, path: &str) -> bool Write through plat::write_file; missing directories are created. [ini_save]
  • fn section(&self, sec: &str) -> Vec<(&str, &str)> every key of a section with its value, in file order (entries that are not UTF-8 are left out; sec "" = the keys before the first header)
  • fn sections(&self) -> Vec<&str> the names of the sections in file order, each once (names that are not UTF-8 are left out; the keys before the first header are not a section here)
  • fn items(&self) -> Vec<Item<'_>> every header, key and malformed line in file order with its line number; blank lines and comments are left out
  • fn get(&self, sec: &str, key: &str) -> Option<&str> the value, or None when missing or not UTF-8 [ini_get]
  • fn get_bytes(&self, sec: &str, key: &str) -> Option<&[u8]>
  • fn get_int(&self, sec: &str, key: &str, def: i64) -> i64 [ini_get_int]
  • fn get_f64(&self, sec: &str, key: &str, def: f64) -> f64 the whole value must be the number [ini_get_f64]
  • fn set(&mut self, sec: &str, key: &str, value: &str) -> bool add or replace (false: a bad name, or a line longer than LINE_MAX -- it would be read back as a malformed line, not as this key or section) [ini_set]
  • fn set_int(&mut self, sec: &str, key: &str, value: i64) -> bool [ini_set_int]
  • fn set_f64(&mut self, sec: &str, key: &str, value: f64) -> bool the shortest text that reads back to the same double [ini_set_f64]
  • fn remove(&mut self, sec: &str, key: &str) -> bool false: not there [ini_remove]

base/num.rs#

Source: lib/base/num.rs

num -- numbers <-> text                                                  [src/core/ini.s]

  f64_parse(s) -> (value, used)   leading blanks, sign, digits, '.', exponent, inf /
                                  infinity / nan; used = 0 when there is no number
  f64_format(v) -> String         the shortest text that reads back to the same double,
                                  '.' separator, "1e-07" style below 1e-5 and from 1e17,
                                  "inf" / "-inf" / "nan"
  parse_i64(s) -> Option<i64>     decimal (+/-), 0x hex, true/false/yes/no/on/off (the whole
                                  string; overflow -> None)

The scaling steps run on the x87 unit like in ASMLIB (rt::x87), so both directions are
bit-identical to the assembly -- the text of a saved setting included. Where the unit holds
only doubles (x64 under the emulation of Windows on ARM, docs/ARM64.md), rt::portable::math
does the same steps without it.
  • fn f64_parse(s: &[u8]) -> (f64, usize) the number at the start of s: (value, bytes used; 0 = none) [f64_parse]

  • fn f64_format(v: f64) -> String the shortest decimal text that reads back to v [f64_format]

  • fn parse_i64(s: &[u8]) -> Option<i64> an integer setting: the whole string must match [parse_i64]

base/settings.rs#

Source: lib/base/settings.rs

settings -- typed settings: a schema of keys (type, default, limits, label) over a settings
file (Ini) with a format version and migrations

  const DARK: Key<bool> = Key::bool("view.dark", false).label("Dunkles Design");
  const ZOOM: Key<i64> = Key::int("view.zoom", 100, 10, 800).label("Zoom (%)").step(10);
  static SCHEMA: Schema = Schema::new(2, &[DARK.d, ZOOM.d]).sections(&[("view", "Ansicht")])
      .migrate(migrate);
  let mut s = Settings::open("config://settings.ini", &SCHEMA);
  let zoom: i64 = s.get(&ZOOM);   s.set(&ZOOM, 120);   s.save();

Key types: Key<bool> (Key::bool), Key<i64> (Key::int: min..max, step), Key<f64> (Key::num:
min..max, decimals), Key<String> (Key::text: at most max bytes of UTF-8), Key<usize>
(Key::choice: an index into (stored word, label) items; the file keeps the word),
Key<u32> (Key::color: 0xRRGGBB; the file "#RRGGBB").  Builders: label(s), help(s),
hidden() (not on the settings page), restart() (takes effect after a restart: the page
says so), step(n) (int: the number box's step).

  Settings::open(path, &schema)   load, migrate, read (a missing file: the defaults)
  Settings::new(&schema)          only in memory (save does nothing)
  Settings::from_ini(ini, &schema)  in memory, from an Ini (tests)
  s.get(&key) -> T   s.text(&key) -> &str   s.set(&key, v) -> changed   s.reset(&key)
  s.reset_all()   s.is_default(&key)   s.save() -> ok   s.dirty()   s.revision()
  s.ini() / s.ini_mut()   the file for free-form data the schema does not describe (a
                          list of recent files); ini_mut marks the settings dirty
  s.file_version()        the version the file had (0: none or older than versions)
  s.schema(), s.at(i), s.set_at(i, val), s.default_at(i)   by schema index (the page)
  rename(&mut ini, "old.key", "new.key")   for migrations

Names are "section.key" (no '.': the top of the file).  The file keeps only values that
differ from the default (setting the default or a reset removes every line of the key, also
one that already read as the default), so a new default reaches users who never changed it;
comments, unknown keys and other sections survive (Ini).  set / reset report whether the
value or the file changed.  A text is kept as the file can hold it: CR, LF and NUL become
blanks, blanks around it go, then it is cut to its maximum (what a restart reads back); a
value whose line would be too long for the file is not set (false, a WARN).
The format version is "version=N" at the top: a file of an older version (no line: 0)
runs migrate(from, &mut ini) once before its values are read (rename keys, convert units)
and is saved with the new version by the next save; a missing file needs no migration; a
file of a newer version is read as far as the schema goes and keeps its number.  A value
the schema cannot use (not a number, an unknown choice, a bad colour) reads as the default
and a WARN goes to the log; numbers out of range are clamped, texts cut to their maximum.
Keys that are not in the schema still work through get / set (read from the file each
time) but are not on the page.
/// Desc::flags: not on the settings page
KF_HIDDEN: u32 = 1
/// Desc::flags: takes effect after a restart (the page says so)
KF_RESTART: u32 = 2
  • enum Kind what a key holds, with its default and limits

    • Bool(bool)
    • Int { def: i64, min: i64, max: i64, step: i64 }
    • Num { def: f64, min: f64, max: f64, dec: u32 }
    • Text { def: &'static str, max: usize }
    • Choice { def: usize, items: &'static [(&'static str, &'static str)] }
    • Color(u32)
  • struct Desc a key of a schema (Key::d)

    • name: &'static str
    • label: &'static str
    • help: &'static str
    • flags: u32
    • kind: Kind

impl Desc

  • fn split(&self) -> (&'static str, &'static str) (section, key) of the name

  • fn default_val(&self) -> Val the default value

  • fn fit(&self, v: Val) -> Val v made valid for this key (clamped, cut, the default when it is of another type)

  • fn format(&self, v: &Val) -> String the value written into the file for v

  • fn parse(&self, s: &str) -> Option<Val> the text of the file read as this key: Some(valid value) (clamped / cut) or None

  • enum Val a value of a key

    • Bool(bool)
    • Int(i64)
    • Num(f64)
    • Text(String)
    • Choice(usize)
    • Color(u32)
  • trait Value: Sized the Rust types a key can have: bool, i64, f64, String, usize (choice), u32 (colour)

    • fn from_val(v: &Val) -> Option<Self>
    • fn into_val(self) -> Val
  • struct Key<T> a typed key: its description (d) and the Rust type of its value

    • d: Desc

impl Key<bool>

  • const fn bool(name: &'static str, def: bool) -> Key<bool>

impl Key<i64>

  • const fn int(name: &'static str, def: i64, min: i64, max: i64) -> Key<i64> a whole number in min..=max (step 1)
  • const fn step(self, step: i64) -> Key<i64> the step of the number box's arrows and arrow keys

impl Key<f64>

  • const fn num(name: &'static str, def: f64, min: f64, max: f64, dec: u32) -> Key<f64> a number in min..=max, shown with dec decimals

impl Key<String>

  • const fn text(name: &'static str, def: &'static str, max: usize) -> Key<String> a text of at most max bytes (UTF-8)

impl Key<usize>

  • const fn choice(name: &'static str, def: usize, items: &'static [(&'static str, &'static str)]) -> Key<usize> one of items (stored word, label); the value is its index

impl Key<u32>

  • const fn color(name: &'static str, def: u32) -> Key<u32> a colour 0xRRGGBB

impl<T> Key<T>

  • const fn label(self, label: &'static str) -> Key<T> the text of the settings page (default: the name)

  • const fn help(self, help: &'static str) -> Key<T> a line of explanation below the label

  • const fn hidden(self) -> Key<T> not on the settings page (state the app keeps)

  • const fn restart(self) -> Key<T> takes effect after a restart

  • struct Schema the keys of a settings file, its format version, the page's section titles and the migration of older files

    • version: u32
    • keys: &'static [Desc]
    • sections: &'static [(&'static str, &'static str)] -- (section, title) for the settings page, in this order (sections without a title come after them, titled by their name)
    • migrate: Option<fn(u32, &mut Ini)> -- migrate(from, &mut ini): bring a file of version from up to version

impl Schema

  • const fn new(version: u32, keys: &'static [Desc]) -> Schema

  • const fn sections(self, sections: &'static [(&'static str, &'static str)]) -> Schema

  • const fn migrate(self, f: fn(u32, &mut Ini)) -> Schema

  • fn index(&self, name: &str) -> Option<usize> the index of a key name

  • fn split(name: &str) -> (&str, &str) "section.key" -> (section, key); no '.': ("", name)

  • fn rename(ini: &mut Ini, old: &str, new: &str) -> bool for migrations: move a value from one name to another ("section.key"); false: not there

  • struct Settings typed settings over a file (see the module header)

impl Settings

  • fn open(path: &str, schema: &'static Schema) -> Settings the settings of a file (a missing or unreadable file: the defaults)
  • fn new(schema: &'static Schema) -> Settings settings only in memory (save does nothing)
  • fn from_ini(ini: Ini, schema: &'static Schema) -> Settings settings in memory, read from an Ini (migrated like a file)
  • fn schema(&self) -> &'static Schema
  • fn path(&self) -> &str the file's path ("" in memory)
  • fn file_version(&self) -> u32 the format version the file had before a migration (0: none / no version line)
  • fn get<T: Value>(&self, k: &Key<T>) -> T a value (the key's default when the key is not in the schema and not in the file)
  • fn text(&self, k: &Key<String>) -> &str a text without copying it
  • fn set<T: Value>(&mut self, k: &Key<T>, v: T) -> bool set a value (made valid for the key) -> the value or the file changed (the default removes every line of the key, also one that held it already)
  • fn reset<T>(&mut self, k: &Key<T>) -> bool back to the default: every line of the key leaves the file (also an explicit default, a value that read as the default, a second line of the same key)
  • fn reset_all(&mut self) -> bool every key of the schema back to its default
  • fn is_default<T>(&self, k: &Key<T>) -> bool the key has its default value
  • fn at(&self, i: usize) -> &Val the value of schema key i
  • fn default_at(&self, i: usize) -> Val the default of schema key i
  • fn set_at(&mut self, i: usize, v: Val) -> bool set schema key i (made valid) -> the value or the file changed (as set)
  • fn dirty(&self) -> bool unsaved changes
  • fn revision(&self) -> u32 counts every change (redraw or apply what depends on the settings when it moved)
  • fn ini(&self) -> &Ini the file's data (free-form sections the schema does not describe)
  • fn ini_mut(&mut self) -> &mut Ini change free-form data (marks the settings dirty; keys of the schema: use set)
  • fn save(&mut self) -> bool write the file when something changed (atomic; in memory: nothing) -> ok

base/rng.rs#

Source: lib/base/rng.rs

rng -- deterministic pseudo-random numbers for simulations, tests and games (NOT for keys:
those come from plat::fill_random)

  SplitMix64::new(seed)      next_u64; derives seeds (Vigna's splitmix64)
  Pcg32::new(seed, stream)   PCG-XSH-RR 64/32 (O'Neill), the reference pcg32_srandom_r: the
                             same seed and stream give the same numbers on every target;
                             different streams are independent sequences
  Pcg32::derive(seed, id)    a generator for one of many objects (seed and id mixed through
                             SplitMix64), so adding an object does not shift the others
  next_u32 / next_u64 / below(n) (unbiased) / range(lo, hi) / f64 (0..1, 53 bits) /
  chance(num, den) / chance_ppm(ppm) / fill(bytes) / shuffle(slice) / advance(delta)
  • struct SplitMix64 SplitMix64: a 64-bit generator mostly used to expand one seed into many

impl SplitMix64

  • const fn new(seed: u64) -> SplitMix64

  • fn next_u64(&mut self) -> u64

  • struct Pcg32 PCG32 (XSH-RR, 64-bit state, 32-bit output)

impl Pcg32

  • fn new(seed: u64, stream: u64) -> Pcg32 the generator of seed on stream (pcg32_srandom_r(seed, stream))
  • fn derive(seed: u64, id: u64) -> Pcg32 a generator for object id under a common seed
  • fn next_u32(&mut self) -> u32
  • fn next_u64(&mut self) -> u64
  • fn below(&mut self, n: u32) -> u32 uniform in 0..n without modulo bias (n = 0 gives 0)
  • fn range(&mut self, lo: i64, hi: i64) -> i64 uniform in lo..=hi
  • fn f64(&mut self) -> f64 uniform in [0, 1) with 53 random bits
  • fn chance(&mut self, num: u32, den: u32) -> bool true with probability num / den
  • fn chance_ppm(&mut self, ppm: u32) -> bool true with probability ppm / 1 000 000 (loss and error rates)
  • fn fill(&mut self, out: &mut [u8])
  • fn shuffle<T>(&mut self, v: &mut [T]) Fisher-Yates
  • fn advance(&mut self, mut delta: u64) skips delta outputs in O(log delta) (Brown's jump ahead for LCGs)

base/metrics.rs#

Source: lib/base/metrics.rs

metrics -- measurements of running systems without keeping single values: counters, gauges,
log-linear histograms and a sliding window of them (simulators, servers, benchmarks)

  Counter        inc / add / get (saturating u64)
  Gauge          set / add / get / max (i64; max is the highest value seen)
  Hist           log-linear buckets: values below 2^b exactly, above in 2^b linear steps
                 per power of two (b = 5: at most 1/32 = 3.1 % bucket width, the midpoint
                 is off by half of that); record / record_n / count / sum / min / max /
                 mean / quantile(per_mille) / p50 / p95 / p99 / merge / clear / buckets
  Window         n slots of `span` time units each (Window::new(300, 1_000_000_000): five
                 minutes in 1 s slots of nanoseconds); record(t, v) / quantile(t, pm) /
                 p50 / p95 / p99 / count / sum / mean / min / max over the slots still in
                 the window at t / per_slot(t, pm) for charts / hist(t)
                 hist_between(from, to): the slots that start in [from, to) as one
                 histogram (a time series: one point per interval, quantiles of any span);
                 bytes(): the heap memory it holds -- its slots come with the first value,
                 so a window that never got one costs nothing (a simulator keeps one per
                 device and copies them often)

Quantiles use the nearest rank (rank = ceil(pm * n / 1000)) and give the midpoint of that
rank's bucket, clamped to the smallest and largest value seen (the first and the last rank
are those values), so a run of equal values reports that value exactly.  A window slot keeps a sparse histogram (bucket, count) and its
own count, sum, min and max; nothing stores the values themselves.  All integer arithmetic:
the same values give the same results on every target.
  • struct Counter(u64) a monotonic count

impl Counter

  • const fn new() -> Counter

  • fn inc(&mut self)

  • fn add(&mut self, n: u64)

  • fn get(&self) -> u64

  • struct Gauge a value that goes up and down, with the highest value it reached

impl Gauge

  • const fn new() -> Gauge
  • fn set(&mut self, v: i64)
  • fn add(&mut self, d: i64)
  • fn get(&self) -> i64
  • fn max(&self) -> i64
/// the default resolution: 32 linear steps per power of two
HIST_BITS: u8 = 5
  • struct Hist a log-linear histogram

impl Hist

  • fn new() -> Hist

  • fn with_bits(bits: u8) -> Hist bits linear steps per power of two as a power of two (1..=8)

  • fn bits(&self) -> u8

  • fn bucket(&self, v: u64) -> usize the bucket a value falls into

  • fn range(&self, i: usize) -> (u64, u64) the smallest value and the width of a bucket

  • fn record(&mut self, v: u64)

  • fn record_n(&mut self, v: u64, n: u64)

  • fn count(&self) -> u64

  • fn sum(&self) -> u128

  • fn min(&self) -> Option<u64>

  • fn max(&self) -> Option<u64>

  • fn mean(&self) -> Option<u64> the mean, rounded down

  • fn quantile(&self, per_mille: u32) -> Option<u64> the value at per_mille (500: median, 990: p99, 1000: the largest)

  • fn p50(&self) -> Option<u64>

  • fn p95(&self) -> Option<u64>

  • fn p99(&self) -> Option<u64>

  • fn merge(&mut self, o: &Hist) -> bool adds the values of another histogram of the same resolution (false otherwise)

  • fn clear(&mut self)

  • fn buckets(&self) -> Vec<(u64, u64, u64)> the buckets that hold values: (smallest value, width, count)

  • struct Window a histogram over the last slots spans of time

impl Window

  • fn new(slots: usize, span: u64) -> Window slots slots of span time units each (at least one of each)
  • fn with_bits(slots: usize, span: u64, bits: u8) -> Window
  • fn slots(&self) -> usize
  • fn bytes(&self) -> usize the heap memory it holds: its slots and their histograms (none before the first value)
  • fn span(&self) -> u64
  • fn record(&mut self, t: u64, v: u64) -> bool counts v at time t; false when t lies before the window that ends at the newest time recorded so far
  • fn record_n(&mut self, t: u64, v: u64, n: u32) -> bool
  • fn hist(&self, t: u64) -> Hist everything in the window at time t as one histogram
  • fn hist_between(&self, from: u64, to: u64) -> Hist the slots that start in [from, to) as one histogram: what was recorded between two times, to the resolution of the slots; slots the ring no longer holds are left out
  • fn count(&self, t: u64) -> u64
  • fn sum(&self, t: u64) -> u128
  • fn mean(&self, t: u64) -> Option<u64>
  • fn min(&self, t: u64) -> Option<u64>
  • fn max(&self, t: u64) -> Option<u64>
  • fn quantile(&self, t: u64, per_mille: u32) -> Option<u64>
  • fn p50(&self, t: u64) -> Option<u64>
  • fn p95(&self, t: u64) -> Option<u64>
  • fn p99(&self, t: u64) -> Option<u64>
  • fn per_slot(&self, t: u64, per_mille: u32) -> Vec<(u64, u64, Option<u64>)> one value per slot of the window at time t, oldest first: (start time of the slot, count, quantile or None when the slot is empty)

base/cmdtree.rs#

Source: lib/base/cmdtree.rs

cmdtree -- command trees for IOS-like command lines: unique prefix abbreviations ("sh ip int
br"), "?" help with descriptions, Tab completion, modes with prompts, the "no" form, typed
parameters and the position of an error for the IOS-like messages ("% Invalid input detected at
'^' marker.", "% Incomplete command.", "% Ambiguous command:")

  Tree::new()                          an empty tree of commands of type C (an app's enum)
  mode(prompt, title, parent, no_help) a mode: its prompt after the host name ("(config)#"),
                                       the title of its "?" list, the mode its commands fall
                                       back to, the help of its "no" (None: no "no")
  add(mode, path, help, cmd, flags)    a command path; shared prefixes merge, the last word
                                       gets the help text, `cmd` makes the path complete
  also(mode, path, target)             the words after `target` may follow `path` too
                                       (options in any order)
  parse(mode, line, &dyn Names)        -> Result<Parsed<C>, Error>
  help(mode, line, &dyn Names)         -> Help: the answer to "?" typed after `line`
  complete(mode, line, &dyn Names)     -> Completion (Tab)
  Error::render / Help::render         the text an IOS-like console shows
  find_mode(prompt)                    a mode by its prompt (modes that parts of an app add
                                       need no fixed number)

Paths are words separated by spaces.  A keyword stands for itself ("shutdown"; "access=mode"
stores it under the key "mode").  A parameter is TYPE or TYPE=key (a later value of a key
hides an earlier one, so "mode access=mode" reads as "access"):

  <lo-hi>      a decimal number in the range          Val::Num
  A.B.C.D      an IPv4 address                         Val::Ipv4
  MASK         a contiguous dotted netmask              Val::Mask (its length)
  A.B.C.D/nn   an address with a prefix length          Val::Prefix
  X:X:X:X::X   an IPv6 address (every RFC 4291 form)    Val::Ipv6
  X:X:X:X::X/<0-128>   an IPv6 address with a prefix length   Val::Prefix6
  H.H.H        a MAC address (H.H.H or with colons)     Val::Mac
  WORD         one word                                 Val::Word
  LINE         the rest of the line, spaces included    Val::Line
  NAME, NAME1 .. NAME9   one of the caller's names (lists 0 .. 9, interfaces): a type and a
               number ("gi0/0/0", "Gi 0/0/0", "lo0"), the type abbreviated like a keyword,
               also as two words                       Val::Name (the full name)

Matching is IOS-like: keywords ignore case and may be shortened to any prefix that no other
word of that place shares; a word that is a whole keyword wins; numbers, addresses and names
must be valid; WORD and LINE take what no keyword takes.  The error position is the first
character no candidate accepts (the "^" marker).  "no" is a keyword of every mode that has
it; it leads to the commands added with F_NO, and a no-form may end early where add_no says.
Help lists keywords and parameters in ASCII order (parameters and capitalised interface
types first) with "<cr>" when the command may end there.
  • type NodeId = u32 the index of a node of a tree

  • type ModeId = u16 the index of a mode

/// a command may be negated ("no shutdown"); set on its first word
F_NO: u8 = 1
/// not listed by help and completion (aliases, commands of the configuration file only)
F_HIDDEN: u8 = 2
  • enum Param a typed parameter
    • Num(i64, i64)
    • Ipv4
    • Mask
    • Prefix
    • Mac
    • Word
    • Line
    • Name(u8)
    • Ipv6
    • Prefix6

impl Param

  • fn label(&self) -> String what help shows for it ("<1-4094>", "A.B.C.D", "WORD")

  • enum Val a value of a parsed command

    • Key(String) -- a keyword, written out in full
    • Num(i64)
    • Ipv4([u8; 4])
    • Mask(u8)
    • Prefix([u8; 4], u8)
    • Mac([u8; 6])
    • Word(String)
    • Line(String)
    • Name(String)
    • Ipv6([u8; 16])
    • Prefix6([u8; 16], u8)
  • trait Names the names a NAME parameter takes (interfaces of a device); "*" in a name stands for a number ("Loopback*", "GigabitEthernet0/0/0.*")

    • fn names(&self, list: u8) -> Vec<String>
    • fn type_help(&self, _list: u8, ty: &str) -> String the help text of a type of names ("GigabitEthernet" -> "GigabitEthernet IEEE 802.3z")
  • struct NoNames no names at all

  • struct Mode a mode of the command line

    • prompt: String -- what follows the host name in the prompt ("#", "(config-if)#")
    • title: String -- the first line of the "?" list ("Commands at the user level:")
    • parent: Option<ModeId> -- where a command that is not one of this mode goes (configuration submodes: the global configuration); the caller decides whether it tries there
  • struct Parsed<C> a parsed command line

    • cmd: C
    • no: bool -- the line started with "no"
    • vals: Vec<(String, Val)> -- the keywords and parameters in order, by key

impl<C> Parsed<C>

  • fn get(&self, key: &str) -> Option<&Val> the value of a key; a later one hides an earlier one ("name WORD=name" gives the word, "ping X repeat 5 repeat 7" the 7)

  • fn has(&self, key: &str) -> bool the keyword or parameter is there

  • fn num(&self, key: &str) -> Option<i64>

  • fn ip(&self, key: &str) -> Option<[u8; 4]>

  • fn mask(&self, key: &str) -> Option<u8> a netmask's length

  • fn prefix(&self, key: &str) -> Option<([u8; 4], u8)>

  • fn mac(&self, key: &str) -> Option<[u8; 6]>

  • fn ip6(&self, key: &str) -> Option<[u8; 16]>

  • fn prefix6(&self, key: &str) -> Option<([u8; 16], u8)> an IPv6 address with its prefix length

  • fn text(&self, key: &str) -> Option<&str> a word, line, name or keyword as text

  • enum Error why a line does not parse

    • Empty -- nothing was typed
    • Invalid(usize) -- no command goes on at this byte of the line (the "^" marker)
    • Incomplete -- the line ends before the command does
    • Ambiguous(usize) -- the word at this byte fits several commands

impl Error

  • fn render(&self, col: usize, line: &str) -> String the console text; col is where the line starts on the screen (the prompt's length), so the marker stands under the bad character

  • enum Help the answer to "?"

    • List { title: Option<String>, items: Vec<(String, String)>, cr: bool } -- what may follow: (label, description) in display order; cr when the command may end here; the mode's title for an empty line
    • Words(Vec<String>) -- the keywords a partly typed word may become
    • Unrecognized -- nothing starts like the partly typed word
    • Error(Error)

impl Help

  • fn render(&self, col: usize, line: &str) -> String the console text (col: the prompt's length, for an error marker)

  • struct Completion what Tab does

    • line: Option<String> -- the line with the last word completed (None: nothing to complete, the console rings the bell)
    • choices: Vec<String> -- what the last word may become
  • fn parse_ipv4(s: &str) -> Option<[u8; 4]> "10.1.2.3" -> [10, 1, 2, 3] (four decimal parts of at most 255, no signs)

  • fn parse_mask(s: &str) -> Option<u8> the length of a contiguous dotted netmask ("255.255.255.0" -> 24)

  • fn parse_mac(s: &str) -> Option<[u8; 6]> "aabb.ccdd.eeff", "aa:bb:cc:dd:ee:ff" or "aa-bb-cc-dd-ee-ff"

  • fn parse_ipv6(s: &str) -> Option<[u8; 16]> an IPv6 address in any RFC 4291 text form: eight groups of up to four hex digits, "::" once for a run of zero groups, the last 32 bits as dotted decimal ("::ffff:10.0.0.1"); hex digits in either case

  • struct Tree<C> a tree of commands in modes

impl<C: Copy> Tree<C>

  • fn new() -> Tree<C>
  • fn mode(&mut self, prompt: &str, title: &str, parent: Option<ModeId>, no_help: Option<&str>) -> ModeId a new mode; no: a "no" keyword negates its commands (no_help is its help text)
  • fn mode_info(&self, m: ModeId) -> &Mode
  • fn find_mode(&self, prompt: &str) -> Option<ModeId> the mode with this prompt suffix ("(config-ext-nacl)#"; the first one made)
  • fn prompt(&self, m: ModeId, host: &str) -> String the prompt of a mode for a host name ("R1(config)#")
  • fn add(&mut self, mode: ModeId, path: &str, help: &str, cmd: Option<C>, flags: u8) -> NodeId adds a command path: help describes its last word; cmd makes the command complete there; flags (F_NO, F_HIDDEN) go to the last word
  • fn add_no(&mut self, mode: ModeId, path: &str, cmd: C) the no-form of a command may end at path ("no ip address" without an address)
  • fn also(&mut self, mode: ModeId, path: &str, target: &str) after path, the words that follow target may follow as well (a list of options in any order: "ping A repeat 5 size 100")
  • fn parse(&self, mode: ModeId, line: &str, names: &dyn Names) -> Result<Parsed<C>, Error> the command a line of mode is
  • fn help(&self, mode: ModeId, line: &str, names: &dyn Names) -> Help the answer to "?" typed right after line (a partly typed last word lists what it may become; after a space, what may follow)
  • fn complete(&self, mode: ModeId, line: &str, names: &dyn Names) -> Completion Tab: the last, partly typed word written out when only one keyword or name type fits
  • fn knows_first(&self, mode: ModeId, line: &str) -> bool does the first word of a line name a command of mode (a keyword or the "no" of the mode, abbreviations included)? An IOS-like EXEC answers unknown first words with a host name lookup instead of the marker.

base/hashring.rs#

Source: lib/base/hashring.rs

hashring -- consistent hashing: a ring of tokens with virtual nodes per member; a key belongs
to the member of the first token at or after its hash (going round at the end), and its
preference list is the next n distinct members from there (sharded stores, load balancers
with sticky keys).  Adding or removing a member moves only the keys of its own tokens.

  hash64(bytes) -> u64                    FNV-1a (64 bit) with a final mix; the same on every
                                          target
  Ring::new() / add(member, key, vnodes) / remove(&member) / members() / tokens()
  owner(h) -> Option<&M>                  the member of the first token at or after h
  preference(h, n) -> Vec<M>              the first n distinct members from h on
  preference_by(h, n, ok)                 the same, skipping members ok() refuses
  shares() -> Vec<(M, u32)>               each member's part of the ring in parts per million

The tokens of a member come from its key and the vnode number ("10.0.4.11#3"), so every
device that knows the members builds the same ring.
  • fn hash64(b: &[u8]) -> u64 FNV-1a over the bytes, then the finaliser of SplitMix64 (spreads close keys over the ring)

  • struct Ring<M: Ord + Clone> a ring of tokens; M names a member (an address, a backend)

impl<M: Ord + Clone> Ring<M>

  • fn new() -> Ring<M>
  • fn add(&mut self, m: M, key: &str, vnodes: u32) adds a member with vnodes tokens made from key (a member that is there already gets its tokens again)
  • fn remove(&mut self, m: &M) -> bool removes a member and its tokens
  • fn members(&self) -> &[M] the members, sorted
  • fn tokens(&self) -> &[(u64, M)] the tokens with their members, sorted by token
  • fn is_empty(&self) -> bool
  • fn owner(&self, h: u64) -> Option<&M> the member a hash belongs to
  • fn preference(&self, h: u64, n: usize) -> Vec<M> the first n distinct members from h on, in ring order
  • fn preference_by(&self, h: u64, n: usize, ok: impl Fn(&M) -> bool) -> Vec<M> the first n distinct members from h on that ok accepts
  • fn shares(&self) -> Vec<(M, u32)> the part of the hash space each member owns, in parts per million (sorted by member)

base/lru.rs#

Source: lib/base/lru.rs

lru -- a map that forgets the least recently used entries: a limit on the number of entries
and one on their weight (bytes), ordered maps only (deterministic, no hashing); caches of
simulators and servers

  Lru::new(max_len, max_weight)          0: no limit
  get(k) (counts as a use) / peek(k) / contains(k) / get_mut(k)
  insert(k, v, weight) -> evicted        the entries that had to go, oldest first (the new
                                         one itself when it alone is too heavy)
  remove(k) / pop_lru() / clear() / len() / weight() / keys() (oldest first)

Every use moves an entry to the young end; eviction takes from the old end until both
limits hold.  Costs are O(log n) per call.
  • struct Lru<K: Ord + Clone, V> a least-recently-used map
    • max_len: usize -- entries at most (0: no limit)
    • max_weight: u64 -- summed weight at most (0: no limit)

impl<K: Ord + Clone, V> Lru<K, V>

  • fn new(max_len: usize, max_weight: u64) -> Lru<K, V>
  • fn len(&self) -> usize
  • fn is_empty(&self) -> bool
  • fn weight(&self) -> u64 the summed weight of the entries
  • fn contains(&self, k: &K) -> bool
  • fn peek(&self, k: &K) -> Option<&V> an entry without counting it as a use
  • fn get(&mut self, k: &K) -> Option<&V> an entry; it becomes the most recently used
  • fn get_mut(&mut self, k: &K) -> Option<&mut V> an entry to change in place; it becomes the most recently used
  • fn insert(&mut self, k: K, v: V, weight: u64) -> Vec<(K, V)> stores an entry (replacing one with the same key) as the most recently used; the entries that had to go for the limits, oldest first
  • fn remove(&mut self, k: &K) -> Option<V>
  • fn pop_lru(&mut self) -> Option<(K, V)> takes the least recently used entry
  • fn clear(&mut self)
  • fn keys(&self) -> impl Iterator<Item = &K> the keys, least recently used first
  • fn iter(&self) -> impl Iterator<Item = (&K, &V)> the entries in key order (no use counted)

base/pattern.rs#

Source: lib/base/pattern.rs

pattern -- shell wildcards and a small engine for regular expressions (the shells of
JFNetworker's hosts: globs, find -name, grep)

  glob(pat, s) -> bool          fnmatch(3) without flags: * any run of characters, ? one,
                                [abc] [a-z] [!x] [^x] [[:digit:]] one of a set, \x the
                                character x; '/' and a leading '.' are ordinary characters
                                here (a caller matches path components one by one and hides
                                dot files itself)
  has_glob(s) -> bool           s holds an unescaped *, ? or [ (a word to expand)
  Regex::new(pat, Syntax::Basic | Syntax::Extended, icase) -> Result<Regex, ReErr>
  Regex::is_match(s)            the expression matches somewhere in s
  Regex::find(s) / find_at(s, from) -> Option<(start, end)>   byte offsets of the leftmost
                                match, the longest one starting there (POSIX)
  ReErr::text()                 the error in GNU grep's words ("Unmatched ( or \(")

The expressions are POSIX's basic (BRE) and extended (ERE) syntax without back-references
and collating elements: characters, ".", bracket expressions with ranges, negation and the
classes [:alpha:] [:digit:] [:alnum:] [:upper:] [:lower:] [:space:] [:blank:] [:punct:]
[:xdigit:] [:print:] [:graph:] [:cntrl:]; the anchors ^ and $; the repetitions *, and in
ERE + ? {m} {m,} {m,n} (BRE: \+ \? \{m,n\} as GNU takes them); groups ( ) and alternatives |
(BRE: \( \) \|); GNU's \w \W \s \S and the word edges \< \> \b \B.  As GNU does, a
repetition with nothing before it is an ordinary character, an ERE "{" that starts no
interval too, and BRE takes ^ and $ as anchors only at the ends of the expression or of a
group.  Matching runs a Pike VM over the characters: time grows with the text times the
program, never exponentially; a repetition counts to 255 at most and a program has at most
20000 steps (ReErr::TooBig beyond).  Case-insensitive matching compares simple lowercase
forms.
  • fn glob(pat: &str, s: &str) -> bool the wildcard pattern matches all of s (fnmatch without flags)

  • fn has_glob(s: &str) -> bool the word holds an unescaped wildcard (*, ? or [)

  • enum Syntax which syntax an expression is written in

    • Basic -- POSIX basic (grep): \( \) \{ \} \| \+ \? are the operators
    • Extended -- POSIX extended (grep -E, egrep)
  • enum ReErr why an expression does not compile

    • Paren -- an open group without its end
    • CloseParen -- a group's end without its start
    • Bracket -- a bracket expression without its ']'
    • Range -- a range whose end comes before its start
    • Class -- [:name:] with a name that is no class
    • Backslash -- a '\' at the end
    • Brace -- \{ without \}
    • BraceContent -- what is between { and } is no interval
    • Repeat -- a repetition of something that cannot repeat
    • TooBig -- the program would be too long

impl ReErr

  • fn text(self) -> &'static str GNU grep's message

  • struct Regex a compiled regular expression

impl Regex

  • fn new(pat: &str, syntax: Syntax, icase: bool) -> Result<Regex, ReErr> compiles an expression; icase: upper and lower case are the same
  • fn is_match(&self, s: &str) -> bool the expression matches somewhere in s
  • fn find(&self, s: &str) -> Option<(usize, usize)> the leftmost match (the longest of those starting there): byte offsets
  • fn find_at(&self, s: &str, from: usize) -> Option<(usize, usize)> as find, starting the search at byte from (the edges still see the text before it)

Source: docs/API.md in the JFLib repository.