#! @file indexable.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the indexable trait, which lets a type of the standard library or of a #! program be written `d[key]`, the way the language already writes a fixed array, #! a pointer, and a view. module core; #! Defines that a type is indexed by a key, giving the element it holds there. #! #! `d[key]` is `d.at(key)`: the reference the accessor gives, which is read, #! assigned through, and bound as any reference is, so indexing copies nothing. #! `val e := d[key]` refers to the element, and `val e: V = d[key]` copies it. #! There are two accessors, both named `at`: one taking `&this` gives a `&V`, and #! one taking `&mut this` gives a `&mut V`. The receiver chooses between them, so #! a value that can be written is given the element to write, and one that #! cannot is given it only to read. #! #! Only `at(&this)` is required. A type that is only ever read leaves out the #! other, which is `@optional`, and is then read through `at(&this)` however it #! is held, so writing an element of it is an error where it is written. #! #! Both accessors are given the same key, and both are expected to stop a #! checked program where the key is one the value does not hold, as indexing a #! fixed array outside its length does, with `if const checking()`: one that #! is not checked trusts the key, as C does. A key that may be one the value #! does not hold in a program that is right is asked of a `get` the type gives #! beside this trait, returning `maybe<&V>`, as each container of std's does. #! #! Traits are satisfied by shape, as they are everywhere else, so a type with #! `at` is indexable whether or not it names the trait. Naming it is still worth #! doing: it says the type means to be indexed, and it is what a `where` clause #! bounds a type parameter by. #! @tparam K The type of the keys it is indexed by. #! @tparam V The type of the elements it holds. pub trait indexable { #! Reaches the element held at a key, to read it. #! @param this The value to index. #! @param key The key of the element. #! @returns The element. #! @remarks A key the value does not hold stops a checked program. def at(&this, key: K): &V; #! Reaches the element held at a key, to write it. #! @param this The value to index. #! @param key The key of the element. #! @returns The element. #! @remarks A key the value does not hold stops a checked program. @optional def at(&mut this, key: K): &mut V; }