From d03d8c29eeed026f1731d91ffda0b967cd744f86 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 30 Oct 2026 04:57:46 -0700 Subject: [PATCH 1/2] chore(quest): claim quest/m3/ts-slice-ranges.md Quest-Claim: 9800f92fe6b8bba4 From 4ab00ddff3e939832823ba5b8626aecb744c0538 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 30 Oct 2026 05:18:00 -0700 Subject: [PATCH 2/2] feat(ts): translate a slice's parts by inclusive and checked ranges and by fixed size `&v[a..=b]`, `&v[..=b]`, a pair of `Bound`s, and their `&mut`, `get` and `get_mut` of each kind of range, and `first_chunk`, `last_chunk`, `split_first_chunk`, `split_last_chunk`, and their `_mut` forms translate, of bytes and other values. A range std's ranges don't take apart in place passes as the `rt.Bounds` drains read, which the runtime checks as std's `SliceIndex` does, `a..=b` by its own fields. A mutable part of other values is the runtime's `sliceView`. Co-Authored-By: Claude Opus 5.5 --- quest/m3/README.md | 1 - quest/m3/ts-slice-ranges.md | 20 - ts/fixtures/lang/caller.ts | 15 +- ts/fixtures/lang/expected/core/option.ts | 15 + ts/fixtures/lang/expected/harness.ts | 6 +- ts/fixtures/lang/expected/lib.ts | 4 + ts/fixtures/lang/expected/slices.ts | 461 ++++++++++++++++++++++- ts/fixtures/lang/expected/splits.ts | 2 +- ts/fixtures/lang/src/harness.rs | 1 + ts/fixtures/lang/src/lib.rs | 3 +- ts/fixtures/lang/src/slices.rs | 205 +++++++++- ts/runtime/rt.ts | 56 ++- ts/runtime/rt/collections.ts | 34 +- ts/src/lower/collections.rs | 28 +- ts/src/lower/library.rs | 33 +- ts/src/lower/mir/call.rs | 51 ++- 16 files changed, 865 insertions(+), 70 deletions(-) delete mode 100644 quest/m3/ts-slice-ranges.md diff --git a/quest/m3/README.md b/quest/m3/README.md index c2c0248b6..5e8cb08df 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -30,7 +30,6 @@ generic std gap is planned here even when moq never calls it. - [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 - [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 - [A slice's edits in place](/quest/m3/ts-slice-edits.md) - `fill`, `rotate_left`, and `copy_from_slice` of other values translate -- [A slice's parts by inclusive range, checked range, and fixed size](/quest/m3/ts-slice-ranges.md) - `&v[a..=b]`, `get_mut(a..b)`, and `first_chunk_mut` translate, writing through - [Waiting: a slice object for a mutable part of other values](/quest/m3/ts-slice-object.md) - waits on a moq profile showing the `Proxy` view's traps matter, then decides on an `rt.ByteSlice`-like form - [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-slice-ranges.md b/quest/m3/ts-slice-ranges.md deleted file mode 100644 index 8ebf0ac71..000000000 --- a/quest/m3/ts-slice-ranges.md +++ /dev/null @@ -1,20 +0,0 @@ -# [S] A slice's parts by inclusive range, checked range, and fixed size - -## Goal - -rust2-ts translates the parts of a slice that still refuse with a span: indexing by an -inclusive range (`&v[a..=b]`, `&v[..=b]`, and their `&mut`), `get` and `get_mut` of a -range, and `first_chunk`, `last_chunk`, `split_last_chunk`, and the `_mut` forms of those -and `split_first_chunk`, for bytes and other values, with writes through a mutable part -landing in the slice and std's panics and `None`s. Proven by differential tests against -native Rust. - -## Plan - -Indexing takes `Range`, `RangeTo`, `RangeFrom`, and `RangeFull` apart in `range_bounds` -(`src/lower/mir/call.rs`); an inclusive range falls through to an unsupported call, and -must panic as std's does at `b == usize::MAX` and past the end. `get` maps only an -integer index. A part of bytes is a view already, and a mutable part of other values the -runtime's `sliceView`, as `&mut v[a..b]` lends it. - -Public API: the translator's output. diff --git a/ts/fixtures/lang/caller.ts b/ts/fixtures/lang/caller.ts index c0e2885a9..b2f035b38 100644 --- a/ts/fixtures/lang/caller.ts +++ b/ts/fixtures/lang/caller.ts @@ -340,4 +340,17 @@ const subslices = [0, 1, 2, 3, 4].flatMap((n) => }), ); -export const cases: Uint8Array[] = [...loops, ...durations, ...ints(), ...utf8, ...floats, ...formats, ...parsed, ...dyns, ...cells, ...shared, ...locks, ...onces, ...bounds, ...unsafeCells, ...edits, ...subslices]; +/** + * `ranges` of each kind, and each kind of `Bound` at the end, over zero to four items, at + * every pair of bounds up to one past the end and at `usize::MAX`. + */ +const rangesOp = op("slices::ranges"); +const ranges = [0, 1, 2, 3, 4].flatMap((n) => { + const ends = [...Array(n + 2).keys(), 0xff]; + return Array.from({ length: 24 * ends.length ** 2 }, (_, i) => { + const [kind, a, b] = [i % 24, ends[Math.floor(i / 24) % ends.length], ends[Math.floor(i / 24 / ends.length)]]; + return Uint8Array.of(rangesOp, kind, a, b, ...[0x31, 0xc2, 0x07, 0xfe].slice(0, n)); + }); +}); + +export const cases: Uint8Array[] = [...loops, ...durations, ...ints(), ...utf8, ...floats, ...formats, ...parsed, ...dyns, ...cells, ...shared, ...locks, ...onces, ...bounds, ...unsafeCells, ...edits, ...subslices, ...ranges]; diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts index c745a3449..7af9b96e9 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -33,6 +33,7 @@ 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 slices_Pair from "../slices.Pair.ts"; import type * as Short from "../splits.Short.ts"; export function isSomeAnd$09tpccf(self: rt.u8 | undefined, f: (a0: rt.u8) => boolean): boolean { @@ -273,6 +274,13 @@ export function map$0pkankm(self: rt.u8 | undefined | rt.None, f: (a0: rt.u8 | u return f(self); } +export function map$11y9s7r(self: slices_Pair.Pair[] | undefined, f: (a0: slices_Pair.Pair[]) => rt.u8): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + export function map$0lcwx9x(self: Way.Way | undefined, f: (a0: Way.Way) => boolean): boolean | undefined { if (self === undefined) { return undefined; @@ -294,6 +302,13 @@ export function map$0qyyft9(self: rt.u16[] | undefined, _: (a0: rt.u16[]) => rt. return digestWords(self); } +export function map$1wqzuhy(self: rt.u16[] | undefined, f: (a0: rt.u16[]) => rt.u8): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + export function map$0a57co2(self: rt.u32 | undefined, f: (a0: rt.u32) => rt.u8): rt.u8 | undefined { if (self === undefined) { return undefined; diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index df730287a..e761f1c8e 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -34,7 +34,7 @@ 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, cells as pointers_cells } 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, chunked, subslices, drains } from "./slices.ts"; +import { parts, chunked, subslices, drains, ranges as slices_ranges } from "./slices.ts"; import { splits } from "./splits.ts"; import { statics, cells as statics_cells, onces } from "./statics.ts"; import { strs, slices, edits as strs_edits } from "./strs.ts"; @@ -90,7 +90,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, _351: rt.ByteSlice, out23: rt.ByteVec): void => { + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["fmt::rounding", (_2122: rt.u8, _354: 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); @@ -168,7 +168,7 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) writes(data59, out60); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["bounds::bounds", bounds] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["pointers::cells", (_2160: rt.u8, data60: rt.ByteSlice, out61: rt.ByteVec): void => { pointers_cells(data60, out61); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["ints::parses", ints_parses] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["strs::edits", strs_edits] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["slices::subslices", subslices] 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], ["ints::parses", ints_parses] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["strs::edits", strs_edits] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["slices::subslices", subslices] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["slices::ranges", slices_ranges] 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/lib.ts b/ts/fixtures/lang/expected/lib.ts index 254fe9f3d..36f8bfb5c 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -47,6 +47,10 @@ export function copy$Bound_usize(v: rt.RangeBound): rt.RangeBound; } +export function copy$Bound_usize_Bound_usize(v: [rt.RangeBound, rt.RangeBound]): [rt.RangeBound, rt.RangeBound] { + return [copy$Bound_usize(v[0]), copy$Bound_usize(v[1])]; +} + export function copy$Bumped(v: Bumped.Bumped): Bumped.Bumped { return { _0: v._0 }; } diff --git a/ts/fixtures/lang/expected/slices.ts b/ts/fixtures/lang/expected/slices.ts index 980c4a442..a38c8dca5 100644 --- a/ts/fixtures/lang/expected/slices.ts +++ b/ts/fixtures/lang/expected/slices.ts @@ -1,8 +1,8 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Pair$3 } from "./lib.ts"; -import { map$003seos, map$0qyyft9, map$0a57co2, map$0c2keyb, map$1xk4yz1 } from "./core/option.ts"; +import { copy$Bound_usize_Bound_usize, copy$Pair$3 } from "./lib.ts"; +import { map$003seos, map$11y9s7r, map$0qyyft9, map$1wqzuhy, map$0a57co2, map$0c2keyb, map$1xk4yz1 } from "./core/option.ts"; import * as Item from "./slices.Item.ts"; import * as Pair from "./slices.Pair.ts"; @@ -1294,4 +1294,461 @@ export function drains(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } } +/** + * A slice's parts by an inclusive range, by a pair of `Bound`s, by `get` and `get_mut` of + * each kind of range, and by fixed size from either end, of bytes and other values, at + * bounds from the first two bytes, 0xff being `usize::MAX`, which may be out of bounds or + * backwards, which panics or gives `None`; with what is written through each mutable + * part landing in what it came from. + */ +export function ranges(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + let _104!: rt.u8; + let _112!: rt.u8; + let _120!: rt.u8; + let _128!: rt.u8; + let _136!: rt.u8; + let _144!: rt.u8; + let _151!: rt.u8; + let _157!: rt.u8; + let _165!: rt.u8; + let _173!: rt.u8; + let _181!: rt.u8; + let _189!: rt.u8; + let _197!: rt.u8; + let _207!: rt.u8; + let _293!: rt.u8; + let _302!: rt.u8; + let _311!: rt.u8; + let _350!: rt.u8; + let _358!: rt.u8; + const _46: (a0: rt.u32[]) => rt.u8 = (s2: rt.u32[]): rt.u8 => { + return rt.iterFold(rt.iterSlice(s2), s2.length & 0xff, (acc: rt.u8, _32: rt.u32): rt.u8 => { + return rt.u8WrappingMul(acc, 31) ^ ((_32 >>> 5) & 0xff); + }); + }; + const _335: (a0: rt.usize, a1: rt.u8) => rt.RangeBound = (x2: rt.usize, k: rt.u8): rt.RangeBound => { + const _42: rt.u8 = rt.u8Rem(k, 3); + if (_42 === 0) { + return { tag: "Included", _0: x2 } as rt.RangeBound; + } + if (_42 === 1) { + return { tag: "Excluded", _0: x2 } as rt.RangeBound; + } + return { tag: "Unbounded" } as rt.RangeBound; + }; + if (data.length >= 2) { + const reach: rt.usize = rt.usizeAdd(rt.byteSliceRange(data, 2).length, 2); + const at: (a0: rt.u8) => rt.usize = (x3: rt.u8): rt.usize => { + if (!(x3 === 255)) { + return rt.usizeRem(x3 as rt.usize, reach); + } + return 4294967295; + }; + const _16: [rt.usize, rt.usize] = [at(data.data[data.start]), at(data.data[data.start + 1])]; + const a: rt.usize = _16[0]; + const b: rt.usize = _16[1]; + const bytes: rt.ByteVec = rt.byteSliceToByteVec(rt.byteSliceRange(data, 2)); + const words: rt.u16[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(rt.byteSliceRange(data, 2))), (_2: rt.u8): rt.u16 => { + return rt.u16Mul(_2 as rt.u16, 257); + })); + const pairs: Pair.Pair[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(rt.byteSliceRange(data, 2))), (_22: rt.u8): Pair.Pair => { + const b4: rt.u8 = _22; + return { a: b4, b: rt.u16Mul(b4 as rt.u16, 3) }; + })); + const array: rt.u32[] = Array.from({ length: 5 }, (): rt.u32 => { + return 0; + }); + const iter: rt.Iter<[rt.Place, rt.u8]> = rt.iterZip(rt.iterSliceMut(array), rt.iterSlice(rt.byteSliceView(rt.byteSliceRange(data, 2))), true); + while (true) { + const _39: [rt.Place, rt.u8] | rt.Done = iter.next(); + if (_39 === rt.DONE) { + break; + } + _39[0].v = rt.u32Mul(_39[1] as rt.u32, 65599); + } + const _47: rt.u8 = rt.u8Rem(kind, 8); + if (_47 === 0) { + const _53: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.usizeStep); + const slice7 = rt.byteVecSlice(bytes); + const bounds26 = rt.sliceIndexBounds(_53, slice7.length); + rt.byteVecPush(out, digest(rt.byteSliceRange(slice7, bounds26[0], bounds26[1]))); + const bounds27 = rt.sliceIndexBounds(new rt.RangeInclusive(a, b, rt.usizeStep), words.length); + rt.byteVecPush(out, digestWords(rt.sliceRange(words, bounds27[0], bounds27[1]))); + const bounds28 = rt.sliceIndexBounds({ end: b, inclusive: true }, pairs.length); + rt.byteVecPush(out, digestPairs(rt.sliceRange(pairs, bounds28[0], bounds28[1]))); + const bounds29 = rt.sliceIndexBounds(new rt.RangeInclusive(rt.min(a, 4), rt.min(b, 4), rt.usizeStep), array.length); + const part6 = rt.sliceRange(array, bounds29[0], bounds29[1]); + rt.byteVecPush(out, _46(part6)); + const slice8 = rt.byteSliceRange(data, 2); + const bounds30 = rt.sliceIndexBounds({ end: b, inclusive: true }, slice8.length); + rt.byteVecPush(out, digest(rt.byteSliceRange(slice8, bounds30[0], bounds30[1]))); + } else if (_47 === 1) { + const _79: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.usizeStep); + const slice6 = rt.byteVecSlice(bytes); + const bounds21 = rt.sliceIndexBounds(_79, slice6.length); + const part: rt.ByteSlice = rt.byteSliceRange(slice6, bounds21[0], bounds21[1]); + rt.byteSliceView(part).reverse(); + rt.idx(part, 0); + part.data[part.start] = part.data[part.start] ^ 90; + const bounds22 = rt.sliceIndexBounds({ end: b, inclusive: true }, words.length); + pokeWords(0, rt.sliceRangeMut(words, bounds22[0], bounds22[1])); + const bounds23 = rt.sliceIndexBounds(new rt.RangeInclusive(a, b, rt.usizeStep), pairs.length); + pokePairs(1, rt.sliceRangeMut(pairs, bounds23[0], bounds23[1])); + const bounds24 = rt.sliceIndexBounds({ end: rt.min(b, 4), inclusive: true }, array.length); + pokeArray(rt.sliceRangeMut(array, bounds24[0], bounds24[1])); + const s: rt.u16[] = words; + const bounds25 = rt.sliceIndexBounds(new rt.RangeInclusive(a, b, rt.usizeStep), s.length); + pokeWords(2, rt.sliceRangeMut(s, bounds25[0], bounds25[1])); + } else if (_47 === 2) { + const _105: rt.ByteSlice | undefined = rt.byteSliceGetRange(rt.byteVecSlice(bytes), a, b); + if (_105 === undefined) { + _104 = 238; + } else { + _104 = digest(_105); + } + rt.byteVecPush(out, _104); + const _114: rt.ByteSlice = rt.byteVecSlice(bytes); + const bounds16 = rt.sliceGetBounds(new rt.RangeInclusive(a, b, rt.usizeStep), _114.length); + const _113: rt.ByteSlice | undefined = rt.byteSliceGetRange(_114, bounds16[0], bounds16[1]); + if (_113 === undefined) { + _112 = 238; + } else { + _112 = digest(_113); + } + rt.byteVecPush(out, _112); + const _121: rt.ByteSlice | undefined = rt.byteSliceGetRange(rt.byteVecSlice(bytes), 0, b); + if (_121 === undefined) { + _120 = 238; + } else { + _120 = digest(_121); + } + rt.byteVecPush(out, _120); + const _130: rt.ByteSlice = rt.byteVecSlice(bytes); + const bounds17 = rt.sliceGetBounds({ end: b, inclusive: true }, _130.length); + const _129: rt.ByteSlice | undefined = rt.byteSliceGetRange(_130, bounds17[0], bounds17[1]); + if (_129 === undefined) { + _128 = 238; + } else { + _128 = digest(_129); + } + rt.byteVecPush(out, _128); + const _137: rt.ByteSlice | undefined = rt.byteSliceGetRange(rt.byteVecSlice(bytes), a); + if (_137 === undefined) { + _136 = 238; + } else { + _136 = digest(_137); + } + rt.byteVecPush(out, _136); + const _145: rt.ByteSlice | undefined = rt.byteSliceGetRange(rt.byteVecSlice(bytes), 0); + if (_145 === undefined) { + _144 = 238; + } else { + _144 = digest(_145); + } + rt.byteVecPush(out, _144); + const _152: rt.ByteSlice | undefined = rt.byteSliceGetRange(rt.byteSliceRange(data, 2), a, b); + if (_152 === undefined) { + _151 = 238; + } else { + _151 = digest(_152); + } + rt.byteVecPush(out, _151); + const _158: rt.u16[] | undefined = rt.sliceGetRange(words, a, b); + if (_158 === undefined) { + _157 = 238; + } else { + _157 = digestWords(_158); + } + rt.byteVecPush(out, _157); + const _167: rt.u16[] = words; + const bounds18 = rt.sliceGetBounds(new rt.RangeInclusive(a, b, rt.usizeStep), _167.length); + const _166: rt.u16[] | undefined = rt.sliceGetRange(_167, bounds18[0], bounds18[1]); + if (_166 === undefined) { + _165 = 238; + } else { + _165 = digestWords(_166); + } + rt.byteVecPush(out, _165); + const _175: rt.u16[] = words; + const bounds19 = rt.sliceGetBounds({ end: b, inclusive: true }, _175.length); + const _174: rt.u16[] | undefined = rt.sliceGetRange(_175, bounds19[0], bounds19[1]); + if (_174 === undefined) { + _173 = 238; + } else { + _173 = digestWords(_174); + } + rt.byteVecPush(out, _173); + const _182: Pair.Pair[] | undefined = rt.sliceGetRange(pairs, a); + if (_182 === undefined) { + _181 = 238; + } else { + _181 = digestPairs(_182); + } + rt.byteVecPush(out, _181); + const _190: Pair.Pair[] | undefined = rt.sliceGetRange(pairs, 0, b); + if (_190 === undefined) { + _189 = 238; + } else { + _189 = digestPairs(_190); + } + rt.byteVecPush(out, _189); + const _199: rt.u32[] = array; + const bounds20 = rt.sliceGetBounds(new rt.RangeInclusive(a, b, rt.usizeStep), _199.length); + const _198: rt.u32[] | undefined = rt.sliceGetRange(_199, bounds20[0], bounds20[1]); + if (_198 === undefined) { + _197 = 238; + } else { + _197 = _46(_198); + } + rt.byteVecPush(out, _197); + const _208: rt.u32[] | undefined = rt.sliceGetRange(array, 0); + if (_208 === undefined) { + _207 = 238; + } else { + _207 = _46(_208); + } + rt.byteVecPush(out, _207); + } else if (_47 === 3) { + const _217: rt.ByteSlice = rt.byteVecSlice(bytes); + const bounds12 = rt.sliceGetBounds(new rt.RangeInclusive(a, b, rt.usizeStep), _217.length); + const _216: rt.ByteSlice | undefined = rt.byteSliceGetRange(_217, bounds12[0], bounds12[1]); + if (_216 === undefined) { + rt.byteVecPush(out, 238); + } else { + rt.byteSliceView(_216).reverse(); + } + const _222: rt.ByteSlice | undefined = rt.byteSliceGetRange(rt.byteVecSlice(bytes), 0, b); + b26: { + if (_222 !== undefined) { + const iter2: rt.Iter> = rt.iterSliceMut(rt.byteSliceView(_222)); + while (true) { + const _231: rt.Place | rt.Done = iter2.next(); + if (_231 === rt.DONE) { + break b26; + } + _231.v = 119; + } + } + } + const _236: rt.u16[] | undefined = rt.sliceGetRangeMut(words, a, b); + if (_236 === undefined) { + rt.byteVecPush(out, 238); + } else { + pokeWords(3, _236); + } + const _243: rt.u16[] = words; + const bounds13 = rt.sliceGetBounds({ end: b, inclusive: true }, _243.length); + const _242: rt.u16[] | undefined = rt.sliceGetRangeMut(_243, bounds13[0], bounds13[1]); + if (_242 !== undefined) { + pokeWords(4, _242); + } + const _251: Pair.Pair[] = pairs; + const bounds14 = rt.sliceGetBounds(new rt.RangeInclusive(a, b, rt.usizeStep), _251.length); + const _250: Pair.Pair[] | undefined = rt.sliceGetRangeMut(_251, bounds14[0], bounds14[1]); + if (_250 === undefined) { + rt.byteVecPush(out, 238); + } else { + pokePairs(5, _250); + } + const _256: Pair.Pair[] | undefined = rt.sliceGetRangeMut(pairs, a); + if (_256 !== undefined) { + pokePairs(6, _256); + } + const _264: rt.u32[] = array; + const bounds15 = rt.sliceGetBounds(new rt.RangeInclusive(a, b, rt.usizeStep), _264.length); + const _263: rt.u32[] | undefined = rt.sliceGetRangeMut(_264, bounds15[0], bounds15[1]); + if (_263 !== undefined) { + pokeArray(_263); + } + } else if (_47 === 4) { + const stepped: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.usizeStep); + const iter3: rt.Iter = rt.iterTake(rt.iterBorrow(stepped), 8); + while (iter3.next() !== rt.DONE) { + } + const folded: rt.RangeInclusive = new rt.RangeInclusive(a, rt.min(b, reach), rt.usizeStep); + rt.iterSum(rt.iterBorrow(folded), rt.usizeAdd, 0); + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(rt.rangeInclusiveIsEmpty(stepped) ? 1 : 0, rt.rangeInclusiveIsEmpty(folded) ? 1 : 0))); + const _295: rt.u16[] = words; + const bounds6 = rt.sliceGetBounds(rt.rangeInclusiveClone(stepped), _295.length); + const _294: rt.u16[] | undefined = rt.sliceGetRange(_295, bounds6[0], bounds6[1]); + if (_294 === undefined) { + _293 = 238; + } else { + _293 = digestWords(_294); + } + rt.byteVecPush(out, _293); + const _304: rt.ByteSlice = rt.byteVecSlice(bytes); + const bounds7 = rt.sliceGetBounds(rt.rangeInclusiveClone(folded), _304.length); + const _303: rt.ByteSlice | undefined = rt.byteSliceGetRange(_304, bounds7[0], bounds7[1]); + if (_303 === undefined) { + _302 = 238; + } else { + _302 = digest(_303); + } + rt.byteVecPush(out, _302); + const _313: Pair.Pair[] = pairs; + const bounds8 = rt.sliceGetBounds(rt.rangeInclusiveClone(folded), _313.length); + const _312: Pair.Pair[] | undefined = rt.sliceGetRangeMut(_313, bounds8[0], bounds8[1]); + if (_312 === undefined) { + _311 = 238; + } else { + _311 = ((p: Pair.Pair[]): rt.u8 => { + return digestPairs(p); + })(_312); + } + rt.byteVecPush(out, _311); + const bounds9 = rt.sliceIndexBounds(rt.rangeInclusiveClone(folded), words.length); + pokeWords(7, rt.sliceRangeMut(words, bounds9[0], bounds9[1])); + const _330: rt.RangeInclusive = stepped; + const slice3 = rt.byteVecSlice(bytes); + const bounds10 = rt.sliceIndexBounds(_330, slice3.length); + rt.byteVecPush(out, digest(rt.byteSliceRange(slice3, bounds10[0], bounds10[1]))); + const _334: rt.RangeInclusive = folded; + const slice4 = rt.byteSliceRange(data, 2); + const bounds11 = rt.sliceIndexBounds(_334, slice4.length); + rt.byteVecPush(out, digest(rt.byteSliceRange(slice4, bounds11[0], bounds11[1]))); + } else if (_47 === 5) { + const part4 = rt.byteSliceRange(data, 2).length & 0xff; + const _339: rt.RangeBound = _335(a, part4); + const _338: [rt.RangeBound, rt.RangeBound] = [_339, _335(b, rt.u8Div(kind, 8))]; + const lo: rt.RangeBound = _339; + const hi: rt.RangeBound = _338[1]; + const _352: rt.ByteSlice = rt.byteVecSlice(bytes); + const bounds = rt.sliceGetBounds(copy$Bound_usize_Bound_usize([lo, hi] as [rt.RangeBound, rt.RangeBound]), _352.length); + const _351: rt.ByteSlice | undefined = rt.byteSliceGetRange(_352, bounds[0], bounds[1]); + if (_351 === undefined) { + _350 = 238; + } else { + _350 = digest(_351); + } + rt.byteVecPush(out, _350); + const _360: Pair.Pair[] = pairs; + const bounds2 = rt.sliceGetBounds(copy$Bound_usize_Bound_usize([lo, hi] as [rt.RangeBound, rt.RangeBound]), _360.length); + const _359: Pair.Pair[] | undefined = rt.sliceGetRange(_360, bounds2[0], bounds2[1]); + if (_359 === undefined) { + _358 = 238; + } else { + _358 = digestPairs(_359); + } + rt.byteVecPush(out, _358); + const _366: rt.u16[] = words; + const bounds3 = rt.sliceGetBounds(copy$Bound_usize_Bound_usize([lo, hi] as [rt.RangeBound, rt.RangeBound]), _366.length); + const _365: rt.u16[] | undefined = rt.sliceGetRangeMut(_366, bounds3[0], bounds3[1]); + if (_365 !== undefined) { + pokeWords(8, _365); + } + const bounds4 = rt.sliceIndexBounds(copy$Bound_usize_Bound_usize([lo, hi] as [rt.RangeBound, rt.RangeBound]), pairs.length); + pokePairs(9, rt.sliceRangeMut(pairs, bounds4[0], bounds4[1])); + const slice2 = rt.byteVecSlice(bytes); + const bounds5 = rt.sliceIndexBounds(copy$Bound_usize_Bound_usize([lo, hi] as [rt.RangeBound, rt.RangeBound]), slice2.length); + rt.byteVecPush(out, digest(rt.byteSliceRange(slice2, bounds5[0], bounds5[1]))); + } else if (_47 === 6) { + rt.iterExtendBytes(out, rt.iterOption(map$0c2keyb(rt.byteSliceGetRange(rt.byteVecSlice(bytes), 0, 0), (c2: rt.ByteSlice): rt.u8 => { + return digest(c2); + }))); + rt.iterExtendBytes(out, rt.iterOption(map$0c2keyb(rt.byteSliceGetRange(rt.byteVecSlice(bytes), 0, 3), (c3: rt.ByteSlice): rt.u8 => { + return digest(c3); + }))); + rt.iterExtendBytes(out, rt.iterOption(map$0c2keyb(rt.byteSliceLastChunk(rt.byteSliceRange(data, 2), 1), (c4: rt.ByteSlice): rt.u8 => { + return digest(c4); + }))); + rt.iterExtendBytes(out, rt.iterOption(map$0c2keyb(rt.byteSliceLastChunk(rt.byteSliceRange(data, 2), 4), (c5: rt.ByteSlice): rt.u8 => { + return digest(c5); + }))); + rt.iterExtendBytes(out, rt.iterOption(map$1wqzuhy(rt.sliceGetRange(words, 0, 4), (c6: rt.u16[]): rt.u8 => { + return digestWords(c6); + }))); + rt.iterExtendBytes(out, rt.iterOption(map$1wqzuhy(rt.sliceLastChunk(words, 0), (c7: rt.u16[]): rt.u8 => { + return digestWords(c7); + }))); + rt.iterExtendBytes(out, rt.iterOption(map$11y9s7r(rt.sliceLastChunk(pairs, 3), (c8: Pair.Pair[]): rt.u8 => { + return digestPairs(c8); + }))); + const slice: rt.ByteSlice = rt.byteVecSlice(bytes); + if (slice.length >= 1) { + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(digest(new rt.ByteSlice(slice.data, slice.start, 1)), digest(new rt.ByteSlice(slice.data, slice.start + 1, slice.length - 1))))); + } + const _423: [rt.ByteSlice, rt.ByteSlice] | undefined = rt.byteSliceSplitLastChunk(rt.byteVecSlice(bytes), 4); + if (_423 !== undefined) { + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(digest(_423[0]), digest(_423[1])))); + } + const _434: [rt.u16[], rt.u16[]] | undefined = rt.sliceSplitAtChecked(words, 0); + if (_434 !== undefined) { + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(digestWords(_434[0]), digestWords(_434[1])))); + } + const _445: [Pair.Pair[], Pair.Pair[]] | undefined = rt.sliceSplitLastChunk(pairs, 3); + if (_445 !== undefined) { + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(digestPairs(_445[0]), digestPairs(_445[1])))); + } + const _456: [rt.u32[], rt.u32[]] | undefined = rt.sliceSplitLastChunk(array, 5); + if (_456 !== undefined) { + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(_46(_456[0]), _46(_456[1])))); + } + } else { + const _471: rt.ByteSlice | undefined = rt.byteSliceGetRange(rt.byteVecSlice(bytes), 0, 3); + if (_471 !== undefined) { + const _476: rt.u8 = rt.u8WrappingAdd(_471.data[_471.start + 2], 1); + _471.data[_471.start] = _476; + rt.byteSliceView(_471).reverse(); + } + const _484: rt.ByteSlice | undefined = rt.byteSliceLastChunk(rt.byteVecSlice(bytes), 1); + if (_484 !== undefined) { + _484.data[_484.start] = _484.data[_484.start] ^ 255; + } + const _491: rt.u16[] | undefined = rt.sliceGetRangeMut(words, 0, 4); + if (_491 !== undefined) { + pokeWords(10, _491); + } + const _498: rt.u16[] | undefined = rt.sliceLastChunkMut(words, 0); + if (_498 !== undefined) { + pokeWords(11, _498); + } + const _505: Pair.Pair[] | undefined = rt.sliceLastChunkMut(pairs, 3); + if (_505 !== undefined) { + pokePairs(12, _505); + _505[0].b = 9; + } + const _514: [rt.ByteSlice, rt.ByteSlice] | undefined = rt.byteSliceSplitAtChecked(rt.byteVecSlice(bytes), 1); + if (_514 !== undefined) { + _514[0].data[_514[0].start] = _514[1].length & 0xff; + rt.byteSliceView(_514[1]).reverse(); + } + const _525: [rt.u16[], rt.u16[]] | undefined = rt.sliceSplitLastChunkMut(words, 4); + if (_525 !== undefined) { + pokeWords(13, _525[0]); + rt.sliceSwap(_525[1], 0, 3); + _525[1][1] = 43981; + } + const _536: [Pair.Pair[], Pair.Pair[]] | undefined = rt.sliceSplitAtMutChecked(pairs, 0); + if (_536 !== undefined) { + pokePairs(14, _536[0]); + pokePairs(15, _536[1]); + } + const _545: [Pair.Pair[], Pair.Pair[]] | undefined = rt.sliceSplitAtMutChecked(pairs, 2); + if (_545 !== undefined) { + rt.idx(_545[1], 0); + const swapped = _545[0][0]; + _545[0][0] = _545[1][0]; + _545[1][0] = swapped; + _545[0][1].a = 3; + } + const _562: [rt.u32[], rt.u32[]] | undefined = rt.sliceSplitLastChunkMut(array, 2); + if (_562 !== undefined) { + _562[1][1] = _562[0].length as rt.u32; + pokeArray(_562[0]); + } + } + rt.iterExtendBytes(out, rt.iterSlice(rt.byteVecView(bytes))); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(words), (_25: rt.u16): rt.u8 => { + const w: rt.u16 = _25; + return (w ^ (w >> 8)) & 0xff; + })); + rt.byteVecPush(out, digestPairs(pairs)); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(array), (_26: rt.u32): rt.u8 => { + const x4: rt.u32 = _26; + return ((x4 ^ (x4 >>> 13)) >>> 0) & 0xff; + })); + } +} + //# sourceMappingURL=slices.ts.map diff --git a/ts/fixtures/lang/expected/splits.ts b/ts/fixtures/lang/expected/splits.ts index ede22ae21..bc608c66d 100644 --- a/ts/fixtures/lang/expected/splits.ts +++ b/ts/fixtures/lang/expected/splits.ts @@ -185,7 +185,7 @@ export function splits(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } rt.byteVecPush(out, rest2.length & 0xff); } else if (_4 === 6) { - const split: [rt.ByteSlice, rt.ByteSlice] | undefined = rt.byteSliceSplitFirstChunk(data, 4); + const split: [rt.ByteSlice, rt.ByteSlice] | undefined = rt.byteSliceSplitAtChecked(data, 4); b5: { if (split !== undefined) { const _227: rt.ByteSlice = split[0]; diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 07071ef2e..c7c1aa117 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -139,6 +139,7 @@ fn cases() -> Vec<(&'static str, Case)> { ("ints::parses", ints::parses), ("strs::edits", strs::edits), ("slices::subslices", slices::subslices), + ("slices::ranges", slices::ranges), ] } diff --git a/ts/fixtures/lang/src/lib.rs b/ts/fixtures/lang/src/lib.rs index 534eb704e..c64efe411 100644 --- a/ts/fixtures/lang/src/lib.rs +++ b/ts/fixtures/lang/src/lib.rs @@ -10,7 +10,8 @@ //! 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, what `Hash` writes //! into `DefaultHasher` and `RandomState`, slices' `windows` and chunks, mutable ones -//! written through, `Vec::drain`, the order of bytes, and ranges of `Bound`s and of the +//! written through, their parts by inclusive and checked ranges and by fixed size, +//! `Vec::drain`, the order of bytes, and ranges of `Bound`s and of the //! crate's own `RangeBounds`. //! //! `harness::run` is the entry point both sides of the differential test run, and diff --git a/ts/fixtures/lang/src/slices.rs b/ts/fixtures/lang/src/slices.rs index 1d4f5e9b2..e414df926 100644 --- a/ts/fixtures/lang/src/slices.rs +++ b/ts/fixtures/lang/src/slices.rs @@ -2,7 +2,8 @@ //! both ends, skipped through, and counted, at sizes past the slice's length, with what //! is written through a mutable chunk landing in the slice; and `Vec::drain` of //! each kind of range, read from both ends, dropped part way, and forgotten, of values -//! that log when they drop. +//! that log when they drop; and a slice's parts by each kind of range and by fixed size, +//! with what is written through a mutable one landing in the slice. use std::cell::RefCell; @@ -571,3 +572,205 @@ pub fn drains(kind: u8, data: &[u8], out: &mut Vec) { drop(items); flush(out); } + +/// What a part read by `$get` gives: its digest, or 0xee for `None`. +macro_rules! got { + ($get:expr, $digest:expr) => { + match $get { + Some(part) => $digest(part), + None => 0xee, + } + }; +} + +/// A slice's parts by an inclusive range, by a pair of `Bound`s, by `get` and `get_mut` of +/// each kind of range, and by fixed size from either end, of bytes and other values, at +/// bounds from the first two bytes, 0xff being `usize::MAX`, which may be out of bounds or +/// backwards, which panics or gives `None`; with what is written through each mutable +/// part landing in what it came from. +pub fn ranges(kind: u8, data: &[u8], out: &mut Vec) { + use std::ops::Bound::{self, Excluded, Included, Unbounded}; + let [a, b, data @ ..] = data else { + return; + }; + let reach = data.len() + 2; + let at = |x: u8| if x == 0xff { usize::MAX } else { x as usize % reach }; + let (a, b) = (at(*a), at(*b)); + let mut bytes = data.to_vec(); + let mut words: Vec = data.iter().map(|&b| b as u16 * 257).collect(); + let mut pairs: Vec = data.iter().map(|&b| Pair { a: b, b: b as u16 * 3 }).collect(); + let mut array = [0u32; 5]; + for (x, &b) in array.iter_mut().zip(data) { + *x = b as u32 * 65599; + } + let digest_array = |s: &[u32]| { + s.iter() + .fold(s.len() as u8, |acc, &x| acc.wrapping_mul(31) ^ (x >> 5) as u8) + }; + match kind % 8 { + 0 => { + out.push(digest(&bytes[a..=b])); + out.push(digest_words(&words[a..=b])); + out.push(digest_pairs(&pairs[..=b])); + out.push(digest_array(&array[a.min(4)..=b.min(4)])); + out.push(digest(&data[..=b])); + } + 1 => { + let part = &mut bytes[a..=b]; + part.reverse(); + part[0] ^= 0x5a; + poke_words(0, &mut words[..=b]); + poke_pairs(1, &mut pairs[a..=b]); + poke_array(&mut array[..=b.min(4)]); + let s = words.as_mut_slice(); + poke_words(2, &mut s[a..=b]); + } + // Each kind of range by `get`, of bytes, other values, and an array. + 2 => { + out.push(got!(bytes.get(a..b), digest)); + out.push(got!(bytes.get(a..=b), digest)); + out.push(got!(bytes.get(..b), digest)); + out.push(got!(bytes.get(..=b), digest)); + out.push(got!(bytes.get(a..), digest)); + out.push(got!(bytes.get(..), digest)); + out.push(got!(data.get(a..b), digest)); + out.push(got!(words.get(a..b), digest_words)); + out.push(got!(words.get(a..=b), digest_words)); + out.push(got!(words.get(..=b), digest_words)); + out.push(got!(pairs.get(a..), digest_pairs)); + out.push(got!(pairs.get(..b), digest_pairs)); + out.push(got!(array.get(a..=b), digest_array)); + out.push(got!(array.get(..), digest_array)); + } + 3 => { + match bytes.get_mut(a..=b) { + Some(part) => part.reverse(), + None => out.push(0xee), + } + if let Some(part) = bytes.get_mut(..b) { + for x in part.iter_mut() { + *x = 0x77; + } + } + match words.get_mut(a..b) { + Some(part) => poke_words(3, part), + None => out.push(0xee), + } + if let Some(part) = words.get_mut(..=b) { + poke_words(4, part); + } + match pairs.get_mut(a..=b) { + Some(part) => poke_pairs(5, part), + None => out.push(0xee), + } + if let Some(part) = pairs.get_mut(a..) { + poke_pairs(6, part); + } + if let Some(part) = array.get_mut(a..=b) { + poke_array(part); + } + } + // An inclusive range stepped past its end by `next`, and one a fold exhausts at its + // end, which then index nothing past it. + 4 => { + let mut stepped = a..=b; + for _ in stepped.by_ref().take(8) {} + let mut folded = a..=b.min(reach); + let _: usize = folded.by_ref().sum(); + out.extend([stepped.is_empty() as u8, folded.is_empty() as u8]); + out.push(got!(words.get(stepped.clone()), digest_words)); + out.push(got!(bytes.get(folded.clone()), digest)); + out.push(got!(pairs.get_mut(folded.clone()), |p: &mut [Pair]| digest_pairs(p))); + poke_words(7, &mut words[folded.clone()]); + out.push(digest(&bytes[stepped])); + out.push(digest(&data[folded])); + } + // A pair of `Bound`s, each kind at either end. + 5 => { + let bound = |x: usize, k: u8| -> Bound { + match k % 3 { + 0 => Included(x), + 1 => Excluded(x), + _ => Unbounded, + } + }; + let (lo, hi) = (bound(a, data.len() as u8), bound(b, kind / 8)); + out.push(got!(bytes.get((lo, hi)), digest)); + out.push(got!(pairs.get((lo, hi)), digest_pairs)); + if let Some(part) = words.get_mut((lo, hi)) { + poke_words(8, part); + } + poke_pairs(9, &mut pairs[(lo, hi)]); + out.push(digest(&bytes[(lo, hi)])); + } + // Fixed-size parts, of none, one, three, and four, from either end. + 6 => { + out.extend(bytes.first_chunk::<0>().map(|c| digest(c))); + out.extend(bytes.first_chunk::<3>().map(|c| digest(c))); + out.extend(data.last_chunk::<1>().map(|c| digest(c))); + out.extend(data.last_chunk::<4>().map(|c| digest(c))); + out.extend(words.first_chunk::<4>().map(|c| digest_words(c))); + out.extend(words.last_chunk::<0>().map(|c| digest_words(c))); + out.extend(pairs.last_chunk::<3>().map(|c| digest_pairs(c))); + if let Some((c, rest)) = bytes.split_first_chunk::<1>() { + out.extend([digest(c), digest(rest)]); + } + if let Some((rest, c)) = bytes.split_last_chunk::<4>() { + out.extend([digest(rest), digest(c)]); + } + if let Some((c, rest)) = words.split_first_chunk::<0>() { + out.extend([digest_words(c), digest_words(rest)]); + } + if let Some((rest, c)) = pairs.split_last_chunk::<3>() { + out.extend([digest_pairs(rest), digest_pairs(c)]); + } + if let Some((rest, c)) = array.split_last_chunk::<5>() { + out.extend([digest_array(rest), digest_array(c)]); + } + } + _ => { + if let Some(c) = bytes.first_chunk_mut::<3>() { + c[0] = c[2].wrapping_add(1); + c.reverse(); + } + if let Some(c) = bytes.last_chunk_mut::<1>() { + c[0] ^= 0xff; + } + if let Some(c) = words.first_chunk_mut::<4>() { + poke_words(10, c); + } + if let Some(c) = words.last_chunk_mut::<0>() { + poke_words(11, c); + } + if let Some(c) = pairs.last_chunk_mut::<3>() { + poke_pairs(12, c); + c[0].b = 9; + } + if let Some((c, rest)) = bytes.split_first_chunk_mut::<1>() { + c[0] = rest.len() as u8; + rest.reverse(); + } + if let Some((rest, c)) = words.split_last_chunk_mut::<4>() { + poke_words(13, rest); + c.swap(0, 3); + c[1] = 0xabcd; + } + if let Some((c, rest)) = pairs.split_first_chunk_mut::<0>() { + poke_pairs(14, c); + poke_pairs(15, rest); + } + if let Some((c, rest)) = pairs.split_first_chunk_mut::<2>() { + std::mem::swap(&mut c[0], &mut rest[0]); + c[1].a = 3; + } + if let Some((rest, c)) = array.split_last_chunk_mut::<2>() { + c[1] = rest.len() as u32; + poke_array(rest); + } + } + } + out.extend(&bytes); + out.extend(words.iter().map(|&w| (w ^ w >> 8) as u8)); + out.push(digest_pairs(&pairs)); + out.extend(array.iter().map(|&x| (x ^ x >> 13) as u8)); +} diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index 1f8c48830..8a173ccee 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -328,16 +328,41 @@ export function sliceRangeMut(s: T[], start: number, end: number = s.length): return sliceView(s, start, end); } +/** `get` of `start..end`: the part, or `undefined` unless it is within the slice. */ +export function sliceGetRange(s: T[], start: number, end: number = s.length): T[] | undefined { + return start <= end && end <= s.length ? s.slice(start, end) : undefined; +} + +/** `get_mut` of `start..end`: the runtime's view of it, or `undefined` as `sliceGetRange`. */ +export function sliceGetRangeMut(s: T[], start: number, end: number = s.length): T[] | undefined { + return start <= end && end <= s.length ? sliceView(s, start, end) : undefined; +} + +/** `last_chunk`: the last `n` elements, or `undefined` if fewer. */ +export function sliceLastChunk(s: T[], n: number): T[] | undefined { + return n > s.length ? undefined : s.slice(s.length - n); +} + +/** `last_chunk_mut`: a view of the last `n` elements, or `undefined` if fewer. */ +export function sliceLastChunkMut(s: T[], n: number): T[] | undefined { + return n > s.length ? undefined : sliceView(s, s.length - n, s.length); +} + +/** `split_last_chunk`: the rest and the last `n` elements, or `undefined` if fewer. */ +export function sliceSplitLastChunk(s: T[], n: number): [T[], T[]] | undefined { + return n > s.length ? undefined : sliceSplitAt(s, s.length - n); +} + +/** `split_last_chunk_mut`: views of the rest and the last `n` elements, or `undefined` if fewer. */ +export function sliceSplitLastChunkMut(s: T[], n: number): [T[], T[]] | undefined { + return n > s.length ? undefined : sliceSplitAtMut(s, s.length - n); +} + /** `split_first`: the first element and the rest, or `undefined` if empty. */ export function sliceSplitFirst(s: T[]): [T, T[]] | undefined { return s.length === 0 ? undefined : [s[0], s.slice(1)]; } -/** `split_first_chunk`: the first `n` elements and the rest, or `undefined` if shorter. */ -export function sliceSplitFirstChunk(s: T[], n: number): [T[], T[]] | undefined { - return s.length < n ? undefined : [s.slice(0, n), s.slice(n)]; -} - /** `split_at`, panicking past the length. */ export function sliceSplitAt(s: T[], n: number): [T[], T[]] { if (n > s.length) panic("mid > len"); @@ -651,6 +676,21 @@ export function byteSliceRange(s: ByteSlice, start: number, end: number = s.leng return new ByteSlice(s.data, s.start + start, end - start); } +/** `get` of `start..end`: the part, or `undefined` unless it is within the slice. */ +export function byteSliceGetRange(s: ByteSlice, start: number, end: number = s.length): ByteSlice | undefined { + return start <= end && end <= s.length ? new ByteSlice(s.data, s.start + start, end - start) : undefined; +} + +/** `last_chunk`: the last `n` bytes, or `undefined` if fewer. */ +export function byteSliceLastChunk(s: ByteSlice, n: number): ByteSlice | undefined { + return n > s.length ? undefined : new ByteSlice(s.data, s.start + s.length - n, n); +} + +/** `split_last_chunk`: the rest and the last `n` bytes, or `undefined` if fewer. */ +export function byteSliceSplitLastChunk(s: ByteSlice, n: number): [ByteSlice, ByteSlice] | undefined { + return n > s.length ? undefined : byteSliceSplitAt(s, s.length - n); +} + /** `split_first`: the first byte and the rest, or `undefined` if empty. */ export function byteSliceSplitFirst(s: ByteSlice): [number, ByteSlice] | undefined { return s.length === 0 ? undefined : [s.data[s.start], new ByteSlice(s.data, s.start + 1, s.length - 1)]; @@ -667,12 +707,6 @@ export function byteSliceSplitLastMut(s: ByteSlice): [Place, ByteSlice] return n < 0 ? undefined : [new AtIndex(s.data, s.start + n), new ByteSlice(s.data, s.start, n)]; } -/** `split_first_chunk`: the first `n` bytes and the rest, or `undefined` if shorter. */ -export function byteSliceSplitFirstChunk(s: ByteSlice, n: number): [ByteSlice, ByteSlice] | undefined { - if (s.length < n) return undefined; - return [new ByteSlice(s.data, s.start, n), new ByteSlice(s.data, s.start + n, s.length - n)]; -} - /** `*r` of a `&[u8; N]`: a copy of its bytes. */ export function byteSliceToArray(s: ByteSlice): Uint8Array { return s.data.slice(s.start, s.start + s.length); diff --git a/ts/runtime/rt/collections.ts b/ts/runtime/rt/collections.ts index 9b19997a4..c1f8862bc 100644 --- a/ts/runtime/rt/collections.ts +++ b/ts/runtime/rt/collections.ts @@ -1366,8 +1366,7 @@ function bounds(r: Bounds): BoundPair { if (r === undefined) return [UNBOUNDED, UNBOUNDED]; if (typeof r === "function") return r(); if (Array.isArray(r)) return r as BoundPair; - // A field test, not `instanceof`, so a bundle without `a..=b` leaves the class out. - if ("exhausted" in r) return [rangeInclusiveStartBound(r), rangeInclusiveEndBound(r)]; + if (inclusive(r)) return [rangeInclusiveStartBound(r), rangeInclusiveEndBound(r)]; const start: RangeBound = "start" in r ? { tag: "Included", _0: r.start } : UNBOUNDED; if (!("end" in r)) return [start, UNBOUNDED]; return [start, { tag: "inclusive" in r ? "Included" : "Excluded", _0: r.end }]; @@ -1956,6 +1955,37 @@ export function boundsRange(r: Bounds, n: number): [number, number] { return [start, end]; } +/** + * A slice's index `r` other than `a..b`, `a..`, `..b`, and `..`, as the start and end of + * the part it reads within `n` elements, panicking as std's `index` does. + */ +export function sliceIndexBounds(r: Bounds, n: number): [number, number] { + if (!inclusive(r)) return boundsRange(r, n); + // std checks `a..=b` by its own fields, not by the bounds it gives. + if (r.hi >= n) sliceIndexFail(r.lo, r.hi, n); + const bounds = sliceGetBounds(r, n); + if (bounds[0] > bounds[1]) sliceIndexFail(bounds[0], bounds[1], n); + return bounds; +} + +/** + * A slice's index `r`, as `sliceIndexBounds` reads it, unchecked: what `get` reads, which + * gives `None` unless the start is at most the end and the end at most `n`. + */ +export function sliceGetBounds(r: Bounds, n: number): [number, number] { + // An `a..=b` iterated to its end starts past it, at `b + 1`, which JS doesn't overflow. + if (inclusive(r)) return [r.exhausted ? r.hi + 1 : r.lo, r.hi + 1]; + const [lo, hi] = bounds(r); + const start = lo.tag === "Unbounded" ? 0 : lo.tag === "Included" ? lo._0 : lo._0 + 1; + const end = hi.tag === "Unbounded" ? n : hi.tag === "Included" ? hi._0 + 1 : hi._0; + return [start, end]; +} + +/** Whether `r` is an `a..=b`: a field test, not `instanceof`, so a bundle without one leaves the class out. */ +function inclusive(r: Bounds): r is RangeInclusive { + return typeof r === "object" && "exhausted" in r; +} + /** std's `slice_index_fail`, which names the end where neither bound is out of order. */ function sliceIndexFail(start: number, end: number, n: number): never { rangeCheck(n, start, end); diff --git a/ts/src/lower/collections.rs b/ts/src/lower/collections.rs index 651d592b7..9b84141d3 100644 --- a/ts/src/lower/collections.rs +++ b/ts/src/lower/collections.rs @@ -10,6 +10,7 @@ use rustc_middle::ty::{self, Instance, Ty}; use rustc_span::Span; +use super::Translator; use super::body::Body; use super::library::{self, Call, Std}; use super::num::Int; @@ -1283,8 +1284,19 @@ pub fn bounds<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, range: Expr) format!("passing `{ty}`, which drops, to `{owner}::{name}`, which is not supported yet"), ); } - let pair = |t: &Ty<'tcx>| b.t.std_of(*t) == Some(Std::Bound); - match (ty.kind(), b.t.std_of(ty)) { + // Each instance decides for a range it is generic over. + if plain_bounds(b.t, ty) || b.t.deferred(ty) { + return range; + } + let args = tcx.mk_args(&[ty.into(), target.into()]); + let start = b.fn_value(trait_fn(tcx, "RangeBounds", "start_bound"), args, span); + let end = b.fn_value(trait_fn(tcx, "RangeBounds", "end_bound"), args, span); + Expr::rt("boundsOf", vec![range, start, end]) +} + +/// Whether an `rt.Bounds` reads `ty` as it is: std's range types and a pair of `Bound`s. +pub fn plain_bounds<'tcx>(t: &Translator<'_, 'tcx>, ty: Ty<'tcx>) -> bool { + match (ty.kind(), t.std_of(ty)) { ( _, Some( @@ -1295,16 +1307,10 @@ pub fn bounds<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, range: Expr) | Std::RangeToInclusive | Std::RangeFull, ), - ) => return range, - (ty::Tuple(tys), _) if tys.len() == 2 && tys.iter().all(|t| pair(&t)) => return range, - // Each instance decides. - _ if b.t.deferred(ty) => return range, - _ => {} + ) => true, + (ty::Tuple(tys), _) => tys.len() == 2 && tys.iter().all(|b| t.std_of(b) == Some(Std::Bound)), + _ => false, } - let args = tcx.mk_args(&[ty.into(), target.into()]); - let start = b.fn_value(trait_fn(tcx, "RangeBounds", "start_bound"), args, span); - let end = b.fn_value(trait_fn(tcx, "RangeBounds", "end_bound"), args, span); - Expr::rt("boundsOf", vec![range, start, end]) } /// Which of its inputs is the range `call` takes, and the `T` of the `RangeBounds` it diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 303a24d04..cf56fd51c 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -1383,14 +1383,37 @@ fn mapping<'tcx>( ("ChunksExact" | "RChunksExact", "remainder") | ("ChunksExactMut" | "RChunksExactMut", "into_remainder") => { Expr::rt("partsRemainder", args) } - ("slice", "split_first_chunk") => { + // The first `N` elements are `get(..N)`, and split off, `split_at_checked(N)`. A part + // of bytes is a view already, and one of other values lent mutably the runtime's view. + ( + "slice", + "first_chunk" + | "first_chunk_mut" + | "last_chunk" + | "last_chunk_mut" + | "split_first_chunk" + | "split_first_chunk_mut" + | "split_last_chunk" + | "split_last_chunk_mut", + ) => { let n = gargs.consts().next()?.try_to_target_usize(tcx)?; + let (of, name) = match is_u8(targ(gargs, 0)) { + true => ("byteSlice", name.strip_suffix("_mut").unwrap_or(&name)), + false => ("slice", name.as_str()), + }; let mut values = args; - values.push(Expr::lit(n.to_string())); - match is_u8(targ(gargs, 0)) { - true => Expr::rt("byteSliceSplitFirstChunk", values), - false => Expr::rt("sliceSplitFirstChunk", values), + if name.starts_with("first") { + values.push(Expr::lit("0")); } + values.push(Expr::lit(n.to_string())); + let name = match name { + "first_chunk" => "get_range", + "first_chunk_mut" => "get_range_mut", + "split_first_chunk" => "split_at_checked", + "split_first_chunk_mut" => "split_at_mut_checked", + name => name, + }; + rt2(values, of, &super::camel(name)) } // A slice of the one value. ("raw", "from_ref") if std_path(tcx, call.def_id) == ["slice", "raw", "from_ref"] => { diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 821db3048..ad3445f7a 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -684,13 +684,17 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } // Indexing, whose result a `&mut` reads in place. ("Index" | "IndexMut", "index" | "index_mut") => self.index(&name, gargs, args, dest, span, out), - // Out of bounds is undefined, so the checked index's panic is one outcome of it. - ("slice", "get_unchecked" | "get_unchecked_mut") => { + // Out of bounds is undefined, so the checked index's panic is one outcome of it; a + // part by a range is checked as indexing by it is, giving `None` where that panics. + ("slice", "get_unchecked" | "get_unchecked_mut" | "get" | "get_mut") + if name.starts_with("get_unchecked") || Int::of(targ(1)?).is_none() => + { let slice = ty::Ty::new_slice(tcx, targ(0)?); let gargs = tcx.mk_args(&[slice.into(), targ(1)?.into()]); let name = match name.as_str() { "get_unchecked" => "index", - _ => "index_mut", + "get_unchecked_mut" => "index_mut", + name => name, }; self.index(name, gargs, args, dest, span, out) } @@ -1305,7 +1309,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } - /// `container[index]`, or a slice of it by a range, which a reference reads in place. + /// `container[index]`, or a slice of it by a range, which a reference reads in place; or + /// `get` or `get_mut` of a slice by a range. fn index( &mut self, name: &str, @@ -1366,9 +1371,18 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { Some(Some((place, true))) } None => { + let get = matches!(name, "get" | "get_mut"); + let lent = matches!(name, "index_mut" | "get_mut"); // The range's bounds are taken apart before the slice is read, while they are - // still held back. - let (start, end) = self.range_bounds(&args[1].node, index_ty, span, out)?; + // still held back. Any other range, as an `rt.Bounds`, is checked by the + // runtime, as std checks its own fields, into a start and end. + let bounds = match self.range_bounds(&args[1].node, index_ty, span, out) { + Some(bounds) => Ok(bounds), + None if crate::lower::collections::plain_bounds(self.b.t, index_ty) => { + Err(self.operand(&args[1].node, span, out)) + } + None => return None, + }; let base = match container.kind() { ty::Adt(..) => library::vec_view(base, elem_ty), _ => base, @@ -1376,18 +1390,33 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { // All of a mutable slice of other values is the slice itself. let full = matches!(index_ty.kind(), ty::Adt(adt, _) if self.tcx.item_name(adt.did()).as_str() == "RangeFull"); - if full && !bytes && name == "index_mut" { + if full && !bytes && lent { return Some(Some((base, true))); } let base = self.path(base, "slice", out); + let (start, end) = match bounds { + Ok(bounds) => bounds, + Err(range) => { + let length = super::slice_member(base.clone(), "length"); + let checked = match get { + true => "sliceGetBounds", + false => "sliceIndexBounds", + }; + let pair = self.path(Expr::rt(checked, vec![range, length]), "bounds", out); + (pair.clone().index(Expr::lit("0")), Some(pair.index(Expr::lit("1")))) + } + }; let mut values = vec![base, start]; values.extend(end); // A range of bytes is a view already, and one of other values lent mutably the // runtime's view, as a JS array has none of its own. - let range = match (bytes, name) { - (true, _) => "byteSliceRange", - (false, "index_mut") => "sliceRangeMut", - (false, _) => "sliceRange", + let range = match (bytes, lent, get) { + (true, _, false) => "byteSliceRange", + (true, _, true) => "byteSliceGetRange", + (false, true, false) => "sliceRangeMut", + (false, true, true) => "sliceGetRangeMut", + (false, false, false) => "sliceRange", + (false, false, true) => "sliceGetRange", }; Some(Some((Expr::rt(range, values), true))) }