plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
0faae62
— Peter John
2026-11-10T23:28:03+05:30
std: at crashes out of range and get is the Option form, everywhere
- compiler/checker/tests/checker/features/primitive_generics.rs +1 -1
- compiler/cli/tests/cli/std_bounds_test.rs +29 -13
- compiler/core/src/native.rs +1 -1
- compiler/core/src/purity.rs +1 -1
- compiler/core/tests/core/uniqueness_moves_test.rs +1 -1
- compiler/game/web-test/fixtures/interleave.plum +1 -1
- compiler/wasm-codegen/src/intrinsics.rs +2 -2
- compiler/wasm-codegen/src/optimize.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs +2 -2
- docs/language.md +1 -1
- docs/std.md +8 -6
- examples/arrays.plum +38 -38
- examples/recursion.plum +1 -1
- std/Array.plum +26 -19
- std/Decimal.plum +3 -3
- std/Int.plum +4 -4
- std/Slice.plum +34 -34
- std/Str.plum +19 -10
- std/collections/BPlusTree.plum +6 -6
- std/collections/BTree.plum +5 -5
- std/collections/Deque.plum +5 -5
- std/collections/Grid.plum +23 -11
- std/collections/List.plum +8 -6
- std/collections/Map.plum +19 -12
- std/collections/Set.plum +7 -2
- std/game/SceneTree.plum +2 -2
- std/math/math.plum +1 -1
- tests/fbip_probes/array_set.plum +1 -1
- tests/std/collections.plum +5 -5
- tests/std/map_model.plum +1 -1
compiler/checker/tests/checker/features/primitive_generics.rs
CHANGED
|
@@ -23,7 +23,7 @@ fn primitiveGenericsAreNotPseudoVariants() {
|
|
|
23
23
|
fn arrayElementTypeIsEnforced() {
|
|
24
24
|
let source = load(
|
|
25
25
|
"c",
|
|
26
|
-
"import std/Array\nimport std/Int\nimport std/Str\n\nfun main() -> Str =\n a := Array<Int>().push(3)\n a.
|
|
26
|
+
"import std/Array\nimport std/Int\nimport std/Str\n\nfun main() -> Str =\n a := Array<Int>().push(3)\n a.at(0)\n",
|
|
27
27
|
);
|
|
28
28
|
assert!(checkSource(&source).is_err());
|
|
29
29
|
}
|
compiler/cli/tests/cli/std_bounds_test.rs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#![allow(non_snake_case)]
|
|
2
|
-
//! std's checked indexing: `Slice.at`, `Deque.at`, `
|
|
2
|
+
//! std's checked indexing: `Slice.at`, `Deque.at`, `List.at`, `Set.at`, `Map.entryAt`, `Str.byteAt`,
|
|
3
|
+
//! `Str.at` and `Grid.at`/`set`
|
|
3
4
|
//! out of range stop the program with the index and the length, instead of reading another slot.
|
|
4
5
|
use std::process::Command;
|
|
5
6
|
|
|
@@ -18,7 +19,7 @@ fn run(name: &str, body: &str) -> (bool, String) {
|
|
|
18
19
|
let dir = crate::common::Scratch::new(&format!("bounds_{name}"));
|
|
19
20
|
let src = dir.join(format!("{name}.plum"));
|
|
20
21
|
let text = format!(
|
|
21
|
-
"import std/Int\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/Slice\nimport std/collections/Deque\nimport std/collections/Grid\n\nfun main(io: Io) =\n{body}"
|
|
22
|
+
"import std/Int\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/Slice\nimport std/collections/Deque\nimport std/collections/Grid\nimport std/collections/List\nimport std/collections/Map\nimport std/collections/Set\n\nfun main(io: Io) =\n{body}"
|
|
22
23
|
);
|
|
23
24
|
std::fs::write(&src, text).unwrap();
|
|
24
25
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
|
@@ -64,16 +65,16 @@ fn deque_at_out_of_range_crashes() {
|
|
|
64
65
|
}
|
|
65
66
|
|
|
66
67
|
#[test]
|
|
67
|
-
fn
|
|
68
|
+
fn str_byte_at_and_at_out_of_range_crash() {
|
|
68
69
|
expectCrash(
|
|
69
70
|
"str_byte",
|
|
70
71
|
" s := \"abcdef\".sub(1, 3)\n io.printLn(\"{s.byteAt(2)}\")\n",
|
|
71
72
|
"Str.byteAt: index 2 out of range for length 2",
|
|
72
73
|
);
|
|
73
74
|
expectCrash(
|
|
74
|
-
"
|
|
75
|
+
"str_at",
|
|
75
|
-
" io.printLn(\"ab\".
|
|
76
|
+
" io.printLn(\"ab\".at(-1))\n",
|
|
76
|
-
"Str.
|
|
77
|
+
"Str.at: index -1 out of range for length 2",
|
|
77
78
|
);
|
|
78
79
|
}
|
|
79
80
|
|
|
@@ -86,17 +87,32 @@ fn in_range_reads_still_work() {
|
|
|
86
87
|
assert!(ok, "stderr: {stderr}");
|
|
87
88
|
}
|
|
88
89
|
|
|
89
|
-
/// `Grid.
|
|
90
|
+
/// `Grid.at`/`set` off the grid crash with the cell and the size, a column past the row
|
|
90
91
|
/// included (its flat index is still inside the array: it would read the next row).
|
|
91
92
|
#[test]
|
|
92
|
-
fn
|
|
93
|
+
fn grid_at_and_set_off_the_grid_crash() {
|
|
93
94
|
expectCrash(
|
|
94
|
-
"
|
|
95
|
+
"grid_at_past_row",
|
|
95
|
-
" g := Grid.filled(4, 3, 0)\n io.printLn(\"{g.
|
|
96
|
+
" g := Grid.filled(4, 3, 0)\n io.printLn(\"{g.at(4, 0)}\")\n",
|
|
96
|
-
"Grid.
|
|
97
|
+
"Grid.at: cell (4, 0) is off the 4 x 3 grid",
|
|
97
98
|
);
|
|
98
|
-
expectCrash("
|
|
99
|
+
expectCrash("grid_at_negative", " g := Grid.filled(4, 3, 0)\n io.printLn(\"{g.at(0, -1)}\")\n", "Grid.at: cell (0, -1) is off the 4 x 3 grid");
|
|
99
100
|
expectCrash("grid_set_below", " g := Grid.filled(4, 3, 0)\n g.set(1, 3, 7)\n", "Grid.set: cell (1, 3) is off the 4 x 3 grid");
|
|
100
|
-
let (ok, stderr) = run("grid_fine", " g := Grid.filled(4, 3, 0)\n g.set(3, 2, 7)\n io.printLn(\"{g.
|
|
101
|
+
let (ok, stderr) = run("grid_fine", " g := Grid.filled(4, 3, 0)\n g.set(3, 2, 7)\n io.printLn(\"{g.at(3, 2)} {g.get(4, 0).isNone()}\")\n");
|
|
102
|
+
assert!(ok, "stderr: {stderr}");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/// `at` on `List` and `Set` and `entryAt` on `Map` crash with the index and the length; their
|
|
106
|
+
/// `get` and `getEntryAt` forms give None instead.
|
|
107
|
+
#[test]
|
|
108
|
+
fn list_set_and_map_positional_reads_crash_out_of_range() {
|
|
109
|
+
expectCrash("list_at", " l := [1, 2]\n io.printLn(\"{l.at(2)}\")\n", "List.at: index 2 out of range for length 2");
|
|
110
|
+
expectCrash("set_at", " s := Set.fromSlice([5, 6, 7].toSlice())\n io.printLn(\"{s.at(3)}\")\n", "Set.at: index 3 out of range for length 3");
|
|
111
|
+
expectCrash("set_at_negative", " s := Set.fromSlice([5].toSlice())\n io.printLn(\"{s.at(-1)}\")\n", "Set.at: index -1 out of range for length 1");
|
|
112
|
+
expectCrash("map_entry_at", " m := [1 => 10, 2 => 20]\n io.printLn(\"{m.entryAt(2).second}\")\n", "Map.entryAt: index 2 out of range for length 2");
|
|
113
|
+
let (ok, stderr) = run(
|
|
114
|
+
"positional_fine",
|
|
115
|
+
" s := Set.fromSlice([5, 6, 7].toSlice())\n m := [1 => 10, 2 => 20]\n io.printLn(\"{[1, 2].at(1)} {s.at(2)} {s.get(3).isNone()} {m.entryAt(1).second} {m.getEntryAt(2).isNone()}\")\n",
|
|
116
|
+
);
|
|
101
117
|
assert!(ok, "stderr: {stderr}");
|
|
102
118
|
}
|
compiler/core/src/native.rs
CHANGED
|
@@ -65,7 +65,7 @@ const TABLE: &[(&str, Native)] = &[
|
|
|
65
65
|
("Float.toBits", Native::Op(NativeOp::I64ReinterpretF64)),
|
|
66
66
|
("Float.fromBits", Native::Op(NativeOp::F64ReinterpretI64)),
|
|
67
67
|
("Array.init", Native::Array),
|
|
68
|
-
("Array.
|
|
68
|
+
("Array.at", Native::Array),
|
|
69
69
|
("Array.set", Native::Array),
|
|
70
70
|
("Array.length", Native::Array),
|
|
71
71
|
("Array.push", Native::Array),
|
compiler/core/src/purity.rs
CHANGED
|
@@ -180,7 +180,7 @@ pub fn readOnlyFns(src: &Source) -> HashSet<String> {
|
|
|
180
180
|
_ => false,
|
|
181
181
|
})
|
|
182
182
|
} else if isBuiltin(f) {
|
|
183
|
-
// a builtin (`Array.
|
|
183
|
+
// a builtin (`Array.at`): one that returns nothing is called for its write
|
|
184
184
|
// (`Array.set`, `Array.copy`); one that returns a value only reads
|
|
185
185
|
f.returns.as_ref().is_none_or(|t| t.name == "Unit")
|
|
186
186
|
} else {
|
compiler/core/tests/core/uniqueness_moves_test.rs
CHANGED
|
@@ -156,7 +156,7 @@ fn a_field_of_a_shared_struct_stays_shared() {
|
|
|
156
156
|
|
|
157
157
|
#[test]
|
|
158
158
|
fn contents_of_an_array_stay_shared() {
|
|
159
|
-
let s = format!("{CELL}fun go(a: Array<Cell>) -> Cell = bump(a.
|
|
159
|
+
let s = format!("{CELL}fun go(a: Array<Cell>) -> Cell = bump(a.at(0))\n");
|
|
160
160
|
let r = run(&s);
|
|
161
161
|
assert!(!provedFn(&r, "bump"), "{r:?}");
|
|
162
162
|
}
|
compiler/game/web-test/fixtures/interleave.plum
CHANGED
|
@@ -61,4 +61,4 @@ fun drawSprites(io: Io, tex: Array<Texture>, t: Int) =
|
|
|
61
61
|
for i := range Sprites
|
|
62
62
|
x := {i * 37 + t * {1 + i % 5}} % WorldW
|
|
63
63
|
y := {i * 53 + t * {1 + i % 3}} % WorldH
|
|
64
|
-
tex.
|
|
64
|
+
tex.at(i % Textures).draw(io, Float(x), Float(y), Color.White)
|
compiler/wasm-codegen/src/intrinsics.rs
CHANGED
|
@@ -316,7 +316,7 @@ pub(crate) fn compileArrayIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<
|
|
|
316
316
|
Instruction::End.encode(&mut body);
|
|
317
317
|
Some(body)
|
|
318
318
|
}
|
|
319
|
-
"
|
|
319
|
+
"at" => {
|
|
320
320
|
let mut body = vec![0u8];
|
|
321
321
|
Instruction::LocalGet(0).encode(&mut body); // self
|
|
322
322
|
Instruction::LocalGet(1).encode(&mut body); // i
|
|
@@ -473,7 +473,7 @@ pub(crate) fn compileSoaArrayIntrinsic(name: &str, elem: &PlumType, soa_idx: u32
|
|
|
473
473
|
Instruction::ArrayLen.encode(&mut body);
|
|
474
474
|
Instruction::I64ExtendI32U.encode(&mut body);
|
|
475
475
|
}
|
|
476
|
-
"
|
|
476
|
+
"at" => {
|
|
477
477
|
body.push(0);
|
|
478
478
|
for k in 0..n {
|
|
479
479
|
leaf_arr(&mut body, 0, k);
|
compiler/wasm-codegen/src/optimize.rs
CHANGED
|
@@ -221,7 +221,7 @@ pub(crate) const INLINE_LIMIT: usize = 20;
|
|
|
221
221
|
/// most `INLINE_LIMIT` bytes that touch no local and hold no block, branch or return: so
|
|
222
222
|
/// the bytes after the loads, put where the `call` was, do the same work on the same
|
|
223
223
|
/// stack (a `return_call` becomes those bytes and a `return`). Accessors such as
|
|
224
|
-
/// `Str.length` or `Array.
|
|
224
|
+
/// `Str.length` or `Array.at` go this way. Returns the number of call sites inlined.
|
|
225
225
|
pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
|
|
226
226
|
let bytes = module.encode();
|
|
227
227
|
let imports = module.func_import_count;
|
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs
CHANGED
|
@@ -2404,10 +2404,10 @@ struct Vec2(x: Float, y: Float)
|
|
|
2404
2404
|
|
|
2405
2405
|
fun main() -> Float =
|
|
2406
2406
|
a := Array<Vec2>().push(Vec2(x: 1.0, y: 2.0)).push(Vec2(x: 3.0, y: 4.0))
|
|
2407
|
-
v := a.
|
|
2407
|
+
v := a.at(1)
|
|
2408
2408
|
a.set(0, Vec2(x: v.x + 1.0, y: v.y))
|
|
2409
2409
|
b := a.resize(5)
|
|
2410
|
-
a.
|
|
2410
|
+
a.at(0).x + b.at(1).y
|
|
2411
2411
|
";
|
|
2412
2412
|
let dir = plum_test_support::Scratch::at(std::env::temp_dir().join(format!("plum_soa_{}", std::process::id())));
|
|
2413
2413
|
let path = dir.join("main.plum");
|
docs/language.md
CHANGED
|
@@ -768,7 +768,7 @@ primitive Int =
|
|
|
768
768
|
fun popCount(self) -> Int = @native
|
|
769
769
|
```
|
|
770
770
|
|
|
771
|
-
`@native` as a function's whole body says the compiler supplies the body: a wasm instruction (`Float.sqrt`, `Int.popCount`), an array operation (`Array.
|
|
771
|
+
`@native` as a function's whole body says the compiler supplies the body: a wasm instruction (`Float.sqrt`, `Int.popCount`), an array operation (`Array.at`), or what a built-in does. Only std declares such functions, and the compiler knows each by its name (`Int.popCount`, `math.sqrt`), not by the file it is in.
|
|
772
772
|
|
|
773
773
|
It is an error to write `@native` anywhere else: inside an expression, in a block with other statements, in a closure, a constant or a test, or in a file outside std. A `@native` function the compiler has no implementation for is an error at the function.
|
|
774
774
|
|
docs/std.md
CHANGED
|
@@ -69,13 +69,15 @@ fun main() =
|
|
|
69
69
|
- **Change:** `replace`, `replaceAll`, `repeat`, `reverse`, `padStart`, `padEnd`
|
|
70
70
|
- **Case:** `upperCase`, `lowerCase`, `capitalize`, `camelCase`, `snakeCase`, `kebabCase`
|
|
71
71
|
- **Unicode:** `length` counts bytes; `runeLength` and `runeAt` count characters. `runeAt(i)` is an `Option<Str>`, `None` past the last character.
|
|
72
|
-
- **Bytes:** `byteAt(i)` and `
|
|
72
|
+
- **Bytes:** `byteAt(i)` (the byte as an `Int`) and `at(i)` (the one-byte `Str`) crash with the index and the length out of range, so a substring never reads its source's bytes outside it; `get(i)` is `at(i)` as an `Option`, `None` out of range.
|
|
73
73
|
|
|
74
74
|
`Str` has no `+`: join strings with interpolation, `"{a}{b}"`, or `a.concat(b)`. To build a string in steps, use `Buffer`: `write`, `writeByte`, `toStr`.
|
|
75
75
|
|
|
76
76
|
## Sequences
|
|
77
77
|
|
|
78
|
-
|
|
78
|
+
Across std, positional access follows one rule: `at` gives the element and crashes when the position is out of range, and `get` gives an `Option`, `None` out of range. `List`, `Slice`, `Array`, `Grid`, `Deque`, `Set` and `Str` have both; on a `Map`, whose `get` takes a key, they are `entryAt(i)` and `getEntryAt(i)`.
|
|
79
|
+
|
|
80
|
+
**`List`** suits recursion: `map`, `filter`, `fold`, `each`, `find`, `any`, `all`, `append`, `reverse`, `length`, `isEmpty`, `get` (an `Option`), `at` (crashes with the index and the length out of range), `join(sep)` (each element's `toStr()` with `sep` between, like `Slice.join`), `toSlice`, `toArray`, `List.fromSlice`, `==`. Each runs in constant stack (a million elements are fine).
|
|
79
81
|
|
|
80
82
|
**`Slice`** is a growable array:
|
|
81
83
|
|
|
@@ -96,9 +98,9 @@ fun main() =
|
|
|
96
98
|
- **Change:** `push`, `pop`, `set`, `add`, `remove`, `removeAt`, `clear`, `reverse`, `shuffle`
|
|
97
99
|
- **Other:** `sort(before)` (a new slice; a stable merge sort, O(n log n)), `slice` (a view that shares storage), `sublist` (a copy), `chunk`, `join`, `drop`, `==` (the same elements in order; a view equals a copy), and with `std/collections/Map` imported `groupBy(key)` (a `Map` from each key to its elements, in order; the groups come in key order)
|
|
98
100
|
|
|
99
|
-
Renamed or removed: `Slice.head` (use `first`), `Set.toList` is now `toSlice`, and membership is `contains` on every collection (`Map.has`, `Set.has` and the `has` of the trees in `std/collections` are gone).
|
|
101
|
+
Renamed or removed: `Slice.head` (use `first`), `Set.toList` is now `toSlice`, `Set.at(i)` now crashes out of range (its `Option` form is `get(i)`), `Map.entryAt(i)` likewise (the `Option` form is `getEntryAt(i)`), `Array.get`, `Str.get` and `Grid.get` are now `at` and `get` is their `Option` form, and membership is `contains` on every collection (`Map.has`, `Set.has` and the `has` of the trees in `std/collections` are gone).
|
|
100
102
|
|
|
101
|
-
**`Array`** has a fixed size: `Array.filled(n, value)`, `get`, `set`, `length`. **`Grid`** is a 2D array: `Grid.filled(w, h, value)`, `
|
|
103
|
+
**`Array`** has a fixed size: `Array.filled(n, value)`, `at` (the raw wasm `array.get`: out of range it traps without a message), `get` (an `Option`), `set`, `length`. **`Grid`** is a 2D array: `Grid.filled(w, h, value)`, `at(x, y)`, `set(x, y, value)` (both crash with the cell and the size off the grid), `get(x, y)` (an `Option`, `None` off the grid), `inBounds(x, y)`.
|
|
102
104
|
|
|
103
105
|
## Collections
|
|
104
106
|
|
|
@@ -123,14 +125,14 @@ fun main() =
|
|
|
123
125
|
- **Build:** `Map.empty()`, `Map<Str, Int>()`, `Map.single(k, v)`, a literal `[k => v, ..]` (it is `Map.empty().with(k, v)...`, so O(n log n), and a later duplicate key wins), `Map.fromSlice(entries)` and `Map.fromList(entries)` (O(n) when the keys already strictly ascend, else O(n log n); a later duplicate wins).
|
|
124
126
|
- **Read, O(log n):** `get(k)` (an `Option`), `getOr(k, fallback)` (no `Option` made), `contains(k)`; O(1): `length`, `isEmpty`.
|
|
125
127
|
- **Update, O(log n), each returning the new map:** `with(k, v)` (also called `set`), `remove(k)`, `putIfAbsent(k, v)`, `upsert(k, v, f)` (`f` of the old value, or `v` when absent: Data.Map's `insertWith`), `update(k, f)` (only when present: `adjust`), `alter(k, f)` (`f` takes the value or `None` and returns the new one or `None` to leave `k` out).
|
|
126
|
-
- **Order, O(log n):** `min`, `max` (the entry with the smallest or largest key, an `Option<Pair<K, V>>`), `removeMin`, `removeMax`, the neighbours of a key `below(k)` (largest key `< k`), `atMost(k)` (`<=`), `above(k)` (`>`), `atLeast(k)` (`>=`), `entryAt(i)` (the `i`-th entry from 0), `indexOf(k)` (an `Option<Int>`), `rank(k)` (how many keys come before `k`, present or not), `height`.
|
|
128
|
+
- **Order, O(log n):** `min`, `max` (the entry with the smallest or largest key, an `Option<Pair<K, V>>`), `removeMin`, `removeMax`, the neighbours of a key `below(k)` (largest key `< k`), `atMost(k)` (`<=`), `above(k)` (`>`), `atLeast(k)` (`>=`), `entryAt(i)` (the `i`-th entry from 0; crashes with the index and the length out of range), `getEntryAt(i)` (the same as an `Option`), `indexOf(k)` (an `Option<Int>`), `rank(k)` (how many keys come before `k`, present or not), `height`.
|
|
127
129
|
- **Ranges, O(log n), sharing nodes with the map:** `from(lo)` (keys `>= lo`), `until(hi)` (keys `< hi`), `range(lo, hi)` (`lo <= key < hi`), `split(k)` (the maps of keys before and after `k`, as a `Pair`), and its inverse `a.join(b)` (every key of `a` must be before every key of `b`, or it crashes). `foldRange(lo, hi, acc, f)` folds over `lo <= key < hi` without building a map.
|
|
128
130
|
- **Combine, O(m log(n / m + 1)) for sizes m <= n:** `union` (a key in both keeps `self`'s value), `unionWith(o, f)` (`f(self's value, o's value)`), `intersection` (`self`'s values), `difference`.
|
|
129
131
|
- **Walk, O(n), in key order:** `fold(acc, |acc, k, v| ..)`, `each(|k, v| ..)`, `map(|v| ..)` (same keys and shape), `filter(|k, v| ..)`, `any`, `all`, `keys`, `values` and `entries` (each a new `Slice`), `toStr` (`[1 => one, 2 => two]`; interpolating a map, `"{m}"`, isn't supported yet, so write `"{m.toStr()}"`), `==`. `for e := range m` takes O(log n) a step (each step is `min` and `removeMin`); `entries()` is cheaper when you read every entry. Every walk is O(log n) deep, so a 1,000,000-entry map is fine.
|
|
130
132
|
|
|
131
133
|
Gone or changed from the old hash table: `set`, `remove` and `putIfAbsent` return the new map instead of changing the receiver (`with` no longer changes it either); `clear` is gone (use `Map.empty()`); keys need `compare` instead of `hash`; iteration is key order, not insertion order; `Map.toJson` writes object fields in key order. Against the hash table, `Map<Int, Int>` gets and sets are about 3x slower (`benchmarks/master_vs_simpler/branch/map`): every insert allocates the O(log n) nodes on its path, and the compiler's cell reuse does not yet reach a generic method, so those nodes are not updated in place even when the map is unique.
|
|
132
134
|
|
|
133
|
-
**`Set<T>`** is a persistent ordered set, the keys of a `Map<T, Bool>`, with the same costs and the same `compare` on its members. `Set<Int>()` or `Set.empty()`, `Set.fromSlice`, `Set.fromList`; `add`, `remove` (each returns the new set), `contains`, `length`, `isEmpty`, `min`, `max`, `removeMin`, `removeMax`, `below`, `atMost`, `above`, `atLeast`, `at(i)`, `indexOf`, `rank`, `from`, `until`, `range`, `foldRange`, `split`, `join`, `union`, `intersection`, `difference`, `isSubsetOf`, `fold`, `each`, `filter`, `any`, `all`, `toSlice` (ascending), `for x := range s`, `==`, `toStr` (`[1, 2, 3]`). `clear` is gone.
|
|
135
|
+
**`Set<T>`** is a persistent ordered set, the keys of a `Map<T, Bool>`, with the same costs and the same `compare` on its members. `Set<Int>()` or `Set.empty()`, `Set.fromSlice`, `Set.fromList`; `add`, `remove` (each returns the new set), `contains`, `length`, `isEmpty`, `min`, `max`, `removeMin`, `removeMax`, `below`, `atMost`, `above`, `atLeast`, `at(i)` (the `i`-th member; crashes out of range), `get(i)` (an `Option`), `indexOf`, `rank`, `from`, `until`, `range`, `foldRange`, `split`, `join`, `union`, `intersection`, `difference`, `isSubsetOf`, `fold`, `each`, `filter`, `any`, `all`, `toSlice` (ascending), `for x := range s`, `==`, `toStr` (`[1, 2, 3]`). `clear` is gone.
|
|
134
136
|
|
|
135
137
|
- **`Deque`:** a queue you can use from both ends: `pushBack`, `pushFront`, `popBack`, `popFront`, `get`, `at` (crashes out of range)
|
|
136
138
|
- **`Heap`:** gives back first the item nothing comes `before`: `h: Heap<Int> := Heap.by(|a, b| a < b)`, or `Heap.byKey(|n| n.cost)` by a key of any type with `<`; `push`, `pop`, `peek`
|
examples/arrays.plum
CHANGED
|
@@ -15,17 +15,17 @@ import std/Slice
|
|
|
15
15
|
# unboxed wasm arrays (i64 / f64 / i32 elements), not boxed anyref arrays.
|
|
16
16
|
fun sumInts(n: Int) -> Int =
|
|
17
17
|
a := Array.filled(n, 3)
|
|
18
|
-
0.until(n).fold(0, |total, i| total + a.
|
|
18
|
+
0.until(n).fold(0, |total, i| total + a.at(i))
|
|
19
19
|
|
|
20
20
|
fun sumFloats(n: Int) -> Float =
|
|
21
21
|
a := Array.filled(n, 0.5)
|
|
22
|
-
0.until(n).fold(0.0, |total, i| total + a.
|
|
22
|
+
0.until(n).fold(0.0, |total, i| total + a.at(i))
|
|
23
23
|
|
|
24
24
|
fun countTrue(n: Int) -> Int =
|
|
25
25
|
a := Array.filled(n, false)
|
|
26
26
|
a.set(1, true)
|
|
27
27
|
a.set(3, true)
|
|
28
|
-
0.until(n).fold(0, |count, i| if a.
|
|
28
|
+
0.until(n).fold(0, |count, i| if a.at(i) then count + 1 else count)
|
|
29
29
|
|
|
30
30
|
# ==== struct arrays ====
|
|
31
31
|
|
|
@@ -60,7 +60,7 @@ fun bump(h: Holder) =
|
|
|
60
60
|
h.arr.set(0, Vec2(x: 77.0, y: 88.0))
|
|
61
61
|
|
|
62
62
|
fun first<T>(a: Array<T>) -> T =
|
|
63
|
-
a.
|
|
63
|
+
a.at(0)
|
|
64
64
|
|
|
65
65
|
fun mk() -> Array<Vec2> =
|
|
66
66
|
Array<Vec2>().push(Vec2(x: 1.0, y: 2.0))
|
|
@@ -96,29 +96,29 @@ test "List<Vec2> push/get/set round-trips across growth"
|
|
|
96
96
|
test "nested struct (Rect of Vec2s) in an Array"
|
|
97
97
|
a := Array<Rect>().push(Rect(pos: Vec2(x: 1.0, y: 2.0), size: Vec2(x: 3.0, y: 4.0))).push(Rect(pos: Vec2(x: 5.0, y: 6.0), size: Vec2(x: 7.0, y: 8.0)))
|
|
98
98
|
assert a.length() == 2
|
|
99
|
-
r := a.
|
|
99
|
+
r := a.at(1)
|
|
100
100
|
assert r.pos.x == 5.0
|
|
101
101
|
assert r.pos.y == 6.0
|
|
102
102
|
assert r.size.x == 7.0
|
|
103
103
|
assert r.size.y == 8.0
|
|
104
104
|
a.set(0, Rect(pos: r.size, size: r.pos))
|
|
105
|
-
assert a.
|
|
105
|
+
assert a.at(0).pos.y == 8.0
|
|
106
|
-
assert a.
|
|
106
|
+
assert a.at(0).size.x == 5.0
|
|
107
|
-
assert a.
|
|
107
|
+
assert a.at(0).area() == 30.0
|
|
108
108
|
|
|
109
109
|
test "struct with Int, Bool and Float leaves"
|
|
110
110
|
a := Array<Tile>().push(Tile(id: 7, solid: true, weight: 1.5)).push(Tile(id: 9, solid: false, weight: 2.5))
|
|
111
|
-
assert a.
|
|
111
|
+
assert a.at(0).id == 7
|
|
112
|
-
assert a.
|
|
112
|
+
assert a.at(0).solid
|
|
113
|
-
assert a.
|
|
113
|
+
assert a.at(0).weight == 1.5
|
|
114
|
-
assert a.
|
|
114
|
+
assert a.at(1).id == 9
|
|
115
|
-
assert !a.
|
|
115
|
+
assert !a.at(1).solid
|
|
116
|
-
assert a.
|
|
116
|
+
assert a.at(1).weight == 2.5
|
|
117
117
|
b := a.resize(4)
|
|
118
118
|
assert b.length() == 4
|
|
119
|
-
assert b.
|
|
119
|
+
assert b.at(1).id == 9
|
|
120
|
-
assert b.
|
|
120
|
+
assert b.at(3).id == 0
|
|
121
|
-
assert !b.
|
|
121
|
+
assert !b.at(3).solid
|
|
122
122
|
|
|
123
123
|
test "copy semantics: a value read from the array is a copy until set"
|
|
124
124
|
l := Slice<Vec2>()
|
|
@@ -144,15 +144,15 @@ test "for x := range over Array<Vec2>"
|
|
|
144
144
|
test "Array.filled with a struct"
|
|
145
145
|
a := Array.filled(5, Vec2(x: 2.0, y: 3.0))
|
|
146
146
|
assert a.length() == 5
|
|
147
|
-
assert a.
|
|
147
|
+
assert a.at(4).y == 3.0
|
|
148
148
|
|
|
149
149
|
test "Grid<Tile> get/set"
|
|
150
150
|
g := Grid.filled(3, 2, Tile(id: 1, solid: false, weight: 0.5))
|
|
151
151
|
g.set(2, 1, Tile(id: 42, solid: true, weight: 9.0))
|
|
152
|
-
assert g.
|
|
152
|
+
assert g.at(2, 1).id == 42
|
|
153
|
-
assert g.
|
|
153
|
+
assert g.at(2, 1).solid
|
|
154
|
-
assert g.
|
|
154
|
+
assert g.at(0, 0).id == 1
|
|
155
|
-
assert g.
|
|
155
|
+
assert g.at(1, 1).weight == 0.5
|
|
156
156
|
|
|
157
157
|
test "a List<Vec2> inside a record field"
|
|
158
158
|
w := World(points: Slice<Vec2>(), name: "w")
|
|
@@ -166,50 +166,50 @@ test "a List<Vec2> inside a record field"
|
|
|
166
166
|
test "probe push growth, shrink, single leaf"
|
|
167
167
|
a := 0.until(50).fold(Array<One>(), |grown, i| grown.push(One(n: i)))
|
|
168
168
|
assert a.length() == 50
|
|
169
|
-
assert a.
|
|
169
|
+
assert a.at(49).n == 49
|
|
170
170
|
b := a.resize(10)
|
|
171
171
|
assert b.length() == 10
|
|
172
|
-
assert b.
|
|
172
|
+
assert b.at(9).n == 9
|
|
173
173
|
c := b.resize(0)
|
|
174
174
|
assert c.length() == 0
|
|
175
175
|
|
|
176
176
|
test "probe Byte/Bool leaves"
|
|
177
177
|
a := Array<Flags>().push(Flags(a: false, b: true, c: 3))
|
|
178
|
-
assert a.
|
|
178
|
+
assert a.at(0).b
|
|
179
|
-
assert a.
|
|
179
|
+
assert a.at(0).c == 3
|
|
180
180
|
|
|
181
181
|
test "probe three-level nested"
|
|
182
182
|
a := Array<L3>().push(L3(r: Rect(pos: Vec2(x: 1.0, y: 2.0), size: Vec2(x: 3.0, y: 4.0)), k: 9))
|
|
183
|
-
assert a.
|
|
183
|
+
assert a.at(0).r.size.y == 4.0
|
|
184
|
-
assert a.
|
|
184
|
+
assert a.at(0).k == 9
|
|
185
|
-
assert a.
|
|
185
|
+
assert a.at(0).r.area() == 12.0
|
|
186
186
|
|
|
187
187
|
test "probe array field reference semantics"
|
|
188
188
|
h := Holder(arr: Array<Vec2>().push(Vec2(x: 1.0, y: 1.0)))
|
|
189
189
|
bump(h)
|
|
190
|
-
assert h.arr.
|
|
190
|
+
assert h.arr.at(0).x == 77.0
|
|
191
191
|
alias := h.arr
|
|
192
192
|
alias.set(0, Vec2(x: 5.0, y: 5.0))
|
|
193
|
-
assert h.arr.
|
|
193
|
+
assert h.arr.at(0).x == 5.0
|
|
194
194
|
|
|
195
195
|
test "probe generic first, equality"
|
|
196
196
|
a := Array<Vec2>().push(Vec2(x: 1.0, y: 2.0)).push(Vec2(x: 1.0, y: 2.0))
|
|
197
197
|
assert first(a).y == 2.0
|
|
198
|
-
eq := a.
|
|
198
|
+
eq := a.at(0) == a.at(1)
|
|
199
199
|
assert eq
|
|
200
200
|
|
|
201
201
|
test "probe option and list"
|
|
202
202
|
n: Option<Array<Vec2>> := Some(Array<Vec2>().push(Vec2(x: 3.0, y: 3.0)))
|
|
203
|
-
assert n!.
|
|
203
|
+
assert n!.at(0).x == 3.0
|
|
204
204
|
l := Slice<Array<Vec2>>()
|
|
205
205
|
l.push(Array<Vec2>().push(Vec2(x: 4.0, y: 4.0)))
|
|
206
|
-
assert l.get(0)!.
|
|
206
|
+
assert l.get(0)!.at(0).x == 4.0
|
|
207
207
|
r := mk()
|
|
208
|
-
assert r.
|
|
208
|
+
assert r.at(0).y == 2.0
|
|
209
209
|
|
|
210
210
|
test "probe Str leaf"
|
|
211
211
|
a := Array<Named>().push(Named(label: "hi", v: Vec2(x: 1.0, y: 2.0)))
|
|
212
|
-
assert a.
|
|
212
|
+
assert a.at(0).label == "hi"
|
|
213
213
|
|
|
214
214
|
test "Byte struct fields: copy, compare, store"
|
|
215
215
|
p := mkPx(10)
|
|
@@ -219,8 +219,8 @@ test "Byte struct fields: copy, compare, store"
|
|
|
219
219
|
assert p.a == Byte(255)
|
|
220
220
|
assert p != mkPx(11)
|
|
221
221
|
a := Array<Px>().push(p).push(mkPx(20))
|
|
222
|
-
assert a.
|
|
222
|
+
assert a.at(1).g == Byte(21)
|
|
223
|
-
assert a.
|
|
223
|
+
assert a.at(0) == q
|
|
224
224
|
l := Slice<Px>()
|
|
225
225
|
for i := range 50
|
|
226
226
|
l.push(mkPx(i))
|
examples/recursion.plum
CHANGED
|
@@ -193,7 +193,7 @@ test "to_slice_round_trip"
|
|
|
193
193
|
test "to_array"
|
|
194
194
|
a := [7, 8, 9].toArray()
|
|
195
195
|
assert a.length() == 3
|
|
196
|
-
assert a.
|
|
196
|
+
assert a.at(2) == 9
|
|
197
197
|
|
|
198
198
|
test "map_million"
|
|
199
199
|
ys := range(0, 1000000).map(|x| x + 1)
|
std/Array.plum
CHANGED
|
@@ -4,6 +4,7 @@ import std/Int
|
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Str
|
|
6
6
|
import std/Byte
|
|
7
|
+
import std/Option
|
|
7
8
|
|
|
8
9
|
# A fixed-length, O(1)-indexable array of `T`, backed directly by a wasm-gc
|
|
9
10
|
# array. `T` is NOT erased: codegen allocates one wasm array type per distinct
|
|
@@ -12,16 +13,16 @@ import std/Byte
|
|
|
12
13
|
# `Array<Bool>` is `array<mut i32>`, `Array<Byte>` is packed `array<mut i8>`
|
|
13
14
|
# (one byte per element, the storage `Str` uses), and a reference `T` is
|
|
14
15
|
# `array<mut ref null T>` (all reference types of the same wasm type share one
|
|
15
|
-
# array type). `
|
|
16
|
+
# array type). `at`/`set`/`push`/`resize`/`length`/`filled` on the value
|
|
16
17
|
# arrays are plain `array.get`/`array.set`/`array.copy` on the raw elements —
|
|
17
18
|
# nothing is boxed or allocated per element. `Array<S>` for a `struct` S is
|
|
18
19
|
# stored struct-of-arrays: ONE GC struct holding one native array per leaf of
|
|
19
20
|
# S (`Array<Vec2>` is `{xs: array<mut f64>, ys: array<mut f64>}`, a nested
|
|
20
21
|
# `Rect(pos: Vec2, size: Vec2)` has four f64 arrays, Bool leaves are i32
|
|
21
|
-
# arrays). `
|
|
22
|
+
# arrays). `at` reads each leaf array and leaves the flattened value on the
|
|
22
23
|
# stack, `set` writes each leaf, `push`/`resize` allocate the leaf arrays
|
|
23
24
|
# together: no per-element allocation. (Records and other reference types
|
|
24
|
-
# stay arrays of references.) `init`/`
|
|
25
|
+
# stay arrays of references.) `init`/`at`/`set`/`length`/
|
|
25
26
|
# `push`/`resize` are compiler intrinsics (see `compileIntrinsicFnBody`) —
|
|
26
27
|
# there's no way to express raw array allocation/indexing in Plum source itself.
|
|
27
28
|
# `Slice<T>` is built on this.
|
|
@@ -31,18 +32,19 @@ import std/Byte
|
|
|
31
32
|
# longer and copies (a wasm-gc `array` has a fixed length once made), so filling an array
|
|
32
33
|
# by `push` is O(n^2): size it first.
|
|
33
34
|
#
|
|
34
|
-
# New slots are the wasm default: null for a reference `T` (so `
|
|
35
|
+
# New slots are the wasm default: null for a reference `T` (so `at` on a
|
|
35
36
|
# never-`set` index traps), zero for a value `T` (`Int`/`Float`/`Bool`/`Byte`).
|
|
36
37
|
primitive Array<T> =
|
|
37
38
|
# A new, empty array.
|
|
38
39
|
fun init() -> Array<T> = @native
|
|
39
40
|
|
|
41
|
+
# The element at index `i` (also the `for x := range array` protocol, with `length()`).
|
|
40
|
-
#
|
|
42
|
+
# Traps if `i` is out of range (or, for a reference `T`, was never `set`).
|
|
41
|
-
fun
|
|
43
|
+
fun at(self, i: Int) -> T = @native
|
|
42
44
|
|
|
43
|
-
#
|
|
45
|
+
# The element at index `i`, or None when `i` is out of range.
|
|
44
|
-
fun
|
|
46
|
+
fun get(self, i: Int) -> Option<T> =
|
|
45
|
-
self.
|
|
47
|
+
if i < 0 || i >= self.length() then None else Some(self.at(i))
|
|
46
48
|
|
|
47
49
|
# Overwrites the element at index `i` with `v`. Traps if `i` is out of range.
|
|
48
50
|
fun set(self, i: Int, v: T) -> Unit = @native
|
|
@@ -83,7 +85,7 @@ primitive Array<T> =
|
|
|
83
85
|
test "Array is a primitive with working generic methods"
|
|
84
86
|
a := Array<Str>().push("x").push("y")
|
|
85
87
|
assert a.length() == 2
|
|
86
|
-
assert a.
|
|
88
|
+
assert a.at(1) == "y"
|
|
87
89
|
b := Array.filled(3, 7)
|
|
88
90
|
assert b.at(2) == 7
|
|
89
91
|
|
|
@@ -92,33 +94,38 @@ test "Array<Int> holds a million elements unboxed"
|
|
|
92
94
|
for i := range 1000000
|
|
93
95
|
a.set(i, i * 2)
|
|
94
96
|
assert a.length() == 1000000
|
|
95
|
-
assert a.
|
|
97
|
+
assert a.at(999999) == 1999998
|
|
96
|
-
assert a.
|
|
98
|
+
assert a.at(0) == 0
|
|
97
99
|
|
|
98
|
-
test "Array<Byte> is packed bytes:
|
|
100
|
+
test "Array<Byte> is packed bytes: at, set, push, resize, filled"
|
|
99
101
|
a := Array.filled(3, Byte(7))
|
|
100
102
|
assert a.length() == 3
|
|
101
103
|
a.set(1, Byte(200))
|
|
102
|
-
assert a.
|
|
104
|
+
assert a.at(1).toInt() == 200
|
|
103
|
-
assert a.
|
|
105
|
+
assert a.at(0).toInt() == 7
|
|
104
106
|
b := a.push(Byte(255)).resize(6)
|
|
105
107
|
assert b.length() == 6
|
|
106
|
-
assert b.
|
|
108
|
+
assert b.at(3).toInt() == 255
|
|
107
|
-
assert b.
|
|
109
|
+
assert b.at(5).toInt() == 0
|
|
108
110
|
|
|
109
111
|
test "Array.copy and Array.equal over scalar arrays"
|
|
110
112
|
a := Array.filled(5, 1)
|
|
111
113
|
b := Array.filled(5, 2)
|
|
112
114
|
Array.copy(b, 1, a, 0, 2)
|
|
113
|
-
assert b.
|
|
115
|
+
assert b.at(0) == 2 && b.at(1) == 1 && b.at(2) == 1 && b.at(3) == 2
|
|
114
116
|
assert Array.equal(a, 0, b, 1, 2)
|
|
115
117
|
assert !Array.equal(a, 0, b, 0, 2)
|
|
116
118
|
assert Array.equal(a, 0, b, 0, 0)
|
|
117
119
|
Array.copy(a, 1, a, 0, 4)
|
|
118
|
-
assert a.
|
|
120
|
+
assert a.at(4) == 1
|
|
119
121
|
f := Array.filled(3, 1.5)
|
|
120
122
|
assert Array.equal(f, 0, Array.filled(3, 1.5), 0, 3)
|
|
121
123
|
x := Array.filled(4, Byte(9))
|
|
122
124
|
y := Array.filled(4, Byte(9))
|
|
123
125
|
y.set(3, Byte(8))
|
|
124
126
|
assert Array.equal(x, 0, y, 0, 3) && !Array.equal(x, 0, y, 0, 4)
|
|
127
|
+
|
|
128
|
+
test "Array get is an Option, at the element"
|
|
129
|
+
a := Array.filled(3, 4)
|
|
130
|
+
assert a.get(2)! == 4 && a.get(3).isNone() && a.get(-1).isNone()
|
|
131
|
+
assert a.at(0) == 4
|
std/Decimal.plum
CHANGED
|
@@ -115,7 +115,7 @@ struct Decimal(digits: Str, exp: Int, neg: Bool) =
|
|
|
115
115
|
start := if f >= 1000000000 then 2 else 1
|
|
116
116
|
used := if e >= 0 then decMulPow(limbs, start, e, 29, 1 << 29, 2) else decMulPow(limbs, start, 0 - e, 12, 244140625, 5)
|
|
117
117
|
out := Buffer()
|
|
118
|
-
out.write(Int.intToStr(limbs.
|
|
118
|
+
out.write(Int.intToStr(limbs.at(used - 1)))
|
|
119
119
|
decWrite(limbs, used - 2, out)
|
|
120
120
|
if e >= 0 then trimmed(out.toStr(), 0, x < 0.0) else Decimal(digits: out.toStr(), exp: e, neg: x < 0.0)
|
|
121
121
|
|
|
@@ -365,7 +365,7 @@ struct Decimal(digits: Str, exp: Int, neg: Bool) =
|
|
|
365
365
|
# limbs[i..used) times f (at most 2^29) plus `carry`; returns the new used count.
|
|
366
366
|
fun decMul(limbs: Array<Int>, i: Int, used: Int, f: Int, carry: Int) -> Int =
|
|
367
367
|
if i < used
|
|
368
|
-
p := limbs.
|
|
368
|
+
p := limbs.at(i) * f + carry
|
|
369
369
|
q := p / 1000000000
|
|
370
370
|
limbs.set(i, p - q * 1000000000)
|
|
371
371
|
decMul(limbs, i + 1, used, f, q)
|
|
@@ -378,7 +378,7 @@ struct Decimal(digits: Str, exp: Int, neg: Bool) =
|
|
|
378
378
|
# Limbs i down to 0, nine digits each.
|
|
379
379
|
fun decWrite(limbs: Array<Int>, i: Int, out: Buffer) -> Unit =
|
|
380
380
|
if i >= 0
|
|
381
|
-
out.write(Int.fixedFracDigits(limbs.
|
|
381
|
+
out.write(Int.fixedFracDigits(limbs.at(i), 100000000))
|
|
382
382
|
decWrite(limbs, i - 1, out)
|
|
383
383
|
|
|
384
384
|
# ---- big integers ----
|
std/Int.plum
CHANGED
|
@@ -288,16 +288,16 @@ test "range fold, each, find, repeatUntil run a million iterations"
|
|
|
288
288
|
assert 0.until(1000000).find(|x| x == 999999).unwrapOr(-1) == 999999
|
|
289
289
|
calls := Array.filled(1, 0)
|
|
290
290
|
0.until(1000000).each(|x|
|
|
291
|
-
calls.set(0, calls.
|
|
291
|
+
calls.set(0, calls.at(0) + 1)
|
|
292
292
|
)
|
|
293
|
-
assert calls.
|
|
293
|
+
assert calls.at(0) == 1000000
|
|
294
294
|
assert repeatUntil(0, |n| n >= 1000000, |n| n + 1) == 1000000
|
|
295
295
|
|
|
296
296
|
test "range find exits early"
|
|
297
297
|
calls := Array.filled(1, 0)
|
|
298
298
|
r := 0.until(1000000).find(|x|
|
|
299
|
-
calls.set(0, calls.
|
|
299
|
+
calls.set(0, calls.at(0) + 1)
|
|
300
300
|
x == 3
|
|
301
301
|
)
|
|
302
302
|
assert r.unwrapOr(-1) == 3
|
|
303
|
-
assert calls.
|
|
303
|
+
assert calls.at(0) == 4
|
std/Slice.plum
CHANGED
|
@@ -30,14 +30,14 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
30
30
|
if i < 0 || i >= self.size
|
|
31
31
|
None
|
|
32
32
|
else
|
|
33
|
-
Some(self.data.
|
|
33
|
+
Some(self.data.at(self.start + i))
|
|
34
34
|
|
|
35
35
|
# sets the element at i'th index of the list, returning the old value (or None if i is out of bounds)
|
|
36
36
|
fun set(self, i: Int, v: T) -> Option<T> =
|
|
37
37
|
if i < 0 || i >= self.size
|
|
38
38
|
None
|
|
39
39
|
else
|
|
40
|
-
old := self.data.
|
|
40
|
+
old := self.data.at(self.start + i)
|
|
41
41
|
self.data.set(self.start + i, v)
|
|
42
42
|
Some(old)
|
|
43
43
|
|
|
@@ -45,11 +45,11 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
45
45
|
# and the length when i is out of range: a view never reads its parent's slots, and a
|
|
46
46
|
# popped slot is never read back.
|
|
47
47
|
fun at(self, i: Int) -> T =
|
|
48
|
-
if i < 0 || i >= self.size then outOfRange("Slice.at", i, self.size) else self.data.
|
|
48
|
+
if i < 0 || i >= self.size then outOfRange("Slice.at", i, self.size) else self.data.at(self.start + i)
|
|
49
49
|
|
|
50
50
|
# `at` without the range check, for std's own loops whose index is proven in range.
|
|
51
51
|
fun atUnchecked(self, i: Int) -> T =
|
|
52
|
-
self.data.
|
|
52
|
+
self.data.at(self.start + i)
|
|
53
53
|
|
|
54
54
|
fun isEmpty(self) -> Bool =
|
|
55
55
|
self.size == 0
|
|
@@ -72,13 +72,13 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
72
72
|
|
|
73
73
|
# The first element for which `keep` holds, or None. Stops at the first hit.
|
|
74
74
|
fun find(self, keep: fn(T) -> Bool) -> Option<T> =
|
|
75
|
-
self.indexWhere(keep, 0).map(|i| self.data.
|
|
75
|
+
self.indexWhere(keep, 0).map(|i| self.data.at(self.start + i))
|
|
76
76
|
|
|
77
77
|
# The index of the first element at or after `i` for which `keep` holds, or None.
|
|
78
78
|
fun indexWhere(self, keep: fn(T) -> Bool, i: Int) -> Option<Int> =
|
|
79
79
|
if i >= self.size
|
|
80
80
|
None
|
|
81
|
-
else if keep(self.data.
|
|
81
|
+
else if keep(self.data.at(self.start + i))
|
|
82
82
|
Some(i)
|
|
83
83
|
else
|
|
84
84
|
self.indexWhere(keep, i + 1)
|
|
@@ -94,13 +94,13 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
94
94
|
# Rewrites every slot with `f(old)` and returns the same list (no new list).
|
|
95
95
|
fun mapInPlace(self, f: fn(T) -> T) -> Slice<T> =
|
|
96
96
|
for i := range self.size
|
|
97
|
-
self.data.set(self.start + i, f(self.data.
|
|
97
|
+
self.data.set(self.start + i, f(self.data.at(self.start + i)))
|
|
98
98
|
self
|
|
99
99
|
|
|
100
100
|
# Moves the element at index i out (i must be in range); pair it with `putAt`
|
|
101
101
|
# to move an owned element back. The slot keeps a stale reference until `putAt`.
|
|
102
102
|
fun takeAt(self, i: Int) -> T =
|
|
103
|
-
self.data.
|
|
103
|
+
self.data.at(self.start + i)
|
|
104
104
|
|
|
105
105
|
# Writes `v` into slot i (i must be in range).
|
|
106
106
|
fun putAt(self, i: Int, v: T) =
|
|
@@ -123,7 +123,7 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
123
123
|
fun sameFrom(self, other: Slice<T>, i: Int) -> Bool =
|
|
124
124
|
if i >= self.size
|
|
125
125
|
true
|
|
126
|
-
else if self.data.
|
|
126
|
+
else if self.data.at(self.start + i) != other.data.at(other.start + i)
|
|
127
127
|
false
|
|
128
128
|
else
|
|
129
129
|
self.sameFrom(other, i + 1)
|
|
@@ -143,7 +143,7 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
143
143
|
else
|
|
144
144
|
fresh := Array<T>().resize(n)
|
|
145
145
|
for i := range self.size
|
|
146
|
-
fresh.set(i, self.data.
|
|
146
|
+
fresh.set(i, self.data.at(self.start + i))
|
|
147
147
|
self.data = fresh
|
|
148
148
|
self.start = 0
|
|
149
149
|
self.cap = n
|
|
@@ -167,13 +167,13 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
167
167
|
None
|
|
168
168
|
else
|
|
169
169
|
self.size = self.size - 1
|
|
170
|
-
Some(self.data.
|
|
170
|
+
Some(self.data.at(self.start + self.size))
|
|
171
171
|
|
|
172
172
|
# removes the element at i'th index of the list (out of range is a no-op)
|
|
173
173
|
fun removeAt(self, i: Int) =
|
|
174
174
|
if i >= 0 && i < self.size
|
|
175
175
|
for j := range i.until(self.size - 1)
|
|
176
|
-
self.data.set(self.start + j, self.data.
|
|
176
|
+
self.data.set(self.start + j, self.data.at(self.start + j + 1))
|
|
177
177
|
self.size = self.size - 1
|
|
178
178
|
|
|
179
179
|
# removes the first element equal to v from list
|
|
@@ -188,7 +188,7 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
188
188
|
fun indexFrom(self, v: T, i: Int) -> Option<Int> =
|
|
189
189
|
if i >= self.size
|
|
190
190
|
None
|
|
191
|
-
else if self.data.
|
|
191
|
+
else if self.data.at(self.start + i) == v
|
|
192
192
|
Some(i)
|
|
193
193
|
else
|
|
194
194
|
self.indexFrom(v, i + 1)
|
|
@@ -205,8 +205,8 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
205
205
|
# Swaps `i` and `j`, then the pair inside them, until the indexes meet.
|
|
206
206
|
fun swapInwards(self, i: Int, j: Int) -> Unit =
|
|
207
207
|
if i < j
|
|
208
|
-
tmp := self.data.
|
|
208
|
+
tmp := self.data.at(self.start + i)
|
|
209
|
-
self.data.set(self.start + i, self.data.
|
|
209
|
+
self.data.set(self.start + i, self.data.at(self.start + j))
|
|
210
210
|
self.data.set(self.start + j, tmp)
|
|
211
211
|
self.swapInwards(i + 1, j - 1)
|
|
212
212
|
|
|
@@ -228,7 +228,7 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
228
228
|
|
|
229
229
|
# Returns the first element equal to `search`, or None.
|
|
230
230
|
fun findValue(self, search: T) -> Option<T> =
|
|
231
|
-
self.indexFrom(search, 0).map(|i| self.data.
|
|
231
|
+
self.indexFrom(search, 0).map(|i| self.data.at(self.start + i))
|
|
232
232
|
|
|
233
233
|
fun contains(self, v: T) -> Bool =
|
|
234
234
|
self.indexFrom(v, 0).isSome()
|
|
@@ -238,14 +238,14 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
238
238
|
if self.size == 0
|
|
239
239
|
None
|
|
240
240
|
else
|
|
241
|
-
Some(self.data.
|
|
241
|
+
Some(self.data.at(self.start + 0))
|
|
242
242
|
|
|
243
243
|
# returns the last element in the list
|
|
244
244
|
fun last(self) -> Option<T> =
|
|
245
245
|
if self.size == 0
|
|
246
246
|
None
|
|
247
247
|
else
|
|
248
|
-
Some(self.data.
|
|
248
|
+
Some(self.data.at(self.start + self.size - 1))
|
|
249
249
|
|
|
250
250
|
# Returns a new list of the elements at index `[start, end)`, clamped into
|
|
251
251
|
# range (a `start`/`end` outside `[0, length]` is clamped, not an error).
|
|
@@ -254,7 +254,7 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
254
254
|
s := if start < 0 then 0 else start
|
|
255
255
|
e := if end > self.size then self.size else end
|
|
256
256
|
for i := range s.until(e)
|
|
257
|
-
result.push(self.data.
|
|
257
|
+
result.push(self.data.at(self.start + i))
|
|
258
258
|
result
|
|
259
259
|
|
|
260
260
|
# Every element AFTER the first `n` (a copy; `xs.skip(n)` in a `for` is the lazy form).
|
|
@@ -268,7 +268,7 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
268
268
|
None
|
|
269
269
|
else
|
|
270
270
|
d := rng.nextIntBelow(self.size)
|
|
271
|
-
Some(Rolled(value: self.data.
|
|
271
|
+
Some(Rolled(value: self.data.at(self.start + d.value), rng: d.rng))
|
|
272
272
|
|
|
273
273
|
# Returns a new list with `self`'s elements in random order (Fisher-Yates) and the
|
|
274
274
|
# advanced generator.
|
|
@@ -277,8 +277,8 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
277
277
|
final := {result.size - 1}.downTo(1).fold(rng, |gen, i|
|
|
278
278
|
d := gen.nextIntBelow(i + 1)
|
|
279
279
|
j := d.value
|
|
280
|
-
vi := result.data.
|
|
280
|
+
vi := result.data.at(result.start + i)
|
|
281
|
-
result.data.set(result.start + i, result.data.
|
|
281
|
+
result.data.set(result.start + i, result.data.at(result.start + j))
|
|
282
282
|
result.data.set(result.start + j, vi)
|
|
283
283
|
d.rng
|
|
284
284
|
)
|
|
@@ -297,7 +297,7 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
|
|
|
297
297
|
for i := range self.size
|
|
298
298
|
if i > 0
|
|
299
299
|
res.write(sep)
|
|
300
|
-
res.write(self.data.
|
|
300
|
+
res.write(self.data.at(self.start + i).toStr())
|
|
301
301
|
res.toStr()
|
|
302
302
|
|
|
303
303
|
fun toStr(self) -> Str =
|
|
@@ -312,21 +312,21 @@ fun outOfRange<T>(what: Str, i: Int, n: Int) -> T =
|
|
|
312
312
|
# closure of its own, which would capture it).
|
|
313
313
|
fun eachFrom<T>(xs: Slice<T>, i: Int, f: fn(T) -> Unit) -> Unit =
|
|
314
314
|
if i < xs.size
|
|
315
|
-
f(xs.data.
|
|
315
|
+
f(xs.data.at(xs.start + i))
|
|
316
316
|
eachFrom(xs, i + 1, f)
|
|
317
317
|
|
|
318
318
|
fun mapFrom<T, B>(xs: Slice<T>, i: Int, f: fn(T) -> B, out: Slice<B>) -> Slice<B> =
|
|
319
319
|
if i >= xs.size
|
|
320
320
|
out
|
|
321
321
|
else
|
|
322
|
-
out.push(f(xs.data.
|
|
322
|
+
out.push(f(xs.data.at(xs.start + i)))
|
|
323
323
|
mapFrom(xs, i + 1, f, out)
|
|
324
324
|
|
|
325
325
|
fun filterFrom<T>(xs: Slice<T>, i: Int, keep: fn(T) -> Bool, out: Slice<T>) -> Slice<T> =
|
|
326
326
|
if i >= xs.size
|
|
327
327
|
out
|
|
328
328
|
else
|
|
329
|
-
x := xs.data.
|
|
329
|
+
x := xs.data.at(xs.start + i)
|
|
330
330
|
if keep(x)
|
|
331
331
|
out.push(x)
|
|
332
332
|
filterFrom(xs, i + 1, keep, out)
|
|
@@ -334,7 +334,7 @@ fun filterFrom<T>(xs: Slice<T>, i: Int, keep: fn(T) -> Bool, out: Slice<T>) -> S
|
|
|
334
334
|
fun allFrom<T>(xs: Slice<T>, i: Int, keep: fn(T) -> Bool) -> Bool =
|
|
335
335
|
if i >= xs.size
|
|
336
336
|
true
|
|
337
|
-
else if !keep(xs.data.
|
|
337
|
+
else if !keep(xs.data.at(xs.start + i))
|
|
338
338
|
false
|
|
339
339
|
else
|
|
340
340
|
allFrom(xs, i + 1, keep)
|
|
@@ -344,7 +344,7 @@ fun foldFrom<T, A>(xs: Slice<T>, i: Int, acc: A, f: fn(A, T) -> A) -> A =
|
|
|
344
344
|
if i >= xs.size
|
|
345
345
|
acc
|
|
346
346
|
else
|
|
347
|
-
foldFrom(xs, i + 1, f(acc, xs.data.
|
|
347
|
+
foldFrom(xs, i + 1, f(acc, xs.data.at(xs.start + i)), f)
|
|
348
348
|
|
|
349
349
|
# ---- sort's merge sort, over the backing array of a fresh copy ----
|
|
350
350
|
|
|
@@ -361,14 +361,14 @@ fun sortRuns<T>(a: Array<T>, lo: Int, n: Int, before: fn(T, T) -> Bool) -> Unit
|
|
|
361
361
|
# Insertion sorts `a[lo..hi)`, given that `a[lo..i)` is sorted.
|
|
362
362
|
fun insertRun<T>(a: Array<T>, lo: Int, i: Int, hi: Int, before: fn(T, T) -> Bool) -> Unit =
|
|
363
363
|
if i < hi
|
|
364
|
-
insertDown(a, lo, a.
|
|
364
|
+
insertDown(a, lo, a.at(i), i - 1, before)
|
|
365
365
|
insertRun(a, lo, i + 1, hi, before)
|
|
366
366
|
|
|
367
367
|
# Shifts the elements of `a[lo..j]` that `x` belongs before one slot up, then puts `x` in
|
|
368
368
|
# the gap. Only a strict `before` moves an element, so equal ones keep their order.
|
|
369
369
|
fun insertDown<T>(a: Array<T>, lo: Int, x: T, j: Int, before: fn(T, T) -> Bool) -> Unit =
|
|
370
|
-
if j >= lo && before(x, a.
|
|
370
|
+
if j >= lo && before(x, a.at(j))
|
|
371
|
-
a.set(j + 1, a.
|
|
371
|
+
a.set(j + 1, a.at(j))
|
|
372
372
|
insertDown(a, lo, x, j - 1, before)
|
|
373
373
|
else
|
|
374
374
|
a.set(j + 1, x)
|
|
@@ -396,11 +396,11 @@ fun mergePass<T>(src: Array<T>, dst: Array<T>, lo: Int, n: Int, width: Int, befo
|
|
|
396
396
|
# element, which keeps the sort stable.
|
|
397
397
|
fun mergeRun<T>(src: Array<T>, dst: Array<T>, i: Int, mid: Int, j: Int, hi: Int, k: Int, before: fn(T, T) -> Bool) -> Unit =
|
|
398
398
|
if k < hi
|
|
399
|
-
if i < mid && {j >= hi || !before(src.
|
|
399
|
+
if i < mid && {j >= hi || !before(src.at(j), src.at(i))}
|
|
400
|
-
dst.set(k, src.
|
|
400
|
+
dst.set(k, src.at(i))
|
|
401
401
|
mergeRun(src, dst, i + 1, mid, j, hi, k + 1, before)
|
|
402
402
|
else
|
|
403
|
-
dst.set(k, src.
|
|
403
|
+
dst.set(k, src.at(j))
|
|
404
404
|
mergeRun(src, dst, i, mid, j + 1, hi, k + 1, before)
|
|
405
405
|
|
|
406
406
|
# ---- regression tests ----
|
std/Str.plum
CHANGED
|
@@ -26,11 +26,11 @@ struct Str(data: Array<Byte>, start: Int, len: Int) =
|
|
|
26
26
|
# The raw byte value (0-255) at index `i`. Crashes with the index and the length when
|
|
27
27
|
# `i` is out of range (a substring never reads its source's bytes outside it).
|
|
28
28
|
fun byteAt(self, i: Int) -> Int =
|
|
29
|
-
if i < 0 || i >= self.len then slice.outOfRange("Str.byteAt", i, self.len) else self.data.
|
|
29
|
+
if i < 0 || i >= self.len then slice.outOfRange("Str.byteAt", i, self.len) else self.data.at(self.start + i).toInt()
|
|
30
30
|
|
|
31
31
|
# `byteAt` without the range check, for std's own loops whose index is proven in range.
|
|
32
32
|
fun byteAtUnchecked(self, i: Int) -> Int =
|
|
33
|
-
self.data.
|
|
33
|
+
self.data.at(self.start + i).toInt()
|
|
34
34
|
|
|
35
35
|
# A copy that owns exactly its own bytes (no longer shares a larger source).
|
|
36
36
|
fun clone(self) -> Str =
|
|
@@ -50,10 +50,14 @@ struct Str(data: Array<Byte>, start: Int, len: Int) =
|
|
|
50
50
|
else
|
|
51
51
|
hashFrom(s, i + 1, {h ^ s.byteAtUnchecked(i)} * 0x100000001b3)
|
|
52
52
|
|
|
53
|
-
# The one-byte substring at byte index `i`
|
|
53
|
+
# The one-byte substring at byte index `i`. Crashes with the index and the length out of
|
|
54
|
-
# a whole character use `runeAt`.
|
|
54
|
+
# range. For a whole character use `runeAt`.
|
|
55
|
-
fun
|
|
55
|
+
fun at(self, i: Int) -> Str =
|
|
56
|
+
if i < 0 || i >= self.len then slice.outOfRange("Str.at", i, self.len) else byteToStr(self.byteAtUnchecked(i))
|
|
57
|
+
|
|
58
|
+
# The one-byte substring at byte index `i`, or None out of range.
|
|
59
|
+
fun get(self, i: Int) -> Option<Str> =
|
|
56
|
-
byteToStr(self.
|
|
60
|
+
if i < 0 || i >= self.len then None else Some(byteToStr(self.byteAtUnchecked(i)))
|
|
57
61
|
|
|
58
62
|
# `Str` is a byte array (UTF-8 encoded), NOT a sequence of Unicode
|
|
59
63
|
# characters — `length`/`byteAt`/`get`/`sub`/`slice` all operate on raw
|
|
@@ -293,7 +297,7 @@ struct Str(data: Array<Byte>, start: Int, len: Int) =
|
|
|
293
297
|
if j >= s.length()
|
|
294
298
|
result
|
|
295
299
|
else
|
|
296
|
-
result.push(s.
|
|
300
|
+
result.push(s.at(j))
|
|
297
301
|
splitBytes(s, result, j + 1)
|
|
298
302
|
|
|
299
303
|
fun splitFrom(s: Str, sep: Str, limit: Int, result: Slice<Str>, start: Int, i: Int, count: Int) -> Slice<Str> =
|
|
@@ -348,7 +352,7 @@ struct Str(data: Array<Byte>, start: Int, len: Int) =
|
|
|
348
352
|
if self.length() == 0
|
|
349
353
|
self
|
|
350
354
|
else
|
|
351
|
-
"{self.
|
|
355
|
+
"{self.at(0).upperCase()}{self.sub(1, self.length()).toLower()}"
|
|
352
356
|
|
|
353
357
|
fun kebabCase(self) -> Str =
|
|
354
358
|
caseConvert(self, "-", 1)
|
|
@@ -360,7 +364,7 @@ struct Str(data: Array<Byte>, start: Int, len: Int) =
|
|
|
360
364
|
if self.length() == 0
|
|
361
365
|
self
|
|
362
366
|
else
|
|
363
|
-
"{self.
|
|
367
|
+
"{self.at(0).toLower()}{self.sub(1, self.length())}"
|
|
364
368
|
|
|
365
369
|
fun upperCase(self) -> Str =
|
|
366
370
|
mapCase(self, true)
|
|
@@ -369,7 +373,7 @@ struct Str(data: Array<Byte>, start: Int, len: Int) =
|
|
|
369
373
|
if self.length() == 0
|
|
370
374
|
self
|
|
371
375
|
else
|
|
372
|
-
"{self.
|
|
376
|
+
"{self.at(0).upperCase()}{self.sub(1, self.length())}"
|
|
373
377
|
|
|
374
378
|
fun startCase(self) -> Str =
|
|
375
379
|
caseConvert(self, " ", 4)
|
|
@@ -724,6 +728,11 @@ struct Str(data: Array<Byte>, start: Int, len: Int) =
|
|
|
724
728
|
# intrinsics). `typeName<Self>()` in a trait's default gives each implementer's own name.
|
|
725
729
|
fun typeName<T>() -> Str = @native
|
|
726
730
|
|
|
731
|
+
test "Str at is the one-byte string, get the same as an Option"
|
|
732
|
+
s := "abcdef".sub(1, 3)
|
|
733
|
+
assert s.at(0) == "b" && s.at(1) == "c"
|
|
734
|
+
assert s.get(1)! == "c" && s.get(2).isNone() && s.get(-1).isNone()
|
|
735
|
+
|
|
727
736
|
test "split divides on every occurrence of the separator"
|
|
728
737
|
parts := "a,b,c".split(",", 0)
|
|
729
738
|
assert parts.length() == 3
|
std/collections/BPlusTree.plum
CHANGED
|
@@ -599,12 +599,12 @@ fun bpRandomRun(order: Int, steps: Int, span: Int, seed: Int) -> Bool =
|
|
|
599
599
|
for i := range steps
|
|
600
600
|
k := run.roll() % span
|
|
601
601
|
if run.roll() % 3 == 0
|
|
602
|
-
if model.
|
|
602
|
+
if model.at(k) >= 0
|
|
603
603
|
run.count = run.count - 1
|
|
604
604
|
model.set(k, -1)
|
|
605
605
|
run.tree = run.tree.remove(k)
|
|
606
606
|
else
|
|
607
|
-
if model.
|
|
607
|
+
if model.at(k) < 0
|
|
608
608
|
run.count = run.count + 1
|
|
609
609
|
model.set(k, i)
|
|
610
610
|
run.tree = run.tree.insert(k, i)
|
|
@@ -615,7 +615,7 @@ fun bpRandomRun(order: Int, steps: Int, span: Int, seed: Int) -> Bool =
|
|
|
615
615
|
if !bpValid(run.tree)
|
|
616
616
|
run.ok = false
|
|
617
617
|
for k := range span
|
|
618
|
-
if run.tree.get(k).unwrapOr(-1) != model.
|
|
618
|
+
if run.tree.get(k).unwrapOr(-1) != model.at(k)
|
|
619
619
|
run.ok = false
|
|
620
620
|
run.ok
|
|
621
621
|
|
|
@@ -814,14 +814,14 @@ test "20,000 entries at the default order"
|
|
|
814
814
|
assert n > 19000
|
|
815
815
|
ks := t.keys().toArray()
|
|
816
816
|
for j := range 1.until(ks.length())
|
|
817
|
-
assert ks.
|
|
817
|
+
assert ks.at(j - 1) < ks.at(j)
|
|
818
818
|
for j := range ks.length()
|
|
819
819
|
if j % 2 == 0
|
|
820
|
-
run.tree = run.tree.remove(ks.
|
|
820
|
+
run.tree = run.tree.remove(ks.at(j))
|
|
821
821
|
half := run.tree
|
|
822
822
|
assert half.length() == n / 2
|
|
823
823
|
assert bpValid(half)
|
|
824
|
-
assert !half.contains(ks.
|
|
824
|
+
assert !half.contains(ks.at(0)) && half.contains(ks.at(1))
|
|
825
825
|
b: BPlusTree<Int, Int> := BPlusTree.fromSorted(bpSorted(50000), |a, b| a < b)
|
|
826
826
|
assert b.length() == 50000 && bpValid(b)
|
|
827
827
|
assert b.range(1000, 1100).length() == 50
|
std/collections/BTree.plum
CHANGED
|
@@ -619,12 +619,12 @@ test "pseudo-random inserts and removes keep every invariant (t = 2 and t = 3)"
|
|
|
619
619
|
run.x = btLcg(run.x)
|
|
620
620
|
if run.x % 3 == 0
|
|
621
621
|
run.tree = run.tree.remove(k)
|
|
622
|
-
if present.
|
|
622
|
+
if present.at(k)
|
|
623
623
|
run.count = run.count - 1
|
|
624
624
|
present.set(k, false)
|
|
625
625
|
else
|
|
626
626
|
run.tree = run.tree.insert(k, k + step)
|
|
627
|
-
if !present.
|
|
627
|
+
if !present.at(k)
|
|
628
628
|
run.count = run.count + 1
|
|
629
629
|
present.set(k, true)
|
|
630
630
|
value.set(k, k + step)
|
|
@@ -634,9 +634,9 @@ test "pseudo-random inserts and removes keep every invariant (t = 2 and t = 3)"
|
|
|
634
634
|
assert btValid(tree)
|
|
635
635
|
assert tree.length() == run.count
|
|
636
636
|
for k := range 500
|
|
637
|
-
assert tree.contains(k) == present.
|
|
637
|
+
assert tree.contains(k) == present.at(k)
|
|
638
|
-
if present.
|
|
638
|
+
if present.at(k)
|
|
639
|
-
assert tree.get(k)! == value.
|
|
639
|
+
assert tree.get(k)! == value.at(k)
|
|
640
640
|
assert btAscending(tree.keys())
|
|
641
641
|
|
|
642
642
|
test "10,000 ascending keys iterate in order, then drain to empty"
|
std/collections/Deque.plum
CHANGED
|
@@ -30,7 +30,7 @@ struct Deque<T>(mut buf: Array<T>, mut head: Int, mut size: Int) =
|
|
|
30
30
|
cap := self.buf.length()
|
|
31
31
|
nb := Array<T>().resize(cap * 2)
|
|
32
32
|
for i := range self.size
|
|
33
|
-
nb.set(i, self.buf.
|
|
33
|
+
nb.set(i, self.buf.at({self.head + i} % cap))
|
|
34
34
|
self.buf = nb
|
|
35
35
|
self.head = 0
|
|
36
36
|
|
|
@@ -51,7 +51,7 @@ struct Deque<T>(mut buf: Array<T>, mut head: Int, mut size: Int) =
|
|
|
51
51
|
if self.size == 0
|
|
52
52
|
None
|
|
53
53
|
else
|
|
54
|
-
v := self.buf.
|
|
54
|
+
v := self.buf.at(self.head)
|
|
55
55
|
self.head = {self.head + 1} % self.buf.length()
|
|
56
56
|
self.size = self.size - 1
|
|
57
57
|
Some(v)
|
|
@@ -62,19 +62,19 @@ struct Deque<T>(mut buf: Array<T>, mut head: Int, mut size: Int) =
|
|
|
62
62
|
None
|
|
63
63
|
else
|
|
64
64
|
self.size = self.size - 1
|
|
65
|
-
Some(self.buf.
|
|
65
|
+
Some(self.buf.at({self.head + self.size} % self.buf.length()))
|
|
66
66
|
|
|
67
67
|
# The `i`'th element from the front, or None if out of bounds.
|
|
68
68
|
fun get(self, i: Int) -> Option<T> =
|
|
69
69
|
if i < 0 || i >= self.size
|
|
70
70
|
None
|
|
71
71
|
else
|
|
72
|
-
Some(self.buf.
|
|
72
|
+
Some(self.buf.at({self.head + i} % self.buf.length()))
|
|
73
73
|
|
|
74
74
|
# The `i`'th element from the front (the `for x := range deque` protocol). Crashes with
|
|
75
75
|
# the index and the length when `i` is out of range.
|
|
76
76
|
fun at(self, i: Int) -> T =
|
|
77
|
-
if i < 0 || i >= self.size then slice.outOfRange("Deque.at", i, self.size) else self.buf.
|
|
77
|
+
if i < 0 || i >= self.size then slice.outOfRange("Deque.at", i, self.size) else self.buf.at({self.head + i} % self.buf.length())
|
|
78
78
|
|
|
79
79
|
fun clear(self) -> Unit =
|
|
80
80
|
self.head = 0
|
std/collections/Grid.plum
CHANGED
|
@@ -4,11 +4,12 @@ import std/Array
|
|
|
4
4
|
import std/Int
|
|
5
5
|
import std/Float
|
|
6
6
|
import std/Str
|
|
7
|
+
import std/Option
|
|
7
8
|
|
|
8
9
|
# A fixed-size 2D grid stored row-major in ONE flat `Array<T>` (so a
|
|
9
10
|
# `Grid<Int>`/`Grid<Float>`/`Grid<Bool>` is a single native unboxed wasm
|
|
10
11
|
# array). Cell `(x, y)` lives at `y * w + x`; `x` is the column in `[0, w)`,
|
|
11
|
-
# `y` the row in `[0, h)`. `
|
|
12
|
+
# `y` the row in `[0, h)`. `at`/`set` crash with the cell and the size when `(x, y)` is
|
|
12
13
|
# off the grid (an `x` past the row would otherwise read the next row's cell): use
|
|
13
14
|
# `inBounds` first when coordinates may stray off the map (neighbour scans, pathfinding).
|
|
14
15
|
struct Grid<T>(w: Int, h: Int, data: Array<T>) =
|
|
@@ -25,10 +26,15 @@ struct Grid<T>(w: Int, h: Int, data: Array<T>) =
|
|
|
25
26
|
fun inBounds(self, x: Int, y: Int) -> Bool =
|
|
26
27
|
x >= 0 && y >= 0 && x < self.w && y < self.h
|
|
27
28
|
|
|
29
|
+
# The cell `(x, y)`; crashes with the cell and the size off the grid.
|
|
28
|
-
fun
|
|
30
|
+
fun at(self, x: Int, y: Int) -> T =
|
|
29
31
|
if !self.inBounds(x, y)
|
|
30
|
-
self.offGrid("
|
|
32
|
+
self.offGrid("at", x, y)
|
|
31
|
-
self.data.
|
|
33
|
+
self.data.at(y * self.w + x)
|
|
34
|
+
|
|
35
|
+
# The cell `(x, y)`, or None off the grid.
|
|
36
|
+
fun get(self, x: Int, y: Int) -> Option<T> =
|
|
37
|
+
if self.inBounds(x, y) then Some(self.data.at(y * self.w + x)) else None
|
|
32
38
|
|
|
33
39
|
fun set(self, x: Int, y: Int, v: T) -> Unit =
|
|
34
40
|
if !self.inBounds(x, y)
|
|
@@ -45,19 +51,25 @@ test "Grid get/set address cells row-major and fill covers every cell"
|
|
|
45
51
|
assert g.h == 3
|
|
46
52
|
g.set(3, 2, 9)
|
|
47
53
|
g.set(0, 1, 5)
|
|
48
|
-
assert g.
|
|
54
|
+
assert g.at(3, 2) == 9
|
|
49
|
-
assert g.
|
|
55
|
+
assert g.at(0, 1) == 5
|
|
50
|
-
assert g.
|
|
56
|
+
assert g.at(1, 1) == 0
|
|
51
57
|
assert g.index(3, 2) == 11
|
|
52
|
-
assert g.data.
|
|
58
|
+
assert g.data.at(11) == 9
|
|
53
59
|
|
|
54
60
|
test "Grid inBounds rejects negative and too-large coordinates"
|
|
55
61
|
g := Grid.filled(2, 2, 1.5)
|
|
56
62
|
assert g.inBounds(1, 1)
|
|
57
63
|
assert g.inBounds(2, 0) == false
|
|
58
64
|
assert g.inBounds(0, -1) == false
|
|
59
|
-
assert g.
|
|
65
|
+
assert g.at(1, 1) == 1.5
|
|
66
|
+
|
|
67
|
+
test "Grid at and set crash off the grid, a column past the row included"
|
|
68
|
+
g := Grid.filled(4, 3, 0)
|
|
69
|
+
assert g.at(3, 0) == 0 && g.at(0, 2) == 0
|
|
60
70
|
|
|
61
|
-
test "Grid get
|
|
71
|
+
test "Grid get is an Option: None off the grid"
|
|
62
72
|
g := Grid.filled(4, 3, 0)
|
|
73
|
+
g.set(3, 2, 9)
|
|
63
|
-
assert g.get(3,
|
|
74
|
+
assert g.get(3, 2)! == 9 && g.get(0, 0)! == 0
|
|
75
|
+
assert g.get(4, 0).isNone() && g.get(0, -1).isNone() && g.get(0, 3).isNone()
|
std/collections/List.plum
CHANGED
|
@@ -31,8 +31,10 @@ enum List<T> =
|
|
|
31
31
|
Nil => None
|
|
32
32
|
Cons(h, t) => if i < 0 then None else if i == 0 then Some(h) else t.get(i - 1)
|
|
33
33
|
|
|
34
|
-
# The element at index i (O(i) per call). Crashes out of range.
|
|
34
|
+
# The element at index i (O(i) per call). Crashes with the index and the length out of range.
|
|
35
|
-
fun at(self, i: Int) -> T = self.get(i)
|
|
35
|
+
fun at(self, i: Int) -> T = match self.get(i)
|
|
36
|
+
Some(v) => v
|
|
37
|
+
None => slice.outOfRange("List.at", i, self.length())
|
|
36
38
|
|
|
37
39
|
fun map<B>(self, f: fn(T) -> B) -> List<B> = mapCells(self, f)
|
|
38
40
|
|
|
@@ -151,18 +153,18 @@ test "list fold, each, find: a million elements, find exits early"
|
|
|
151
153
|
assert xs.fold(0, |a, x| a + 1) == 1000000
|
|
152
154
|
calls := Array.filled(1, 0)
|
|
153
155
|
xs.each(|x|
|
|
154
|
-
calls.set(0, calls.
|
|
156
|
+
calls.set(0, calls.at(0) + 1)
|
|
155
157
|
)
|
|
156
|
-
assert calls.
|
|
158
|
+
assert calls.at(0) == 1000000
|
|
157
159
|
assert xs.find(|x| x == 1).unwrapOr(-1) == 1
|
|
158
160
|
assert xs.find(|x| x < 0).isNone()
|
|
159
161
|
hits := Array.filled(1, 0)
|
|
160
162
|
found := xs.find(|x|
|
|
161
|
-
hits.set(0, hits.
|
|
163
|
+
hits.set(0, hits.at(0) + 1)
|
|
162
164
|
x == 999998
|
|
163
165
|
)
|
|
164
166
|
assert found.unwrapOr(-1) == 999998
|
|
165
|
-
assert hits.
|
|
167
|
+
assert hits.at(0) == 3
|
|
166
168
|
|
|
167
169
|
test "join puts the separator between the elements, in order"
|
|
168
170
|
none: List<Str> := Nil
|
std/collections/Map.plum
CHANGED
|
@@ -265,19 +265,25 @@ enum Map<K, V> =
|
|
|
265
265
|
else
|
|
266
266
|
r.aboveFrom(k, best, orEqual)
|
|
267
267
|
|
|
268
|
+
# The entry with the `i`-th smallest key (from 0) (`elemAt`). Crashes with the index and
|
|
269
|
+
# the length out of range.
|
|
270
|
+
fun entryAt(self, i: Int) -> Pair<K, V> = match self.getEntryAt(i)
|
|
271
|
+
Some(e) => e
|
|
272
|
+
None => slice.outOfRange("Map.entryAt", i, self.length())
|
|
273
|
+
|
|
268
|
-
# The entry with the `i`-th smallest key (from 0), or None out of range
|
|
274
|
+
# The entry with the `i`-th smallest key (from 0), or None out of range.
|
|
269
|
-
fun
|
|
275
|
+
fun getEntryAt(self, i: Int) -> Option<Pair<K, V>> = match self
|
|
270
276
|
MapTip => None
|
|
271
277
|
MapBin(_, nk, nv, l, r) =>
|
|
272
278
|
sl := l.length()
|
|
273
279
|
if i < 0
|
|
274
280
|
None
|
|
275
281
|
else if i < sl
|
|
276
|
-
l.
|
|
282
|
+
l.getEntryAt(i)
|
|
277
283
|
else if i == sl
|
|
278
284
|
Some(Pair(first: nk, second: nv))
|
|
279
285
|
else
|
|
280
|
-
r.
|
|
286
|
+
r.getEntryAt(i - sl - 1)
|
|
281
287
|
|
|
282
288
|
# The position of `k` in key order (from 0), or None when absent (`lookupIndex`).
|
|
283
289
|
fun indexOf(self, k: K) -> Option<Int> = self.indexFrom(k, 0)
|
|
@@ -736,7 +742,7 @@ test "an empty map"
|
|
|
736
742
|
assert m.min().isNone() && m.max().isNone()
|
|
737
743
|
assert m.removeMin().isEmpty() && m.removeMax().isEmpty()
|
|
738
744
|
assert m.below(1).isNone() && m.atMost(1).isNone() && m.above(1).isNone() && m.atLeast(1).isNone()
|
|
739
|
-
assert m.
|
|
745
|
+
assert m.getEntryAt(0).isNone() && m.indexOf(1).isNone()
|
|
740
746
|
assert m.entries().length() == 0 && m.keys().length() == 0 && m.values().length() == 0
|
|
741
747
|
assert m.toStr() == "[]"
|
|
742
748
|
assert m.remove(1).isEmpty()
|
|
@@ -750,7 +756,7 @@ test "one entry"
|
|
|
750
756
|
m := Map.single(7, "seven")
|
|
751
757
|
assert m.length() == 1 && !m.isEmpty() && m.height() == 1
|
|
752
758
|
assert m.get(7)! == "seven" && m.get(8).isNone()
|
|
753
|
-
assert m.min()!.first == 7 && m.max()!.first == 7 && m.
|
|
759
|
+
assert m.min()!.first == 7 && m.max()!.first == 7 && m.getEntryAt(0)!.second == "seven"
|
|
754
760
|
assert m.toStr() == "[7 => seven]" && m == Map<Int, Str>().with(7, "seven")
|
|
755
761
|
assert m.remove(7).isEmpty() && m.removeMin().isEmpty() && m.removeMax().isEmpty()
|
|
756
762
|
assert m.rank(7) == 0 && m.rank(8) == 1 && m.range(7, 8) == m && m.range(8, 9).isEmpty()
|
|
@@ -758,7 +764,7 @@ test "one entry"
|
|
|
758
764
|
test "a key type's compare is the order: largest first"
|
|
759
765
|
m := [1, 5, 3, 9, 7].fold(Map<MapTestDesc, Int>(), |acc, n| acc.with(MapTestDesc(n: n), n * 10))
|
|
760
766
|
assert m.keys().map(|k| k.n).toStr() == "[9,7,5,3,1]"
|
|
761
|
-
assert m.min()!.first.n == 9 && m.max()!.first.n == 1 && m.
|
|
767
|
+
assert m.min()!.first.n == 9 && m.max()!.first.n == 1 && m.getEntryAt(1)!.second == 70
|
|
762
768
|
assert m.rank(MapTestDesc(n: 4)) == 3 && m.get(MapTestDesc(n: 3))! == 30
|
|
763
769
|
assert m.remove(MapTestDesc(n: 7)).keys().map(|k| k.n).toStr() == "[9,5,3,1]"
|
|
764
770
|
assert m.range(MapTestDesc(n: 7), MapTestDesc(n: 1)).keys().map(|k| k.n).toStr() == "[7,5,3]"
|
|
@@ -854,22 +860,23 @@ test "neighbours agree with a scan over pseudo-random maps"
|
|
|
854
860
|
|
|
855
861
|
test "entryAt and indexOf count positions in key order"
|
|
856
862
|
m := [30 => 3, 10 => 1, 50 => 5, 20 => 2, 40 => 4]
|
|
857
|
-
assert m.
|
|
863
|
+
assert m.getEntryAt(0)!.first == 10 && m.getEntryAt(2)!.second == 3 && m.getEntryAt(4)!.first == 50
|
|
864
|
+
assert m.entryAt(0).first == 10 && m.entryAt(4).first == 50
|
|
858
|
-
assert m.
|
|
865
|
+
assert m.getEntryAt(5).isNone() && m.getEntryAt(-1).isNone()
|
|
859
866
|
assert m.indexOf(10)! == 0 && m.indexOf(40)! == 3 && m.indexOf(35).isNone()
|
|
860
867
|
for i := range 5
|
|
861
|
-
assert m.indexOf(m.
|
|
868
|
+
assert m.indexOf(m.getEntryAt(i)!.first)! == i
|
|
862
869
|
|
|
863
870
|
test "rank counts the keys before k, present or not"
|
|
864
871
|
m := [10 => 1, 20 => 2, 30 => 3, 40 => 4, 50 => 5]
|
|
865
872
|
assert m.rank(10) == 0 && m.rank(30) == 2 && m.rank(50) == 4
|
|
866
873
|
assert m.rank(5) == 0 && m.rank(35) == 3 && m.rank(99) == 5
|
|
867
874
|
for i := range 5
|
|
868
|
-
assert m.rank(m.
|
|
875
|
+
assert m.rank(m.getEntryAt(i)!.first) == i
|
|
869
876
|
e: Map<Int, Int> := Map.empty()
|
|
870
877
|
assert e.rank(7) == 0
|
|
871
878
|
w := [MapTestWord(text: "pear") => 1, MapTestWord(text: "apple") => 2, MapTestWord(text: "zucchini") => 3, MapTestWord(text: "fig") => 4]
|
|
872
|
-
assert w.rank(MapTestWord(text: "kiwi")) == 1 && w.
|
|
879
|
+
assert w.rank(MapTestWord(text: "kiwi")) == 1 && w.getEntryAt(1)!.first.text == "pear"
|
|
873
880
|
big := mapRemoveFrom(mapRange(Map.empty(), 0, 10000), 0, 10000, 2)
|
|
874
881
|
assert big.rank(5001) == 2500 && big.rank(5000) == 2500 && big.rank(-1) == 0 && big.rank(10000) == 5000
|
|
875
882
|
|
std/collections/Set.plum
CHANGED
|
@@ -65,8 +65,12 @@ struct Set<T>(map: Map<T, Bool>) =
|
|
|
65
65
|
|
|
66
66
|
fun atLeast(self, v: T) -> Option<T> = self.map.atLeast(v).map(|e| e.first)
|
|
67
67
|
|
|
68
|
+
# The `i`-th smallest member (from 0). Crashes with the index and the length out of range.
|
|
69
|
+
fun at(self, i: Int) -> T =
|
|
70
|
+
if i < 0 || i >= self.length() then slice.outOfRange("Set.at", i, self.length()) else self.map.entryAt(i).first
|
|
71
|
+
|
|
68
72
|
# The `i`-th smallest member (from 0), or None out of range.
|
|
69
|
-
fun
|
|
73
|
+
fun get(self, i: Int) -> Option<T> = self.map.getEntryAt(i).map(|e| e.first)
|
|
70
74
|
|
|
71
75
|
# The position of `v` in ascending order (from 0), or None when it is not a member.
|
|
72
76
|
fun indexOf(self, v: T) -> Option<Int> = self.map.indexOf(v)
|
|
@@ -183,7 +187,8 @@ test "order: min, max, neighbours, at, split, removeMin, removeMax"
|
|
|
183
187
|
assert s.min()! == 10 && s.max()! == 40
|
|
184
188
|
assert s.removeMin().toStr() == "[20, 30, 40]" && s.removeMax().toStr() == "[10, 20, 30]"
|
|
185
189
|
assert s.below(30)! == 20 && s.atMost(30)! == 30 && s.above(30)! == 40 && s.atLeast(31)! == 40 && s.above(40).isNone()
|
|
190
|
+
assert s.get(1)! == 20 && s.get(4).isNone() && s.get(-1).isNone()
|
|
186
|
-
assert s.at(
|
|
191
|
+
assert s.at(0) == 10 && s.at(1) == 20
|
|
187
192
|
p := s.split(25)
|
|
188
193
|
assert p.first.toStr() == "[10, 20]" && p.second.toStr() == "[30, 40]"
|
|
189
194
|
|
std/game/SceneTree.plum
CHANGED
|
@@ -350,11 +350,11 @@ fun chainFrom<T>(ns: Slice<RoseTree<T>>, i: Int) -> RoseTree<T> =
|
|
|
350
350
|
|
|
351
351
|
fun bitSet(bits: Array<Int>, id: Int) =
|
|
352
352
|
w := id / 64
|
|
353
|
-
bits.set(w, bits.
|
|
353
|
+
bits.set(w, bits.at(w) | {1 << {id % 64}})
|
|
354
354
|
|
|
355
355
|
fun bitHas(bits: Array<Int>, id: Int) -> Bool =
|
|
356
356
|
w := id / 64
|
|
357
|
-
if id < 0 || w >= bits.length() then false else {{bits.
|
|
357
|
+
if id < 0 || w >= bits.length() then false else {{bits.at(w) >> {id % 64}} & 1} == 1
|
|
358
358
|
|
|
359
359
|
# `stepChain` for a tick with no `Kill` and no `Spawn` before the step: no batch to ask.
|
|
360
360
|
fun stepPlain<M>(t: RoseTree<Actor<M>>, ctx: Ctx<M>, dt: Float) -> RoseTree<Actor<M>> = match t
|
std/math/math.plum
CHANGED
|
@@ -296,7 +296,7 @@ fun limbBits(p: Array<Int>, lo: Int, w: Int) -> Int =
|
|
|
296
296
|
v & {{1 << w} - 1}
|
|
297
297
|
|
|
298
298
|
fun limbAt(p: Array<Int>, q: Int) -> Int =
|
|
299
|
-
if q < 13 then p.
|
|
299
|
+
if q < 13 then p.at(q) else 0
|
|
300
300
|
|
|
301
301
|
# The bits of 2/Pi, 24 at a time: chunk `j` is bits `24j + 1` to `24j + 24` after the point
|
|
302
302
|
# (fdlibm's `ipio2`). Fifty cover `Float.Max`.
|
tests/fbip_probes/array_set.plum
CHANGED
|
@@ -12,7 +12,7 @@ fun run(n: Int) -> Int =
|
|
|
12
12
|
a := Array<Int>().resize(1000)
|
|
13
13
|
for i := range n
|
|
14
14
|
a.set(i % 1000, i)
|
|
15
|
-
0.until(1000).fold(0, |total, j| total + a.
|
|
15
|
+
0.until(1000).fold(0, |total, j| total + a.at(j))
|
|
16
16
|
|
|
17
17
|
fun main(io: Io) =
|
|
18
18
|
t0 := Time.now(io).toMillis()
|
tests/std/collections.plum
CHANGED
|
@@ -26,10 +26,10 @@ test "List.toArray of 200000 elements is sized once and keeps the order"
|
|
|
26
26
|
xs := 1.to(200000).fold(nil, |acc, i| Cons(head: i, tail: acc))
|
|
27
27
|
a := xs.toArray()
|
|
28
28
|
assert a.length() == 200000
|
|
29
|
-
assert a.
|
|
29
|
+
assert a.at(0) == 200000 && a.at(199999) == 1
|
|
30
30
|
e: List<Str> := Nil
|
|
31
31
|
assert e.toArray().length() == 0
|
|
32
|
-
assert ["a", "b"].toArray().
|
|
32
|
+
assert ["a", "b"].toArray().at(1) == "b"
|
|
33
33
|
|
|
34
34
|
test "sort: 100000 reversed, sorted, equal and empty inputs"
|
|
35
35
|
big := countdown(100000).sort(|a, b| a < b)
|
|
@@ -88,10 +88,10 @@ test "find stops at the first hit"
|
|
|
88
88
|
xs := countdown(1000)
|
|
89
89
|
calls := Array.filled(1, 0)
|
|
90
90
|
found := xs.find(|x|
|
|
91
|
-
calls.set(0, calls.
|
|
91
|
+
calls.set(0, calls.at(0) + 1)
|
|
92
92
|
x == 998
|
|
93
93
|
)
|
|
94
|
-
assert found! == 998 && calls.
|
|
94
|
+
assert found! == 998 && calls.at(0) == 3
|
|
95
95
|
|
|
96
96
|
test "groupBy keeps each group in order and the groups in key order"
|
|
97
97
|
words := ["bb", "a", "cc", "ddd", "e"].toSlice()
|
|
@@ -121,7 +121,7 @@ test "Heap.by and Heap.byKey"
|
|
|
121
121
|
prev := Array.filled(1, -1)
|
|
122
122
|
for _ := range 500
|
|
123
123
|
v := h.pop()!
|
|
124
|
-
assert v >= prev.
|
|
124
|
+
assert v >= prev.at(0)
|
|
125
125
|
prev.set(0, v)
|
|
126
126
|
assert h.isEmpty() && h.pop().isNone()
|
|
127
127
|
r: Heap<Rec> := Heap.byKey(|r| r.k)
|
tests/std/map_model.plum
CHANGED
|
@@ -102,7 +102,7 @@ test "every operation keeps the tree valid and agrees with the model; inputs sta
|
|
|
102
102
|
st.bad = st.bad + 1
|
|
103
103
|
st.log.push("rank")
|
|
104
104
|
i := draw(st, n1 + 3) - 1
|
|
105
|
-
e := a.
|
|
105
|
+
e := a.getEntryAt(i)
|
|
106
106
|
okE := if i < 0 || i >= ks.length() then e.isNone() else e.isSome() && e!.first == ks.at(i)
|
|
107
107
|
if !okE
|
|
108
108
|
st.bad = st.bad + 1
|