diff --git a/quest/m3/README.md b/quest/m3/README.md index 8f5db3119..f7c4e5ef2 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -27,6 +27,8 @@ generic std gap is planned here even when moq never calls it. - [An inclusive range folded through an adaptor](/quest/m3/ts-range-fold.md) - a `RangeInclusive` folded through `map`, `filter`, or `rev` ends in core's state, and `by_ref` of one type-checks - [Binding gaps](/quest/m3/ts-bind-gaps.md) - bound types as keys, unit returns checked, renamed dependencies - [Drop order in std's folds and iterators](/quest/m3/ts-drop-order.md) - the values that drop still refused in std's folds, zips, flattens, and collects drop as std's do -- [Slice windows and chunks, Vec drain, and the order of byte arrays](/quest/m3/ts-slice-gaps.md) - `windows`, `chunks`, `Vec::drain`, and byte arrays' order translate +- [Byte arrays compared for equality and hashed](/quest/m3/ts-byte-keys.md) - `==` of byte arrays, and byte arrays, slices, and vectors as hash keys, translate +- [Ranges of Bounds](/quest/m3/ts-bound-ranges.md) - drains and B-tree ranges of a `(Bound, Bound)` translate +- [The rest of a slice's chunks](/quest/m3/ts-slice-chunks.md) - `chunks_exact`, `rchunks`, and the mutable chunks translate - [Iterator consumers over items whose None is rt.None](/quest/m3/ts-option-items.md) - `nth`, `last`, and `find` of an iterator of `Option` keep `None` apart from `Some(None)` - [Port the workflow guard to kixelated/quest](/quest/m3/quest-workflow-guard.md) - quest's environment guard parses YAML as this repository's does diff --git a/quest/m3/ts-bound-ranges.md b/quest/m3/ts-bound-ranges.md new file mode 100644 index 000000000..0a5a506bf --- /dev/null +++ b/quest/m3/ts-bound-ranges.md @@ -0,0 +1,17 @@ +# [XS] Ranges of Bounds + +## Goal + +rust2-ts translates `Vec::drain`, `VecDeque::drain`, and a B-tree's `range` and +`range_mut` of a `(Bound, Bound)`, an excluded start included, matching std's +items and panics. Proven by differential tests against native Rust. + +## Plan + +Each refuses with a span since [#259](https://github.com/moq-dev/rust2/pull/259): the +runtime's `bounds` reads std's range types alone, and read a tuple as unbounded. Reading +the tuple's `rt.RangeBound`s there, and an excluded start where `slice::range` and the +B-tree's search take one, covers all four. A crate's own `RangeBounds` stays refused +until it has a consumer. rust2 aims to support all of std. + +Public API: the translator's output. diff --git a/quest/m3/ts-byte-keys.md b/quest/m3/ts-byte-keys.md new file mode 100644 index 000000000..352a302e5 --- /dev/null +++ b/quest/m3/ts-byte-keys.md @@ -0,0 +1,18 @@ +# [S] Byte arrays compared for equality and hashed + +## Goal + +rust2-ts translates `==` and `!=` of byte arrays such as `[u8; 2]`, and a `[u8; N]`, +`&[u8]`, or `Vec` as a hash key or inside a tuple, `Option`, or `Arc` that is one, +matching std's equality and finding each key as std's map does. Proven by differential +tests against native Rust. + +## Plan + +Each refuses with a span today: `==` of byte arrays as a call over a reference to an array +of bytes, and a key as "comparing" or "hashing `[u8; 2]` as a key". Their order translates +through `rt.cmpBytes`, which reads each byte form, a typed array, an `rt.ByteSlice`, or an +`rt.ByteVec`, at run time ([#259](https://github.com/moq-dev/rust2/pull/259)); equality and +hashing can take the same approach. rust2 aims to support all of std. + +Public API: the translator's output. diff --git a/quest/m3/ts-slice-chunks.md b/quest/m3/ts-slice-chunks.md new file mode 100644 index 000000000..899fe17bf --- /dev/null +++ b/quest/m3/ts-slice-chunks.md @@ -0,0 +1,18 @@ +# [S] The rest of a slice's chunks + +## Goal + +rust2-ts translates a slice's `chunks_exact`, `rchunks`, `rchunks_exact`, and their +`_mut` forms, and `chunks_mut`, matching std's parts, remainders, and panics, and writing +through a mutable chunk into the slice it came from. Proven by differential tests against +native Rust. + +## Plan + +Each refuses with a span today. `windows` and `chunks` map to `rt.PartsIter` in +`rt/iter.ts` ([#259](https://github.com/moq-dev/rust2/pull/259)), which the others can +extend. A mutable chunk of a slice that is not bytes is a JS array copied by `slice`, so +writes through it would be lost: it needs a view or a place, as `iter_mut` lends one. +rust2 aims to support all of std. + +Public API: the translator's output. diff --git a/quest/m3/ts-slice-gaps.md b/quest/m3/ts-slice-gaps.md deleted file mode 100644 index 044ada20c..000000000 --- a/quest/m3/ts-slice-gaps.md +++ /dev/null @@ -1,17 +0,0 @@ -# [S] Slice windows and chunks, Vec drain, and the order of byte arrays - -## Goal - -rust2-ts translates a slice's `windows` and `chunks`, `Vec::drain` of a range, and `<`, -`<=`, `>`, `>=`, and `cmp` of byte arrays such as `[u8; 2]`, matching std's iteration, -drop order of drained values, and comparison results. Proven by differential tests -against native Rust. - -## Plan - -Met by [#252](https://github.com/moq-dev/rust2/pull/252) on 2026-10-29: its ordering -fixtures and bench rewrote around each. rust2 aims to support all of std. Each refuses -with a span today; the byte-array comparison refuses because the mapping of a byte array -it is generic over would take the array, not a slice of it. - -Public API: the translator's output. diff --git a/quest/m3/ts-unsafe.md b/quest/m3/ts-unsafe.md index 76942a9d6..5e06953cd 100644 --- a/quest/m3/ts-unsafe.md +++ b/quest/m3/ts-unsafe.md @@ -51,5 +51,11 @@ none of its own `unsafe`. [#252](https://github.com/moq-dev/rust2/pull/252) mapped them to and that must track std's by hand. The lang fixture's `orders` differential case proves the translation still matches std's comparisons, pop order, and drops. +- `Vec::drain` translates from std's MIR, whose `Drain` reads its range out and moves the + tail back through raw pointers into the `Vec`'s storage, replacing `rt.vecDrain` and + `rt.byteVecDrain`, the runtime port that + [the slice gaps' PR](https://github.com/moq-dev/rust2/pull/259) mapped it to. The lang + fixture's `slices::drains` differential case proves the translation still matches std's + items, drops, and what a forgotten drain leaves. Public API: the translator's output. diff --git a/ts/README.md b/ts/README.md index e5f8abdf2..0afaa8f3e 100644 --- a/ts/README.md +++ b/ts/README.md @@ -247,8 +247,9 @@ A collection keeps Rust's key semantics. A hash map or set keeps a key that is a number, string, or boolean in a JS `Map`, which compares those as Rust's `Eq` does, and finds any other key, a 64-bit one past 2^53 included, through its translated `Hash` and `Eq`; a B-tree orders every key by its translated `Ord`. std's impls are the runtime's: an -`Option` orders `None` first, and an `Arc` compares, orders, and hashes as what it holds, -so a map of `Arc` finds a `&str`. A `&mut` to a value a map holds that JS copies, +`Option` orders `None` first, an `Arc` compares, orders, and hashes as what it holds, +so a map of `Arc` finds a `&str`, and byte arrays, slices, and vectors order by their +bytes and then their length. A `&mut` to a value a map holds that JS copies, such as a number, from `get_mut` or the entry API, is an `rt.Place` whose `v` reads and writes the map's slot. A hash map iterates in an order of the runtime's, mostly insertion order, which std leaves unspecified, and hashes a key @@ -274,7 +275,9 @@ drop it where std's do. So do iterators: one that owns its items, as a `Vec`'s ` map's `drain` does, drops those it still holds by `[Symbol.dispose]`, an adaptor drops what it skips or rejects, and a consumer that takes an iterator by value drops it: through each `rt.Iter`'s own `fold` where std's folds, which drops each adaptor's closure -as its fold ends, before what it wraps, as std's does. +as its fold ends, before what it wraps, as std's does. A `Vec`'s `drain` leaves the vector +what precedes its range until it drops, then drops what it still holds and moves the tail +back, so one never dropped, as `mem::forget` leaves it, leaks the rest, as std's does. A trait object of the crate's own trait, or a dependency's, behind `&`, `&mut`, `Box`, or `Arc`, is an object with a method for each function a call can dispatch to, its supertraits' included, named for @@ -543,11 +546,12 @@ they need. - A `BinaryHeap` is std's heap in an array, with std's sifts ported to the runtime: std's move elements through raw pointers into its `Vec`, which no body of std's lowers through, and the sifts decide which `PartialOrd` tests run and which of equal elements - leaves first. The sorts, `max` and `min`, the heap, and `is_sorted` take an integer's - tests as the runtime's `rt.lt`, `rt.le`, `rt.gt`, and `rt.ge` rather than through its - `partial_cmp`, `rt.cmpLt(rt.cmp)`: on `just ts bench`'s `order/` workloads that took - Firefox 0.8-0.86x the time on sorts and `max`/`min` and Chrome 0.66x on the heap, and - Chrome the same on the rest. + leaves first. `Vec::drain` is ported for the same reason: std's reads its range out + and moves the tail back through raw pointers. The sorts, `max` and `min`, the heap, + and `is_sorted` take an integer's tests as the runtime's `rt.lt`, `rt.le`, `rt.gt`, + and `rt.ge` rather than through its `partial_cmp`, `rt.cmpLt(rt.cmp)`: on `just ts + bench`'s `order/` workloads that took Firefox 0.8-0.86x the time on sorts and + `max`/`min` and Chrome 0.66x on the heap, and Chrome the same on the rest. - Iterators are the runtime's lazy classes rather than generators or ES iterator helpers: std's adaptors would lower from std's own bodies, whose slice iterators are raw pointers, ES helpers lack most of them diff --git a/ts/fixtures/lang/expected/core/cmp.ts b/ts/fixtures/lang/expected/core/cmp.ts index fdaca3a8e..3c63311f5 100644 --- a/ts/fixtures/lang/expected/core/cmp.ts +++ b/ts/fixtures/lang/expected/core/cmp.ts @@ -87,6 +87,10 @@ export function max$u8(v1: rt.u8, v2: rt.u8): rt.u8 { return rt.max(v1, v2); } +export function max$u8s(v1: Uint8Array, v2: Uint8Array): Uint8Array { + return rt.ordMax(v1, v2, rt.cmpLt(rt.cmpBytes)); +} + export function maxBy$Item_cmps_closure1(v1: Item.Item, v2: Item.Item, compare: (a0: Item.Item, a1: Item.Item) => rt.Ordering): Item.Item { let _0!: Item.Item; let _10: boolean = false; diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts index 8373765c1..6e1fe3097 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -30,6 +30,8 @@ import type * as Dir from "../shapes.Dir.ts"; import type * as Meters from "../shapes.Meters.ts"; import type * as Point from "../shapes.Point.ts"; import type * as shapes_Shape from "../shapes.Shape.ts"; +import { digest, digestWords } from "../slices.ts"; +import type * as slices_Item from "../slices.Item.ts"; import type * as Short from "../splits.Short.ts"; export function isSomeAnd$Option_u8_bools_closure0(self: rt.u8 | undefined, f: (a0: rt.u8) => boolean): boolean { @@ -242,6 +244,13 @@ export function map$Option_Hop_u64_u64_options_closure0(self: Hop.Hop | undefine return f(self); } +export function map$Option_Item_u8_drains_closure10(self: slices_Item.Item | undefined, f: (a0: slices_Item.Item) => rt.u8): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + export function map$Option_Named_Nameds_from_ref(self: Named.Named | undefined, _: (a0: Named.Named) => Named.Named[]): Named.Named[] | undefined { if (self === undefined) { return undefined; @@ -270,6 +279,20 @@ export function map$Option_str_Cow_str_Borrowed(self: string | undefined, _: (a0 return self; } +export function map$Option_u16s_u8_digest_words(self: rt.u16[] | undefined, _: (a0: rt.u16[]) => rt.u8): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return digestWords(self); +} + +export function map$Option_u32_u8_drains_closure5(self: rt.u32 | undefined, f: (a0: rt.u32) => rt.u8): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + export function map$Option_u8_Option_u8_made_closure1_closure0(self: rt.u8 | undefined, f: (a0: rt.u8) => rt.u8 | undefined): rt.u8 | undefined | rt.None { if (self === undefined) { return rt.None; @@ -326,6 +349,20 @@ export function map$Option_u8_u8_u8_u8_lent_closure2(self: [rt.u8, rt.u8] | unde return f(self); } +export function map$Option_u8s_u8_digest(self: rt.ByteSlice | undefined, _: (a0: rt.ByteSlice) => rt.u8): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return digest(self); +} + +export function map$Option_u8s_u8_parts_closure1(self: rt.ByteSlice | undefined, f: (a0: rt.ByteSlice) => rt.u8): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + export function map$Option_unit_Option_u8_made_closure3(self: undefined | rt.None, f: (a0: undefined) => rt.u8 | undefined): rt.u8 | undefined | rt.None { if (self === rt.None) { return rt.None; @@ -662,6 +699,13 @@ export function mapOr$Option_u8s_u8_skips_closure44(self: Uint8Array | undefined return f(self); } +export function mapOr$Option_u8s_u8s_bytes_closure1(self: rt.ByteSlice | undefined, default_: Uint8Array, f: (a0: rt.ByteSlice) => Uint8Array): Uint8Array { + if (self === undefined) { + return default_; + } + return f(self); +} + export function mapOr$Option_u8s_u8s_u8_splits_closure0(self: [rt.ByteSlice, rt.ByteSlice] | undefined, default_: rt.u8, f: (a0: [rt.ByteSlice, rt.ByteSlice]) => rt.u8): rt.u8 { if (self === undefined) { return default_; diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 68681a3e8..53c3aaa51 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -29,10 +29,11 @@ import { locals } from "./locals.ts"; import { locks, relock, rwlocks } from "./locks.ts"; import { nested } from "./nested.ts"; import { objects } from "./objects.ts"; -import { orders } from "./orders.ts"; +import { orders, bytes as orders_bytes } from "./orders.ts"; import { lists, shared as pointers_shared, places, unchecked, nested as pointers_nested, copies as pointers_copies, sentinels } from "./pointers.ts"; import { refs, toRefs } from "./refs.ts"; import { copies as shapes_copies, order, discriminants, loops, patterns, closures, library, flows } from "./shapes.ts"; +import { parts, drains } from "./slices.ts"; import { splits } from "./splits.ts"; import { statics, cells as statics_cells } from "./statics.ts"; import { strs, slices } from "./strs.ts"; @@ -88,7 +89,7 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) refs(data21, out21); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["fmt::counts", (_2121: rt.u8, data22: rt.ByteSlice, out22: rt.ByteVec): void => { counts(data22, out22); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["fmt::rounding", (_2122: rt.u8, _318: rt.ByteSlice, out23: rt.ByteVec): void => { + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["fmt::rounding", (_2122: rt.u8, _327: rt.ByteSlice, out23: rt.ByteVec): void => { rounding(out23); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["iters::skips", skips] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["wrappers::wrappers", wrappers] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["edits::edits", edits] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["utf8::decodes", decodes] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["floats::floats", floats] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["atomics::atomics", atomics] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["keys::overrides", overrides] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["dyns::dyns", (_2123: rt.u8, data23: rt.ByteSlice, out24: rt.ByteVec): void => { dyns(data23, out24); @@ -158,7 +159,9 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) returned(data55, out56); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["hashes::values", values] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["hashes::random", (_2156: rt.u8, data56: rt.ByteSlice, out57: rt.ByteVec): void => { random(data56, out57); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["floats::formats", formats] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["floats::parses", parses] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void]]).map(copy$str_forabfnu8au8bmutstdvecVecu8); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["floats::formats", formats] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["floats::parses", parses] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["orders::bytes", (_2157: rt.u8, data57: rt.ByteSlice, out58: rt.ByteVec): void => { + orders_bytes(data57, out58); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["slices::parts", parts] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["slices::drains", drains] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void]]).map(copy$str_forabfnu8au8bmutstdvecVecu8); } /** Run one case. */ diff --git a/ts/fixtures/lang/expected/orders.ts b/ts/fixtures/lang/expected/orders.ts index 6ce39a64c..6e0ef4277 100644 --- a/ts/fixtures/lang/expected/orders.ts +++ b/ts/fixtures/lang/expected/orders.ts @@ -2,8 +2,8 @@ import * as rt from "./rt.ts"; import { copy$u8_u8 } from "./lib.ts"; -import { min$Item, min$Item$2, min$String, min$u8, minBy$Item_cmps_closure2, minByKey$Item_cmps_closure4_Reverse_u8, max$Item, max$Item$2, max$String, max$i8, max$u8, maxBy$Item_cmps_closure1, maxByKey$Item_cmps_closure3_Item } from "./core/cmp.ts"; -import { mapOr$Option_Item_u8_heaps_closure1, mapOr$Option_usize_u8_u8_heaps_closure0 } from "./core/option.ts"; +import { min$Item, min$Item$2, min$String, min$u8, minBy$Item_cmps_closure2, minByKey$Item_cmps_closure4_Reverse_u8, max$Item, max$Item$2, max$String, max$i8, max$u8, max$u8s, maxBy$Item_cmps_closure1, maxByKey$Item_cmps_closure3_Item } from "./core/cmp.ts"; +import { mapOr$Option_Item_u8_heaps_closure1, mapOr$Option_u8_u8_btree_maps_closure5, mapOr$Option_u8s_u8s_bytes_closure1, mapOr$Option_usize_u8_u8_heaps_closure0 } from "./core/option.ts"; import * as Item from "./orders.Item.ts"; export const LOG: rt.LocalKey> = /* @__PURE__ */ new rt.LocalKey(LOG$init, false); @@ -369,13 +369,13 @@ export function heaps(data: rt.ByteSlice, out: rt.ByteVec): void { * and tuples, built every way, and their vectors, slices, clones, and debug form. */ export function values(data: rt.ByteSlice, out: rt.ByteVec): void { - const bytes: rt.BinaryHeap = rt.heapFrom(Array.from(rt.byteVecView(rt.byteSliceToByteVec(data))), rt.le, rt.ge, rt.lt); - rt.heapPush(bytes, data.length & 0xff, rt.le); - rt.iterExtendBytes(out, rt.iterSlice(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.from(bytes.d))))); - rt.iterExtendBytes(out, rt.iterSlice(rt.byteVecView(rt.byteVecFrom(Uint8Array.from(rt.heapIntoSortedVec(rt.heapClone(bytes), rt.le, rt.ge, rt.lt)))))); - const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(bytes.d, f, rt.u8Debug)]; + const bytes_: rt.BinaryHeap = rt.heapFrom(Array.from(rt.byteVecView(rt.byteSliceToByteVec(data))), rt.le, rt.ge, rt.lt); + rt.heapPush(bytes_, data.length & 0xff, rt.le); + rt.iterExtendBytes(out, rt.iterSlice(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.from(bytes_.d))))); + rt.iterExtendBytes(out, rt.iterSlice(rt.byteVecView(rt.byteVecFrom(Uint8Array.from(rt.heapIntoSortedVec(rt.heapClone(bytes_), rt.le, rt.ge, rt.lt)))))); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(bytes_.d, f, rt.u8Debug)]; rt.iterExtendBytes(out, rt.strBytes(rt.fmtFormat([args2[0]]))); - rt.iterExtendBytes(out, rt.iterSlice(rt.byteVecView(rt.byteVecFrom(Uint8Array.from(bytes.d))))); + rt.iterExtendBytes(out, rt.iterSlice(rt.byteVecView(rt.byteVecFrom(Uint8Array.from(bytes_.d))))); const least: rt.BinaryHeap = rt.heapFrom(rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_2: rt.u8): rt.u8 => { return _2; })), rt.cmpLe(rt.cmpReverse(rt.cmp)), rt.cmpGe(rt.cmpReverse(rt.cmp)), rt.cmpLt(rt.cmpReverse(rt.cmp))); @@ -439,4 +439,133 @@ export function values(data: rt.ByteSlice, out: rt.ByteVec): void { }, (value: Uint8Array) => rt.iterSlice(value))); } +/** + * Byte arrays, slices, and vectors, of the same length and of others, ordered as std + * orders them, by their bytes and then by length: directly, through `Ord`'s defaults, as + * keys and items, and in tuples, owned and borrowed. + */ +export function bytes(data: rt.ByteSlice, out: rt.ByteVec): void { + const iter: rt.Iter = rt.byteSliceWindows(data, 2); + while (true) { + const _6: rt.ByteSlice | rt.Done = iter.next(); + if (_6 === rt.DONE) { + break; + } + rt.idx(_6, 0); + const _14: rt.u8 = rt.u8Rem(_6.data[_6.start], 4); + rt.idx(_6, 1); + const _13: Uint8Array = Uint8Array.of(_14, rt.u8Rem(_6.data[_6.start + 1], 4)); + rt.idx(_6, 1); + const _27: rt.u8 = rt.u8Rem(_6.data[_6.start + 1], 4); + rt.idx(_6, 0); + const _12: [Uint8Array, Uint8Array] = [_13, Uint8Array.of(_27, rt.u8Rem(_6.data[_6.start], 2))]; + const a: Uint8Array = _13; + const b: Uint8Array = _12[1]; + const _41: rt.u8 = rt.cmpBytes(rt.byteSliceFrom(a), rt.byteSliceFrom(b)) === -1 ? 1 : 0; + const order = rt.cmpBytes(rt.byteSliceFrom(a), rt.byteSliceFrom(b)); + const _45: rt.u8 = order !== undefined && order <= 0 ? 1 : 0; + const _49: rt.u8 = rt.cmpBytes(rt.byteSliceFrom(a), rt.byteSliceFrom(b)) === 1 ? 1 : 0; + const order2 = rt.cmpBytes(rt.byteSliceFrom(a), rt.byteSliceFrom(b)); + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(_41, _45, _49, order2 !== undefined && order2 >= 0 ? 1 : 0))); + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(rt.cmpBytes(rt.byteSliceFrom(a), rt.byteSliceFrom(b)) & 0xff, rt.optionUnwrap(rt.cmpBytes(rt.byteSliceFrom(a), rt.byteSliceFrom(b))) & 0xff))); + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(max$u8s(a, b)[0], rt.ordMin(a, b, rt.cmpLt(rt.cmpBytes))[1], rt.ordClamp(a, Uint8Array.of(1, 1), Uint8Array.of(2, 2), rt.cmpLe(rt.cmpBytes), rt.cmpLt(rt.cmpBytes), rt.cmpGt(rt.cmpBytes))[1]))); + const pair: [Uint8Array, rt.u8] = [a, b[0]]; + const _95: [Uint8Array, rt.u8] = [b, a[1]]; + rt.byteVecPush(out, rt.cmpTuple([rt.cmpBytes, rt.cmp])(pair, _95) === -1 ? 1 : 0); + } + const cut: rt.usize = rt.min(data.length, 6); + const iter2: rt.RangeInclusive = new rt.RangeInclusive(0, cut, rt.usizeStep); + l3: while (true) { + const _104: rt.usize | rt.Done = iter2.next(); + if (_104 === rt.DONE) { + break; + } + const i: rt.usize = _104; + const iter3: rt.RangeInclusive = new rt.RangeInclusive(0, cut, rt.usizeStep); + while (true) { + const _111: rt.usize | rt.Done = iter3.next(); + if (_111 === rt.DONE) { + continue l3; + } + const j: rt.usize = _111; + const _118: rt.ByteSlice = rt.byteSliceRange(data, 0, i); + const _120: rt.ByteSlice = rt.byteSliceRange(data, j, cut); + const s: rt.ByteSlice = _118; + const _124: rt.u8 = rt.cmpBytes(s, _120) & 0xff; + const _127: rt.u8 = rt.cmpBytes(s, _120) === -1 ? 1 : 0; + const order3 = rt.cmpBytes(s, _120); + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(_124, _127, order3 !== undefined && order3 >= 0 ? 1 : 0))); + const _139: [rt.ByteVec, rt.ByteVec] = [rt.byteSliceToByteVec(s), rt.byteSliceToByteVec(_120)]; + const v: rt.ByteVec = _139[0]; + const u: rt.ByteVec = _139[1]; + const _144: rt.u8 = rt.cmpBytes(v, u) & 0xff; + const _149: rt.u8 = rt.cmpBytes(v, u) === 1 ? 1 : 0; + const order4 = rt.cmpBytes(v, u); + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(_144, _149, order4 !== undefined && order4 <= 0 ? 1 : 0))); + } + } + const arrays: Uint8Array[] = rt.iterToArray(rt.iterMap(rt.byteSliceChunks(data, 2), (c: rt.ByteSlice): Uint8Array => { + rt.idx(c, 0); + return Uint8Array.of(rt.u8Rem(c.data[c.start], 4), mapOr$Option_u8_u8_btree_maps_closure5(rt.byteSliceGet(c, 1), 0, (b2: rt.u8): rt.u8 => { + return rt.u8Rem(b2, 4); + })); + })); + rt.iterExtendBytes(out, rt.iterSlice(mapOr$Option_u8s_u8s_bytes_closure1(rt.iterMax(rt.iterMap(rt.iterSlice(arrays), rt.byteSliceFrom), rt.cmpLt(rt.cmpBytes)), Uint8Array.of(9, 9), (a4: rt.ByteSlice): Uint8Array => { + return rt.byteSliceToArray(a4); + }))); + rt.iterExtendBytes(out, rt.iterSlice(mapOr$Option_u8s_u8s_bytes_closure1(rt.iterMin(rt.iterMap(rt.iterSlice(arrays), rt.byteSliceFrom), rt.cmpLt(rt.cmpBytes)), Uint8Array.of(9, 9), (a5: rt.ByteSlice): Uint8Array => { + return rt.byteSliceToArray(a5); + }))); + const heap: rt.BinaryHeap = rt.heapFrom(rt.iterToArray(rt.iterCopied(rt.iterMap(rt.iterSlice(arrays), rt.byteSliceFrom), rt.byteSliceToArray)), rt.cmpLe(rt.cmpBytes), rt.cmpGe(rt.cmpBytes), rt.cmpLt(rt.cmpBytes)); + while (true) { + const _179: Uint8Array | undefined = rt.heapPop(heap, rt.cmpLe(rt.cmpBytes)); + if (_179 !== undefined) { + rt.iterExtendBytes(out, rt.iterSlice(_179)); + } else { + break; + } + } + const _185: rt.Iter<[Uint8Array, rt.usize]> = rt.iterMap(rt.iterEnumerate(rt.iterCopied(rt.iterMap(rt.iterSlice(arrays), rt.byteSliceFrom), rt.byteSliceToArray)), (_2: [rt.usize, Uint8Array]): [Uint8Array, rt.usize] => { + return [_2[1], _2[0]] as [Uint8Array, rt.usize]; + }); + rt.iterExtendBytes(out, rt.iterFlatMap(rt.btreeIter(rt.btreeExtend(rt.btreeNew(rt.cmpBytes) as rt.BTreeMap, _185, true)), (_22: [Uint8Array, rt.usize]): Uint8Array => { + const k: Uint8Array = _22[0]; + return Uint8Array.of(k[0], k[1], _22[1] & 0xff); + }, (value: Uint8Array) => rt.iterSlice(value))); + rt.sliceSort(arrays, rt.cmpLt(rt.cmpBytes)); + rt.iterExtendBytes(out, rt.iterFlatten(rt.iterMap(rt.iterSlice(arrays), rt.byteSliceFrom), (value: rt.ByteSlice) => rt.iterSlice(rt.byteSliceView(value)))); + const slices: rt.ByteSlice[] = rt.iterToArray(rt.byteSliceChunks(data, 3)); + rt.sliceSortBy(slices, (a7: rt.ByteSlice, b3: rt.ByteSlice): rt.Ordering => { + return rt.cmpBytes(b3, a7); + }); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(slices), (s2: rt.ByteSlice): rt.u8 => { + return s2.length & 0xff; + })); + const vecs: [rt.ByteVec, rt.usize][] = rt.iterToArray(rt.iterMap(rt.iterEnumerate(rt.byteSliceChunks(data, 3)), (_29: [rt.usize, rt.ByteSlice]): [rt.ByteVec, rt.usize] => { + const i4: rt.usize = _29[0]; + return [rt.byteSliceToByteVec(_29[1]), i4] as [rt.ByteVec, rt.usize]; + })); + rt.sliceSort(vecs, rt.cmpLt(rt.cmpTuple([rt.cmpBytes, rt.cmp]))); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(vecs), (_211: [rt.ByteVec, rt.usize]): rt.u8 => { + return _211[1] & 0xff; + })); + const refs: [rt.ByteSlice, rt.u8][] = []; + const iter4: rt.Iter = rt.byteSliceWindows(data, 2); + while (true) { + const _228: rt.ByteSlice | rt.Done = iter4.next(); + if (_228 === rt.DONE) { + break; + } + if (_228.length >= 2) { + rt.idx(_228, 0); + refs.push([new rt.ByteSlice(_228.data, _228.start, 2), rt.u8Div(_228.data[_228.start], 64)] as [rt.ByteSlice, rt.u8]); + } + } + rt.sliceSort(refs, rt.cmpLt(rt.cmpTuple([rt.cmpBytes, rt.cmp]))); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(refs), (_212: [rt.ByteSlice, rt.u8]): rt.u8 => { + const _86: rt.ByteSlice = _212[0]; + return _86.data[_86.start] ^ _212[1]; + })); +} + //# sourceMappingURL=orders.ts.map diff --git a/ts/fixtures/lang/expected/slices.Item.ts b/ts/fixtures/lang/expected/slices.Item.ts new file mode 100644 index 000000000..c74d49fc1 --- /dev/null +++ b/ts/fixtures/lang/expected/slices.Item.ts @@ -0,0 +1,25 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { LOG } from "./slices.ts"; + +/** Logs its tag as it drops. */ +export class Item { + tag: rt.u8; + + constructor(tag: rt.u8) { + this.tag = tag; + } + + [Symbol.dispose](): void { + drop$Drop(this); + } +} + +export function drop$Drop(self: Item): void { + rt.localKeyWithBorrowMut(LOG, (log: rt.ByteVec): void => { + rt.byteVecPush(log, self.tag); + }); +} + +//# sourceMappingURL=slices.Item.ts.map diff --git a/ts/fixtures/lang/expected/slices.ts b/ts/fixtures/lang/expected/slices.ts new file mode 100644 index 000000000..72c55ff63 --- /dev/null +++ b/ts/fixtures/lang/expected/slices.ts @@ -0,0 +1,263 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { map$Option_Item_u8_drains_closure10, map$Option_u16s_u8_digest_words, map$Option_u32_u8_drains_closure5, map$Option_u8s_u8_digest, map$Option_u8s_u8_parts_closure1 } from "./core/option.ts"; +import * as Item from "./slices.Item.ts"; + +export const LOG: rt.LocalKey> = /* @__PURE__ */ new rt.LocalKey(LOG$init, false); + +export function LOG$init(): rt.RefCell { + return new rt.RefCell(new rt.ByteVec()); +} + +/** Puts which items dropped since the last flush. */ +export function flush(out: rt.ByteVec): void { + rt.localKeyWithBorrowMut(LOG, (log: rt.ByteVec): void => { + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log)); + rt.byteVecClear(log); + }); +} + +/** A digest of a part, which tells parts of different lengths or contents apart. */ +export function digest(part: rt.ByteSlice): rt.u8 { + return rt.iterFold(rt.iterSlice(rt.byteSliceView(part)), part.length & 0xff, (acc: rt.u8, _32: rt.u8): rt.u8 => { + return rt.u8WrappingAdd(rt.u8WrappingMul(acc, 31), _32); + }); +} + +export function digestWords(part: rt.u16[]): rt.u8 { + return rt.iterFold(rt.iterSlice(part), part.length & 0xff, (acc: rt.u8, _32: rt.u16): rt.u8 => { + return rt.u8WrappingMul(acc, 31) ^ ((_32 >> 3) & 0xff); + }); +} + +/** + * `windows` or `chunks`, as `kind` picks, of a size it picks too, which is 0 one time in + * six, which panics. + */ +export function parts(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + const size: rt.usize = rt.u8Rem(rt.u8Div(kind, 2), 6) as rt.usize; + const words: rt.u16[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_2: rt.u8): rt.u16 => { + return rt.u16Mul(_2 as rt.u16, 257); + })); + if (rt.u8Rem(kind, 2) === 0) { + rt.iterExtendBytes(out, rt.iterMap(rt.byteSliceWindows(data, size), digest)); + rt.iterExtendBytes(out, rt.iterMap(rt.iterRev(rt.byteSliceWindows(data, size)), digest)); + const it: rt.Iter = rt.byteSliceWindows(data, size); + rt.byteVecPush(out, it.len() & 0xff); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_digest(rt.iterToOption(it.next()), digest))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_digest(rt.iterToOption(it.nextBack()), digest))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_digest(rt.iterNth(it, 1), digest))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_digest(rt.iterNthBack(it, 1), digest))); + rt.byteVecPush(out, it.len() & 0xff); + rt.iterExtendBytes(out, rt.iterMap(it, digest)); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_digest(rt.iterLast(rt.byteSliceWindows(data, size)), digest))); + rt.byteVecPush(out, rt.iterCount(rt.byteSliceWindows(data, size)) & 0xff); + rt.iterExtendBytes(out, rt.iterMap(rt.iterStepBy(rt.iterSkip(rt.byteSliceWindows(data, size), 2), 2), digest)); + rt.iterExtendBytes(out, rt.iterMap(rt.sliceWindows(words, size), digestWords)); + rt.iterExtendBytes(out, rt.iterMap(rt.iterRev(rt.sliceWindows(words, size)), digestWords)); + const it2: rt.Iter = rt.sliceWindows(words, size); + rt.byteVecPush(out, it2.len() & 0xff); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u16s_u8_digest_words(rt.iterToOption(it2.next()), digestWords))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u16s_u8_digest_words(rt.iterToOption(it2.nextBack()), digestWords))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u16s_u8_digest_words(rt.iterNth(it2, 1), digestWords))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u16s_u8_digest_words(rt.iterNthBack(it2, 1), digestWords))); + rt.byteVecPush(out, it2.len() & 0xff); + rt.iterExtendBytes(out, rt.iterMap(it2, digestWords)); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u16s_u8_digest_words(rt.iterLast(rt.sliceWindows(words, size)), digestWords))); + rt.byteVecPush(out, rt.iterCount(rt.sliceWindows(words, size)) & 0xff); + rt.iterExtendBytes(out, rt.iterMap(rt.iterStepBy(rt.iterSkip(rt.sliceWindows(words, size), 2), 2), digestWords)); + const steps: rt.Iter = rt.byteSliceWindows(data, size); + const _123: [rt.ByteSlice | undefined, rt.ByteSlice | undefined] = [rt.iterToOption(steps.next()), rt.iterToOption(steps.next())]; + if (_123[0] !== undefined) { + if (_123[1] !== undefined) { + const a: rt.ByteSlice = _123[0]; + const b: rt.ByteSlice = _123[1]; + const _134: rt.u8 = rt.byteSliceEq(a, b) ? 1 : 0; + rt.idx(a, 0); + const _138: rt.u8 = a.data[a.start]; + const _143: rt.usize = rt.usizeSub(size, 1); + rt.idx(b, _143); + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(_134, _138, b.data[b.start + _143]))); + } + } + } else { + rt.iterExtendBytes(out, rt.iterMap(rt.byteSliceChunks(data, size), digest)); + rt.iterExtendBytes(out, rt.iterMap(rt.iterRev(rt.byteSliceChunks(data, size)), digest)); + const it3: rt.Iter = rt.byteSliceChunks(data, size); + rt.byteVecPush(out, it3.len() & 0xff); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_digest(rt.iterToOption(it3.next()), digest))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_digest(rt.iterToOption(it3.nextBack()), digest))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_digest(rt.iterNth(it3, 1), digest))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_digest(rt.iterNthBack(it3, 1), digest))); + rt.byteVecPush(out, it3.len() & 0xff); + rt.iterExtendBytes(out, rt.iterMap(it3, digest)); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_digest(rt.iterLast(rt.byteSliceChunks(data, size)), digest))); + rt.byteVecPush(out, rt.iterCount(rt.byteSliceChunks(data, size)) & 0xff); + rt.iterExtendBytes(out, rt.iterMap(rt.iterStepBy(rt.iterSkip(rt.byteSliceChunks(data, size), 2), 2), digest)); + rt.iterExtendBytes(out, rt.iterMap(rt.sliceChunks(words, size), digestWords)); + rt.iterExtendBytes(out, rt.iterMap(rt.iterRev(rt.sliceChunks(words, size)), digestWords)); + const it4: rt.Iter = rt.sliceChunks(words, size); + rt.byteVecPush(out, it4.len() & 0xff); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u16s_u8_digest_words(rt.iterToOption(it4.next()), digestWords))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u16s_u8_digest_words(rt.iterToOption(it4.nextBack()), digestWords))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u16s_u8_digest_words(rt.iterNth(it4, 1), digestWords))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u16s_u8_digest_words(rt.iterNthBack(it4, 1), digestWords))); + rt.byteVecPush(out, it4.len() & 0xff); + rt.iterExtendBytes(out, rt.iterMap(it4, digestWords)); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u16s_u8_digest_words(rt.iterLast(rt.sliceChunks(words, size)), digestWords))); + rt.byteVecPush(out, rt.iterCount(rt.sliceChunks(words, size)) & 0xff); + rt.iterExtendBytes(out, rt.iterMap(rt.iterStepBy(rt.iterSkip(rt.sliceChunks(words, size), 2), 2), digestWords)); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u8s_u8_parts_closure1(rt.iterToOption(rt.byteSliceChunks(data, size).nextBack()), (c: rt.ByteSlice): rt.u8 => { + return c.length & 0xff; + }))); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(rt.iterToArray(rt.iterMap(rt.sliceChunks(words, size), (c2: rt.u16[]): rt.u16 => { + return rt.iterSum(rt.iterSlice(c2), rt.u16Add, 0) >> 2; + }))), (_22: rt.u16): rt.u8 => { + return _22 & 0xff; + })); + } +} + +/** + * `Vec::drain` of a range from the first two bytes, which may be out of bounds or + * backwards, which panics, of the rest as items, bytes, and integers: what it yields, and + * what each drops and keeps as the drain drops, or as it is forgotten. + */ +export function drains(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + if (data.length >= 2) { + const reach: rt.usize = rt.usizeAdd(rt.byteSliceRange(data, 2).length, 2); + const _14: [rt.usize, rt.usize] = [rt.usizeRem(data.data[data.start] as rt.usize, reach), rt.usizeRem(data.data[data.start + 1] as rt.usize, reach)]; + const a: rt.usize = _14[0]; + const b: rt.usize = _14[1]; + const items: Item.Item[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(rt.byteSliceRange(data, 2))), (_2: rt.u8): Item.Item => { + return new Item.Item(_2); + })); + const bytes: rt.ByteVec = rt.byteSliceToByteVec(rt.byteSliceRange(data, 2)); + const words: rt.u32[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(rt.byteSliceRange(data, 2))), (_23: rt.u8): rt.u32 => { + return rt.u32Add(_23 as rt.u32, 1000); + })); + const _31: rt.u8 = rt.u8Rem(kind, 8); + if (_31 === 0) { + const iter: rt.Iter = rt.vecDrain(items, new rt.Range(a, b), rt.drop); + while (true) { + const _38: Item.Item | rt.Done = iter.next(); + if (_38 === rt.DONE) { + break; + } + const x: Item.Item = _38; + rt.byteVecPush(out, x.tag); + flush(out); + x[Symbol.dispose](); + } + rt.drop(iter); + rt.iterExtendBytes(out, rt.byteVecDrain(bytes, new rt.Range(a, b)), "fold"); + rt.iterExtendBytes(out, rt.iterMap(rt.vecDrain(words, new rt.Range(a, b)), (w3: rt.u32): rt.u8 => { + return w3 & 0xff; + }), "fold"); + } else if (_31 === 1) { + const _56: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.usizeStep); + const drain: rt.Iter = rt.vecDrain(items, _56, rt.drop); + rt.iterExtendBytes(out, rt.iterOption(map$Option_Item_u8_drains_closure10(rt.iterToOption(drain.next()), (x9: Item.Item): rt.u8 => { + const _011: rt.u8 = x9.tag; + x9[Symbol.dispose](); + return _011; + }))); + rt.iterExtendBytes(out, rt.iterOption(map$Option_Item_u8_drains_closure10(rt.iterToOption(drain.nextBack()), (x10: Item.Item): rt.u8 => { + const _012: rt.u8 = x10.tag; + x10[Symbol.dispose](); + return _012; + }))); + rt.byteVecPush(out, drain.len() & 0xff); + rt.drop(drain); + flush(out); + const _74: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.usizeStep); + const drain2: rt.Iter = rt.byteVecDrain(bytes, _74); + rt.iterExtendBytes(out, rt.iterOption(rt.iterToOption(drain2.nextBack()))); + rt.drop(drain2); + const _82: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.usizeStep); + const drain3: rt.Iter = rt.vecDrain(words, _82); + rt.iterExtendBytes(out, rt.iterOption(map$Option_u32_u8_drains_closure5(rt.iterToOption(drain3.next()), (w2: rt.u32): rt.u8 => { + return w2 & 0xff; + }))); + rt.drop(drain3); + } else if (_31 === 2) { + const taken: Item.Item[] = rt.iterToArray(rt.vecDrain(items, { end: b }, rt.drop), "fold"); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(taken), (x8: Item.Item): rt.u8 => { + return x8.tag; + })); + rt.dropAll(taken); + rt.iterExtendBytes(out, rt.iterSlice(rt.byteVecView(rt.iterToByteVec(rt.byteVecDrain(bytes, { end: b }), "fold")))); + rt.drop(rt.vecDrain(words, { end: b })); + } else if (_31 === 3) { + const drain4: rt.Iter = rt.vecDrain(items, { start: a }, rt.drop); + rt.iterExtendBytes(out, rt.iterOption(map$Option_Item_u8_drains_closure10(rt.iterNth(drain4, 1, rt.drop), (x6: Item.Item): rt.u8 => { + const _07: rt.u8 = x6.tag; + x6[Symbol.dispose](); + return _07; + }))); + flush(out); + rt.iterExtendBytes(out, rt.iterOption(map$Option_Item_u8_drains_closure10(rt.iterNthBack(drain4, 1, rt.drop), (x7: Item.Item): rt.u8 => { + const _08: rt.u8 = x7.tag; + x7[Symbol.dispose](); + return _08; + }))); + flush(out); + rt.byteVecPush(out, drain4.len() & 0xff); + rt.drop(drain4); + const _127: rt.Iter = rt.byteVecDrain(bytes, { start: a }); + rt.iterExtendBytes(out, rt.iterOption(rt.iterNth(_127, 2))); + rt.drop(_127); + rt.iterExtendBytes(out, rt.iterMap(rt.iterRev(rt.vecDrain(words, { start: a })), (w: rt.u32): rt.u8 => { + return w & 0xff; + }), "fold"); + } else if (_31 === 4) { + rt.iterExtendBytes(out, rt.iterOption(map$Option_Item_u8_drains_closure10(rt.ownedLast(rt.vecDrain(items, undefined, rt.drop), rt.drop), (x5: Item.Item): rt.u8 => { + const _06: rt.u8 = x5.tag; + x5[Symbol.dispose](); + return _06; + }))); + rt.iterExtendBytes(out, rt.iterOption(rt.ownedLast(rt.byteVecDrain(bytes, undefined)))); + rt.byteVecPush(out, rt.ownedCount(rt.vecDrain(words, undefined)) & 0xff); + } else if (_31 === 5) { + rt.iterExtendBytes(out, rt.iterOption(map$Option_Item_u8_drains_closure10(rt.iterToOption(rt.vecDrain(items, new rt.Range(a, b), rt.drop).next()), (x4: Item.Item): rt.u8 => { + const _05: rt.u8 = x4.tag; + x4[Symbol.dispose](); + return _05; + }))); + rt.iterExtendBytes(out, rt.iterOption(rt.iterToOption(rt.byteVecDrain(bytes, new rt.Range(a, b)).next()))); + rt.vecDrain(words, new rt.Range(a, b)); + } else if (_31 === 6) { + rt.byteVecPush(out, rt.ownedCount(rt.vecDrain(items, new rt.Range(a, b), rt.drop), rt.drop) & 0xff); + } else { + const kept: Item.Item[] = [new Item.Item(238)]; + const _181: rt.Iter = rt.iterFilter(rt.vecDrain(items, new rt.Range(a, b), rt.drop), (x2: Item.Item): boolean => { + return rt.u8Rem(x2.tag, 2) === 0; + }, rt.drop); + rt.iterExtend(kept, _181, "next"); + flush(out); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(kept), (x3: Item.Item): rt.u8 => { + return x3.tag; + })); + const other: rt.ByteVec = rt.byteVecFrom(Uint8Array.of(238)); + const _195: rt.Iter = rt.iterRev(rt.byteVecDrain(bytes, new rt.Range(a, b))); + rt.iterExtendBytes(other, _195, "fold"); + rt.iterExtendBytes(out, rt.iterSlice(rt.byteVecView(other))); + rt.dropAll(kept); + } + flush(out); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(items), (x11: Item.Item): rt.u8 => { + return x11.tag; + })); + rt.byteVecPush(out, items.length & 0xff); + rt.iterExtendBytes(out, rt.iterSlice(rt.byteVecView(bytes))); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(words), (_26: rt.u32): rt.u8 => { + return _26 & 0xff; + })); + items.push(new Item.Item(255)); + rt.dropAll(items); + flush(out); + } +} + +//# sourceMappingURL=slices.ts.map diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 985281437..f722e3c1d 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -4,7 +4,7 @@ use crate::{ arrays, atomics, borrows, captures, cells, chars, chunks, collections, combinators, counts, cows, defaults, durations, dyns, edits, floats, fmt, generics, hashes, holds, ints, iters, keys, locals, locks, nested, objects, - orders, pointers, refs, shapes, splits, statics, strs, utf8, wrappers, + orders, pointers, refs, shapes, slices, splits, statics, strs, utf8, wrappers, }; /// The native side's entry: [`run`], except that a case starting with 0xff prints a @@ -128,6 +128,9 @@ fn cases() -> Vec<(&'static str, Case)> { ("hashes::random", |_, data, out| hashes::random(data, out)), ("floats::formats", floats::formats), ("floats::parses", floats::parses), + ("orders::bytes", |_, data, out| orders::bytes(data, out)), + ("slices::parts", slices::parts), + ("slices::drains", slices::drains), ] } diff --git a/ts/fixtures/lang/src/lib.rs b/ts/fixtures/lang/src/lib.rs index ac9b2db5c..2dc6a1240 100644 --- a/ts/fixtures/lang/src/lib.rs +++ b/ts/fixtures/lang/src/lib.rs @@ -8,8 +8,9 @@ //! `undefined`, atomics, `static` ones included, trait objects, one-time cells, mutexes, //! `Cell`s, `RefCell`s, read-write locks, and thread-locals, the defaults of std types, //! the counts of shared pointers, arrays `array::from_fn` makes, maps of `Option`s, -//! values held back past a write of a variable they name, and what `Hash` writes into -//! `DefaultHasher` and `RandomState`. +//! values held back past a write of a variable they name, what `Hash` writes into +//! `DefaultHasher` and `RandomState`, slices' `windows` and `chunks`, `Vec::drain`, and +//! the order of bytes. //! //! `harness::run` is the entry point both sides of the differential test run, and //! `fmt::Fault` an error only `caller.ts` prints. @@ -46,6 +47,7 @@ mod orders; mod pointers; mod refs; mod shapes; +mod slices; mod splits; mod statics; mod strs; diff --git a/ts/fixtures/lang/src/orders.rs b/ts/fixtures/lang/src/orders.rs index 250b5e90f..235154321 100644 --- a/ts/fixtures/lang/src/orders.rs +++ b/ts/fixtures/lang/src/orders.rs @@ -1,12 +1,13 @@ //! Ordering in std: `cmp`'s `max` and `min` and their `_by` and `_by_key` forms, the //! `is_sorted` family, and `BinaryHeap`, of a type that logs each comparison std makes of //! it and each drop, so which tests run, in what order, which of equal values comes out, -//! and when each value drops all show. +//! and when each value drops all show. Then byte arrays, slices, and vectors, by their +//! bytes and then their length. use std::cell::RefCell; use std::cmp::{self, Ordering, Reverse}; -use std::collections::BinaryHeap; use std::collections::binary_heap::PeekMut; +use std::collections::{BTreeMap, BinaryHeap}; thread_local! { static LOG: RefCell> = const { RefCell::new(Vec::new()) }; @@ -271,3 +272,55 @@ fn values(data: &[u8], out: &mut Vec) { } out.extend(pairs.into_sorted_vec().into_iter().flat_map(|(a, b)| [a, b])); } + +/// Byte arrays, slices, and vectors, of the same length and of others, ordered as std +/// orders them, by their bytes and then by length: directly, through `Ord`'s defaults, as +/// keys and items, and in tuples, owned and borrowed. +pub fn bytes(data: &[u8], out: &mut Vec) { + for w in data.windows(2) { + let (a, b) = ([w[0] % 4, w[1] % 4], [w[1] % 4, w[0] % 2]); + out.extend([(a < b) as u8, (a <= b) as u8, (a > b) as u8, (a >= b) as u8]); + out.extend([a.cmp(&b) as u8, a.partial_cmp(&b).unwrap() as u8]); + out.extend([cmp::max(a, b)[0], a.min(b)[1], a.clamp([1, 1], [2, 2])[1]]); + let pair = (a, b[0]); + out.push((pair < (b, a[1])) as u8); + } + // Each prefix against each suffix: a shorter one that is a prefix of the other is less. + let cut = data.len().min(6); + for i in 0..=cut { + for j in 0..=cut { + let (s, t) = (&data[..i], &data[j..cut]); + out.extend([s.cmp(t) as u8, (s < t) as u8, (s >= t) as u8]); + let (v, u) = (s.to_vec(), t.to_vec()); + out.extend([v.cmp(&u) as u8, (v > u) as u8, (v <= u) as u8]); + } + } + let mut arrays: Vec<[u8; 2]> = data + .chunks(2) + .map(|c| [c[0] % 4, c.get(1).map_or(0, |b| b % 4)]) + .collect(); + out.extend(arrays.iter().max().map_or([9, 9], |a| *a)); + out.extend(arrays.iter().min().map_or([9, 9], |a| *a)); + let mut heap: BinaryHeap<[u8; 2]> = arrays.iter().copied().collect(); + while let Some(a) = heap.pop() { + out.extend(a); + } + let keys: BTreeMap<[u8; 2], usize> = arrays.iter().copied().enumerate().map(|(i, a)| (a, i)).collect(); + out.extend(keys.into_iter().flat_map(|(k, i)| [k[0], k[1], i as u8])); + arrays.sort(); + out.extend(arrays.iter().flatten()); + let mut slices: Vec<&[u8]> = data.chunks(3).collect(); + slices.sort_by(|a, b| b.cmp(a)); + out.extend(slices.iter().map(|s| s.len() as u8)); + let mut vecs: Vec<(Vec, usize)> = data.chunks(3).enumerate().map(|(i, c)| (c.to_vec(), i)).collect(); + vecs.sort(); + out.extend(vecs.iter().map(|(_, i)| *i as u8)); + let mut refs: Vec<(&[u8; 2], u8)> = Vec::new(); + for w in data.windows(2) { + if let Some((a, _)) = w.split_first_chunk::<2>() { + refs.push((a, w[0] / 64)); + } + } + refs.sort(); + out.extend(refs.iter().map(|(a, n)| a[0] ^ n)); +} diff --git a/ts/fixtures/lang/src/slices.rs b/ts/fixtures/lang/src/slices.rs new file mode 100644 index 000000000..f415aec4f --- /dev/null +++ b/ts/fixtures/lang/src/slices.rs @@ -0,0 +1,177 @@ +//! A slice's `windows` and `chunks`, of bytes and of other values, read from both ends, +//! skipped through, and counted, at sizes past the slice's length; and `Vec::drain` of +//! each kind of range, read from both ends, dropped part way, and forgotten, of values +//! that log when they drop. + +use std::cell::RefCell; + +thread_local! { + static LOG: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// Puts which items dropped since the last flush. +fn flush(out: &mut Vec) { + LOG.with_borrow_mut(|log| { + out.extend_from_slice(log); + log.clear(); + }); +} + +/// Logs its tag as it drops. +struct Item { + tag: u8, +} + +impl Drop for Item { + fn drop(&mut self) { + LOG.with_borrow_mut(|log| log.push(self.tag)); + } +} + +/// A digest of a part, which tells parts of different lengths or contents apart. +fn digest(part: &[u8]) -> u8 { + part.iter() + .fold(part.len() as u8, |acc, &b| acc.wrapping_mul(31).wrapping_add(b)) +} + +fn digest_words(part: &[u16]) -> u8 { + part.iter() + .fold(part.len() as u8, |acc, &w| acc.wrapping_mul(31) ^ (w >> 3) as u8) +} + +/// Each way of reading `$parts`, an expression that makes the iterator anew. +macro_rules! read { + ($parts:expr, $digest:expr, $out:expr) => {{ + let out: &mut Vec = $out; + out.extend($parts.map($digest)); + out.extend($parts.rev().map($digest)); + let mut it = $parts; + out.push(it.len() as u8); + out.extend(it.next().map($digest)); + out.extend(it.next_back().map($digest)); + out.extend(it.nth(1).map($digest)); + out.extend(it.nth_back(1).map($digest)); + out.push(it.len() as u8); + out.extend(it.map($digest)); + out.extend($parts.last().map($digest)); + out.push($parts.count() as u8); + out.extend($parts.skip(2).step_by(2).map($digest)); + }}; +} + +/// `windows` or `chunks`, as `kind` picks, of a size it picks too, which is 0 one time in +/// six, which panics. +pub fn parts(kind: u8, data: &[u8], out: &mut Vec) { + let size = (kind / 2 % 6) as usize; + let words: Vec = data.iter().map(|&b| b as u16 * 257).collect(); + match kind % 2 { + 0 => { + read!(data.windows(size), digest, out); + read!(words.windows(size), digest_words, out); + // A window kept past the next, and compared with it. + let mut steps = data.windows(size); + if let (Some(a), Some(b)) = (steps.next(), steps.next()) { + out.extend([(a == b) as u8, a[0], b[size - 1]]); + } + } + _ => { + read!(data.chunks(size), digest, out); + read!(words.chunks(size), digest_words, out); + // The remainder, which the last chunk is. + out.extend(data.chunks(size).next_back().map(|c| c.len() as u8)); + let rows: Vec = words.chunks(size).map(|c| c.iter().sum::() >> 2).collect(); + out.extend(rows.iter().map(|&r| r as u8)); + } + } +} + +/// `Vec::drain` of a range from the first two bytes, which may be out of bounds or +/// backwards, which panics, of the rest as items, bytes, and integers: what it yields, and +/// what each drops and keeps as the drain drops, or as it is forgotten. +pub fn drains(kind: u8, data: &[u8], out: &mut Vec) { + let [a, b, data @ ..] = data else { + return; + }; + let reach = data.len() + 2; + let (a, b) = (*a as usize % reach, *b as usize % reach); + let mut items: Vec = data.iter().map(|&tag| Item { tag }).collect(); + let mut bytes = data.to_vec(); + let mut words: Vec = data.iter().map(|&b| b as u32 + 1000).collect(); + match kind % 8 { + 0 => { + for x in items.drain(a..b) { + out.push(x.tag); + flush(out); + } + out.extend(bytes.drain(a..b)); + out.extend(words.drain(a..b).map(|w| w as u8)); + } + // The rest of the range drops front to back, before the tail moves back. + 1 => { + let mut drain = items.drain(a..=b); + out.extend(drain.next().map(|x| x.tag)); + out.extend(drain.next_back().map(|x| x.tag)); + out.push(drain.len() as u8); + drop(drain); + flush(out); + let mut drain = bytes.drain(a..=b); + out.extend(drain.next_back()); + drop(drain); + let mut drain = words.drain(a..=b); + out.extend(drain.next().map(|w| w as u8)); + } + 2 => { + let taken: Vec = items.drain(..b).collect(); + out.extend(taken.iter().map(|x| x.tag)); + drop(taken); + let taken: Vec = bytes.drain(..b).collect(); + out.extend(taken); + words.drain(..b); + } + // What `nth` and `nth_back` skip drops as they pass it. + 3 => { + let mut drain = items.drain(a..); + out.extend(drain.nth(1).map(|x| x.tag)); + flush(out); + out.extend(drain.nth_back(1).map(|x| x.tag)); + flush(out); + out.push(drain.len() as u8); + drop(drain); + out.extend(bytes.drain(a..).nth(2)); + out.extend(words.drain(a..).rev().map(|w| w as u8)); + } + 4 => { + out.extend(items.drain(..).last().map(|x| x.tag)); + out.extend(bytes.drain(..).last()); + out.push(words.drain(..).count() as u8); + } + // Forgotten, a drain leaves the vector what came before the range, and leaks the rest. + 5 => { + let mut drain = items.drain(a..b); + out.extend(drain.next().map(|x| x.tag)); + std::mem::forget(drain); + let mut drain = bytes.drain(a..b); + out.extend(drain.next()); + std::mem::forget(drain); + std::mem::forget(words.drain(a..b)); + } + 6 => out.push(items.drain(a..b).count() as u8), + _ => { + let mut kept = vec![Item { tag: 0xee }]; + kept.extend(items.drain(a..b).filter(|x| x.tag % 2 == 0)); + flush(out); + out.extend(kept.iter().map(|x| x.tag)); + let mut other = vec![0xee]; + other.extend(bytes.drain(a..b).rev()); + out.extend(other); + } + } + flush(out); + out.extend(items.iter().map(|x| x.tag)); + out.push(items.len() as u8); + out.extend(&bytes); + out.extend(words.iter().map(|&w| w as u8)); + items.push(Item { tag: 0xff }); + drop(items); + flush(out); +} diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index f4b8b45bd..e17c00e14 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 103 -- Function instances: 116 +- Refusals: 105 +- Function instances: 117 - Generic functions no instance reached, lowered over their type parameters: 7 ## By construct @@ -20,6 +20,7 @@ | 2 | `_`, a trait object of another crate's trait, which is not supported yet | fixtures/reject/src/lib.rs:11:16 | | 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | fixtures/reject/src/lib.rs:518:23 | | 2 | a coercion to `_`, which is not supported yet | fixtures/reject/src/lib.rs:509:40 | +| 2 | a range of `_`, whose bounds the runtime doesn't read, which is not supported yet | fixtures/reject/src/lib.rs:753:4 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:169:1 | | 2 | constructing `_` from another crate | fixtures/reject/src/lib.rs:155:23 | | 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:149:2 | @@ -91,6 +92,7 @@ The type or module each refused type or path belongs to. | 3 | `std::sync::Arc` | fixtures/reject/src/lib.rs:321:2 | | 3 | `u8` | fixtures/reject/src/lib.rs:289:6 | | 3 | `{closure}` | fixtures/reject/src/lib.rs:372:13 | +| 2 | `(std::ops::Bound, std::ops::Bound)` | fixtures/reject/src/lib.rs:753:4 | | 2 | `Poll` | fixtures/reject/src/lib.rs:91:20 | | 2 | `Scaled` | fixtures/reject/src/lib.rs:518:23 | | 2 | `dyn Scaled` | fixtures/reject/src/lib.rs:518:23 | @@ -156,6 +158,7 @@ The type or module each refused type or path belongs to. | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | `Option` | fixtures/reject/src/lib.rs:16:15 | | 2 | `_`, a trait object of another crate's trait, which is not supported yet | `dyn std::iter::Iterator` | fixtures/reject/src/lib.rs:11:16 | | 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | `dyn Scaled`, `Scaled` | fixtures/reject/src/lib.rs:518:23 | +| 2 | a range of `_`, whose bounds the runtime doesn't read, which is not supported yet | `(std::ops::Bound, std::ops::Bound)` | fixtures/reject/src/lib.rs:753:4 | | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:126:2 | | 2 | replacing the value behind a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:110:2 | | 2 | unsupported call to `_` | `::sum` | fixtures/reject/src/lib.rs:483:17 | @@ -342,6 +345,13 @@ The type or module each refused type or path belongs to. +
a range of `_`, whose bounds the runtime doesn't read, which is not supported yet (2) + +- fixtures/reject/src/lib.rs:753:4: a range of `(std::ops::Bound, std::ops::Bound)`, whose bounds the runtime doesn't read, which is not supported yet +- fixtures/reject/src/lib.rs:753:52: a range of `(std::ops::Bound, std::ops::Bound)`, whose bounds the runtime doesn't read, which is not supported yet + +
+
an iterator of the crate implementing `_`, which is not supported yet (2) - fixtures/reject/src/lib.rs:169:1: an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index c1f26f8f6..7f18935dd 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -95,6 +95,8 @@ a dangling pointer to `Only`, a value of no bytes made of more than structs and unsupported call to ` as std::iter::Iterator>::is_sorted` at fixtures/reject/src/lib.rs:735:15 comparing pointers to `u32` in an atomic, which JS has no address of at fixtures/reject/src/lib.rs:746:15 a constant of type `&u32`, a pointer into memory translation can't name at fixtures/reject/src/lib.rs:747:3 +a range of `(std::ops::Bound, std::ops::Bound)`, whose bounds the runtime doesn't read, which is not supported yet at fixtures/reject/src/lib.rs:753:4 +a range of `(std::ops::Bound, std::ops::Bound)`, whose bounds the runtime doesn't read, which is not supported yet at fixtures/reject/src/lib.rs:753:52 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:149:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:169:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:203:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index ebcd45751..83ca394ed 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -746,3 +746,9 @@ pub fn pointer_statics(p: *mut u32) -> u32 { let _ = SLOT.compare_exchange(p, std::ptr::null_mut(), Relaxed, Relaxed); *NAMED } + +/// Ranges of `Bound`s, which the runtime reads as unbounded where it reads no `start` or `end`. +pub fn bound_ranges(v: &mut Vec, map: &std::collections::BTreeMap) -> usize { + use std::ops::Bound::{Excluded, Included}; + v.drain((Excluded(0), Included(2))).count() + map.range((Excluded(0), Included(2))).count() +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 8f2102e20..bee7ca06f 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -80,5 +80,6 @@ roots = [ "heap_optional", "places_sorted", "pointer_statics", + "bound_ranges", ] printable = ["Meters"] diff --git a/ts/runtime/rt/collections.ts b/ts/runtime/rt/collections.ts index 7904ab026..faf928323 100644 --- a/ts/runtime/rt/collections.ts +++ b/ts/runtime/rt/collections.ts @@ -14,11 +14,11 @@ // A function that may drop a key, value, or item std's would, rather than return or keep // it, takes what drops each that does, as `k`, `v`, or `f`, and drops it where std's does. -import { type None, type Place, panic } from "../rt.ts"; +import { ByteSlice, type ByteVec, type None, type Place, panic } from "../rt.ts"; import type { Hashing } from "./hash.ts"; import { type Limbs, lt } from "./int.ts"; import { DONE, type Done, Iter, iterMap, iterSlice, type RangeInclusive, type Take } from "./iter.ts"; -import { type Arc, drop as dispose, dropAll } from "./task.ts"; +import { type Arc, drop as dispose, dropAll, dropRange } from "./task.ts"; // Ordering @@ -144,6 +144,23 @@ export function cmpSlice(cmp: (a: T, b: T) => }; } +/** + * `Ord::cmp` of byte arrays, slices, or vectors, or `PartialOrd::partial_cmp`: by their + * bytes in order, then by length. Each is a `[u8; N]`, a `&[u8]` or `&[u8; N]`, or a + * `Vec`, whichever a key or an operand holds. + */ +export function cmpBytes(a: Uint8Array | ByteSlice | ByteVec, b: Uint8Array | ByteSlice | ByteVec): Ordering { + const x = a instanceof Uint8Array ? a : a.data; + const y = b instanceof Uint8Array ? b : b.data; + const i = a instanceof ByteSlice ? a.start : 0; + const j = b instanceof ByteSlice ? b.start : 0; + const n = Math.min(a.length, b.length); + for (let k = 0; k < n; k++) { + if (x[i + k] !== y[j + k]) return x[i + k] < y[j + k] ? -1 : 1; + } + return a.length < b.length ? -1 : a.length > b.length ? 1 : 0; +} + /** `Ord::cmp` of `Arc`s, or `PartialOrd::partial_cmp` or one of its tests: their values'. */ export function cmpArc(cmp: (a: T, b: T) => O): (a: Arc, b: Arc) => O { return (a, b) => cmp(a.value, b.value); @@ -1889,14 +1906,7 @@ class DequePlaces extends Iter> { /** `drain`: the items within `r`, taken out at once, which drop by `drop` as `dequeIter`'s. */ export function dequeDrain(q: VecDeque, r: Bounds, drop?: (item: T) => void): Iter { - // As `slice::range` checks it. - const [lo, hi, inclusive] = bounds(r); - if (hi !== undefined && (inclusive ? hi.key >= q.n : hi.key > q.n)) panic(`range end index ${hi.key} out of range for slice of length ${q.n}`); - const end = hi === undefined ? q.n : inclusive ? hi.key + 1 : hi.key; - const start = lo === undefined ? 0 : lo.key; - if (start > end) { - panic(start > q.n ? `range start index ${start} out of range for slice of length ${q.n}` : `slice index starts at ${start} but ends at ${end}`); - } + const [start, end] = sliceRange(r, q.n); const taken: VecDeque = { b: [], h: 0, n: 0 }; for (let i = start; i < end; i++) dequePushBack(taken, q.b[at(q, i)] as T); for (let i = end; i < q.n; i++) q.b[at(q, i - (end - start))] = q.b[at(q, i)]; @@ -1904,6 +1914,119 @@ export function dequeDrain(q: VecDeque, r: Bounds, drop?: (item: T return new DequeIter(taken, 0, taken.n, drop); } +/** `slice::range`: the start and end of `r` within `n` elements, panicking as std's does. */ +function sliceRange(r: Bounds, n: number): [number, number] { + const [lo, hi, inclusive] = bounds(r); + if (hi !== undefined && (inclusive ? hi.key >= n : hi.key > n)) panic(`range end index ${hi.key} out of range for slice of length ${n}`); + const end = hi === undefined ? n : inclusive ? hi.key + 1 : hi.key; + const start = lo === undefined ? 0 : lo.key; + if (start > end) { + panic(start > n ? `range start index ${start} out of range for slice of length ${n}` : `slice index starts at ${start} but ends at ${end}`); + } + return [start, end]; +} + +// `Vec::drain`, which leaves the vector only what comes before the range until the drain +// drops and moves the tail back, so a drain that never drops, as `mem::forget` leaves +// it, leaks the rest, as std's does. + +/** + * `Vec::drain`: the elements within `r`. Those it still holds as it drops each drop by + * `drop`, front to back, before the tail moves back. + */ +export function vecDrain(v: T[], r: Bounds, drop?: (item: T) => void): Iter { + const [start, end] = sliceRange(r, v.length); + return new VecDrain(v, v.splice(start), end - start, drop); +} + +/** A `Vec`'s drain: of `rest`, what followed the range's start, the range, then the tail. */ +class VecDrain extends Iter implements Disposable { + private readonly v: T[]; + private readonly rest: T[]; + private front = 0; + private back: number; + /** Where the tail starts in `rest`. */ + private readonly tail: number; + private readonly drop: ((item: T) => void) | undefined; + + constructor(v: T[], rest: T[], tail: number, drop?: (item: T) => void) { + super(); + this.v = v; + this.rest = rest; + this.back = tail; + this.tail = tail; + this.drop = drop; + } + + next(): T | Done { + return this.front < this.back ? this.rest[this.front++] : DONE; + } + + override nextBack(): T | Done { + return this.front < this.back ? this.rest[--this.back] : DONE; + } + + override len(): number { + return this.back - this.front; + } + + [Symbol.dispose](): void { + const from = this.front; + this.front = this.back; + if (this.drop !== undefined) dropRange(this.rest, this.drop, from, this.back); + for (let i = this.tail; i < this.rest.length; i++) this.v.push(this.rest[i]); + this.rest.length = this.tail; + } +} + +/** `Vec::drain` of bytes. */ +export function byteVecDrain(v: ByteVec, r: Bounds): Iter { + const [start, end] = sliceRange(r, v.length); + const length = v.length; + v.length = start; + return new ByteVecDrain(v, start, end, length); +} + +/** A `Vec`'s drain, which reads the range from the vector's storage in place. */ +class ByteVecDrain extends Iter implements Disposable { + private readonly v: ByteVec; + private readonly start: number; + private front: number; + private back: number; + private readonly end: number; + /** The vector's length before the drain, or -1 once the tail moved back. */ + private length: number; + + constructor(v: ByteVec, start: number, end: number, length: number) { + super(); + this.v = v; + this.start = start; + this.front = start; + this.back = end; + this.end = end; + this.length = length; + } + + next(): number | Done { + return this.front < this.back ? this.v.data[this.front++] : DONE; + } + + override nextBack(): number | Done { + return this.front < this.back ? this.v.data[--this.back] : DONE; + } + + override len(): number { + return this.back - this.front; + } + + [Symbol.dispose](): void { + if (this.length < 0) return; + this.v.data.copyWithin(this.start, this.end, this.length); + this.v.length = this.start + this.length - this.end; + this.length = -1; + } +} + /** `extend`, and `collect` into a deque through `dequeNew`, which takes `items` as `take` says. */ export function dequeExtend(q: VecDeque, items: Iter, take?: Take): VecDeque { return extending(q, items, (item) => dequePushBack(q, item), take); diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index 5301b1f13..15c77a1a7 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -19,7 +19,7 @@ // an order each kind of iterator has its own, the `owned` functions follow it, dispatching // on the kind, so a bundle that never drops an item carries none of it. -import { ByteVec, byteVecPush, Err, type None, Ok, type Place, panic, type RangeBound, type Result } from "../rt.ts"; +import { ByteSlice, ByteVec, byteVecPush, Err, type None, Ok, type Place, panic, type RangeBound, type Result } from "../rt.ts"; import { AtIndex, BTreeIter, HashIter } from "./collections.ts"; import { type Limbs, lt as wideLt, type Step } from "./int.ts"; import { drop as dispose, dropRange } from "./task.ts"; @@ -217,6 +217,34 @@ export function iterSliceMut(s: { [i: number]: T; length: number }): Iter(s: T[], size: number): Iter { + if (size === 0) panic("window size must be non-zero"); + return new PartsIter(s, s.length, size, 1, (s, start, end) => s.slice(start, end)); +} + +/** `slice::chunks`: each `size` elements, the last fewer, panicking on a size of 0 as std's does. */ +export function sliceChunks(s: T[], size: number): Iter { + if (size === 0) panic("chunk size must be non-zero"); + return new PartsIter(s, s.length, size, size, (s, start, end) => s.slice(start, end)); +} + +/** `slice::windows` of bytes. */ +export function byteSliceWindows(s: ByteSlice, size: number): Iter { + if (size === 0) panic("window size must be non-zero"); + return new PartsIter(s, s.length, size, 1, byteSlicePart); +} + +/** `slice::chunks` of bytes. */ +export function byteSliceChunks(s: ByteSlice, size: number): Iter { + if (size === 0) panic("chunk size must be non-zero"); + return new PartsIter(s, s.length, size, size, byteSlicePart); +} + +function byteSlicePart(s: ByteSlice, start: number, end: number): ByteSlice { + return new ByteSlice(s.data, s.start + start, end - start); +} + /** `Option::iter`, and with what drops its item, `option::IntoIter`. */ export function iterOption(o: T | undefined, drop?: Drop): Iter; export function iterOption(o: T | None, drop: Drop | undefined, none: None): Iter; @@ -953,6 +981,61 @@ class SliceMutIter extends Iter> { } } +/** + * `slice::Windows` and `Chunks` of `s`, of `length` elements: the part from each `step`th + * element on, `size` long or up to the end, as `part` slices it, while one starts before + * the end and, for windows, which step by 1, is `size` long. + */ +class PartsIter extends Iter { + private readonly s: S; + private readonly length: number; + private readonly size: number; + private readonly step: number; + private readonly part: (s: S, start: number, end: number) => S; + private front = 0; + /** How many parts there are, less those taken from the back. */ + private back: number; + + constructor(s: S, length: number, size: number, step: number, part: (s: S, start: number, end: number) => S) { + super(); + this.s = s; + this.length = length; + this.size = size; + this.step = step; + this.part = part; + this.back = step === 1 ? Math.max(length - size + 1, 0) : Math.ceil(length / size); + } + + private at(i: number): S { + const start = i * this.step; + return this.part(this.s, start, Math.min(start + this.size, this.length)); + } + + next(): S | Done { + return this.front < this.back ? this.at(this.front++) : DONE; + } + + override nextBack(): S | Done { + return this.front < this.back ? this.at(--this.back) : DONE; + } + + override len(): number { + return this.back - this.front; + } + + override advanceBy(n: number): number { + const step = Math.min(n, this.back - this.front); + this.front += step; + return n - step; + } + + override advanceBackBy(n: number): number { + const step = Math.min(n, this.back - this.front); + this.back -= step; + return n - step; + } +} + /** `option::IntoIter`, `Once`, and `Empty`: at most one item. */ class OptionIter extends Iter implements Disposable { private item: T | undefined; diff --git a/ts/src/lower/collections.rs b/ts/src/lower/collections.rs index 8098f2983..c6afc7c76 100644 --- a/ts/src/lower/collections.rs +++ b/ts/src/lower/collections.rs @@ -100,9 +100,9 @@ pub fn call<'tcx>( return Ok(Some(test.test(b, order, out))); } ("PartialEq", "eq" | "ne", ..) if let Some(t) = self_ty => { - // The library maps the integers' and `bool`'s. + // The library maps the integers', `bool`'s, and byte slices'. let t = peel(b, t); - if matches!(t.kind(), ty::Bool | ty::Int(_) | ty::Uint(_)) || !std_key(b, t) { + if matches!(t.kind(), ty::Bool | ty::Int(_) | ty::Uint(_)) || bytes(b, t) || !std_key(b, t) { return Err(args); } // A tuple's and an `Arc`'s `ne` call what they hold's, which `!eq` stands for @@ -694,6 +694,7 @@ fn btree<'tcx>( }; Expr::rt(f, super::iter::tail(values, droppers)) } + (_, "range" | "range_mut") if let Some(msg) = unread_range(b, call) => b.err(span, msg), (_, "range") if set => Expr::rt("btreeRangeKeys", values), (_, "range_mut") if b.t.needs_place(arg(coll, 1)) => Expr::rt("btreeRangeMut", values), (_, "range" | "range_mut") => Expr::rt("btreeRange", values), @@ -853,6 +854,7 @@ fn deque<'tcx>( } (_, "iter_mut") if b.t.needs_place(item) => Expr::rt("dequeIterMut", values), (_, "iter" | "iter_mut") => Expr::rt("dequeIter", values), + (_, "drain") if let Some(msg) = unread_range(b, call) => b.err(span, msg), (_, "drain") => { let droppers = entry_droppers(b, coll, span); Expr::rt("dequeDrain", super::iter::tail(values, droppers)) @@ -1210,6 +1212,7 @@ fn std_key<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool { ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true, ty::Tuple(tys) => !tys.is_empty() && tys.iter().all(held), _ if let Some(elem) = elements_of(b, ty) => held(elem), + _ if bytes(b, ty) => true, ty::Adt(..) if let Some(inner) = option_of(b, ty).or_else(|| arc_of(b, ty)).or_else(|| reverse_of(b, ty)) => { held(inner) } @@ -1239,6 +1242,31 @@ fn elements_of<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> Option> { (!matches!(elem.kind(), ty::Uint(ty::UintTy::U8))).then_some(elem) } +/// Whether `ty` is a `Vec`, a slice, or an array of bytes: a typed array, an `rt.ByteSlice` +/// behind a reference, or an `rt.ByteVec`. +fn bytes<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool { + let elem = match ty.kind() { + ty::Slice(elem) | ty::Array(elem, _) => *elem, + ty::Adt(..) if b.t.std_of(ty) == Some(Std::Vec) => arg(ty, 0), + _ => return false, + }; + matches!(elem.kind(), ty::Uint(ty::UintTy::U8)) +} + +/// Why the runtime can't read the range `call` takes last as an `rt.Bounds`, if it can't: +/// it reads std's range types, not a tuple of `Bound`s or the crate's own `RangeBounds`. +pub fn unread_range<'tcx>(b: &Body<'_, '_, 'tcx>, call: &Call<'tcx>) -> Option { + let range = *b.t.sig(call.def_id, call.args).inputs().last()?; + match b.t.std_of(range) { + Some( + Std::Range | Std::RangeInclusive | Std::RangeFrom | Std::RangeTo | Std::RangeToInclusive | Std::RangeFull, + ) => None, + _ => Some(format!( + "a range of `{range}`, whose bounds the runtime doesn't read, which is not supported yet" + )), + } +} + /// What `ty` holds if it is an `Arc`. fn arc_of<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> Option> { (b.t.std_of(ty) == Some(Std::Arc)).then(|| arg(ty, 0)) @@ -1270,6 +1298,8 @@ pub fn cmp_fn<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, partial: bool, spa Expr::rt("cmpReverse", vec![cmp_fn(b, inner, partial, span)]) } _ if let Some(elem) = elements_of(b, ty) => Expr::rt("cmpSlice", vec![cmp_fn(b, elem, partial, span)]), + // Whichever form it has, as the key it is or the operand a reference passes. + _ if bytes(b, ty) => Expr::Rt("cmpBytes".into()), ty::Adt(adt, _) if b.t.own(adt.did()) && partial => { let cmp = trait_fn(tcx, "PartialOrd", "partial_cmp"); b.fn_value(cmp, tcx.mk_args(&[ty.into(), ty.into()]), span) diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index 9c973c039..981a5b507 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -9,7 +9,7 @@ use rustc_middle::ty::{self, AdtDef, Instance, Ty, TypeVisitableExt}; use rustc_span::Span; -use super::library::Std; +use super::library::{self, Std}; use super::mir::Capture; use super::{Adt, AdtRepr, Translator}; use crate::program::{SymKind, Symbol}; @@ -65,6 +65,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { ) => args.types().any(|t| self.drops(t)), // An entry borrows its map, and holds only the key it was given. Some(Std::Entry) => args.types().next().is_some_and(|k| self.drops(k)), + // A `Vec`'s drain moves the vector's tail back as it drops. + None if library::std_path(tcx, adt.did()) == ["vec", "drain", "Drain"] => true, None | Some(Std::Peekable) if self.std_iter(ty) => match adt.has_dtor(tcx) { // What owns its items, an `IntoIter` or a `Drain`, drops those it still holds. true => args.types().any(|t| self.drops(t)), diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 1eb1dcef9..708c6ef94 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -1310,6 +1310,10 @@ fn mapping<'tcx>( }; rt2(values, "slice", &super::camel(name)) } + ("slice", "windows" | "chunks") => match is_u8(targ(gargs, 0)) { + true => rt2(args, "byteSlice", &super::camel(&name)), + false => rt2(args, "slice", &super::camel(&name)), + }, ("slice", "split_first_chunk") => { let n = gargs.consts().next()?.try_to_target_usize(tcx)?; let mut values = args; @@ -1542,6 +1546,13 @@ fn mapping<'tcx>( }; rt2(values, of, &f) } + // Of a range, which `Vec::drain::` takes. + ("Vec", "drain") if let Some(msg) = super::collections::unread_range(b, call) => b.err(span, msg), + ("Vec", "drain") if is_u8(targ(gargs, 0)) => Expr::rt("byteVecDrain", args), + ("Vec", "drain") => { + let dropper = b.t.dropper(targ(gargs, 0), span); + Expr::rt("vecDrain", super::iter::tail(args, vec![dropper])) + } ("Vec", "as_slice" | "as_mut_slice") => { let v = args.pop()?; vec_view(v, targ(gargs, 0)) diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index bcf596ba4..d0044ac5b 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -168,6 +168,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { if let Some((owner, name)) = library::key(tcx, def_id) { let handled = match (owner.as_str(), name.as_str()) { ("Index" | "IndexMut", "index" | "index_mut") | ("Clone", "clone") | ("Argument", _) => true, + // The runtime compares bytes in whichever form it is given them. + ("PartialOrd" | "Ord", _) => true, ("slice", "iter" | "iter_mut") => true, ("IntoIterator", "into_iter") => self_ty.is_some_and(|s| elem(tcx, s).is_some()), _ => false,