From f9bb5404eb2cdcf8dc37b22cc1e82d40e27e1997 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:13:59 -0700 Subject: [PATCH 1/3] chore(quest): claim quest/m2/ts-iter-nth.md Quest-Claim: 59cbd1e2fd07e33d From b380ed509a1e803c85a12c5b28c7f7bde432c6de Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:48:37 -0700 Subject: [PATCH 2/3] wip: skips through the dispatchers --- ts/fixtures/lang/expected/chunks.ts | 2 +- ts/fixtures/lang/expected/core/option.ts | 7 + ts/fixtures/lang/expected/harness.ts | 8 +- ts/fixtures/lang/expected/iters.ts | 424 ++++++++++++++++++++++- ts/fixtures/lang/expected/shapes.ts | 2 +- ts/fixtures/lang/src/harness.rs | 5 +- ts/fixtures/lang/src/iters.rs | 67 ++++ ts/fixtures/task/expected/drops/iters.ts | 38 +- ts/runtime/rt/iter.ts | 291 +++++----------- ts/src/lower/iter.rs | 58 ++-- 10 files changed, 638 insertions(+), 264 deletions(-) diff --git a/ts/fixtures/lang/expected/chunks.ts b/ts/fixtures/lang/expected/chunks.ts index 4b2eeff47..415e41dc2 100644 --- a/ts/fixtures/lang/expected/chunks.ts +++ b/ts/fixtures/lang/expected/chunks.ts @@ -170,7 +170,7 @@ export function chunks(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } _234.data[_234.start] = _234.data[_234.start + 1]; } - const copies: Uint8Array[] = rt.iterToArray(rt.iterMap(rt.iterMap(rt.iterSlice(pairs), rt.byteSliceFrom), rt.byteSliceToArray)); + const copies: Uint8Array[] = rt.iterToArray(rt.iterCopied(rt.iterMap(rt.iterSlice(pairs), rt.byteSliceFrom), rt.byteSliceToArray)); rt.iterExtendBytes(out, rt.iterChain(rt.iterMap(rt.iterMap(rt.iterSlice(pairs), rt.byteSliceFrom), (p: rt.ByteSlice): rt.u8 => { return p.data[p.start]; }), rt.iterMap(rt.iterMap(rt.iterSlice(copies), rt.byteSliceFrom), (p2: rt.ByteSlice): rt.u8 => { diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts index b1e3cfd29..d4e9229d9 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -324,6 +324,13 @@ export function mapOr$Option_u8_usize_shares_closure1(self: rt.u8 | undefined, d return f(self); } +export function mapOr$Option_u8s_u8_skips_closure44(self: Uint8Array | undefined, default_: rt.u8, f: (a0: Uint8Array) => rt.u8): rt.u8 { + 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 832a9c971..675abdb19 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -10,7 +10,7 @@ import { durations } from "./durations.ts"; import { ints, strings, derived, written, panics } from "./fmt.ts"; import { methods } from "./generics.ts"; import { u8Op, u16Op, u32Op, u64Op, u128Op, usizeOp, i8Op, i16Op, i32Op, i64Op, i128Op, isizeOp, i8Neg, i16Neg, i32Neg, i64Neg, i128Neg, isizeNeg, cast, convert } from "./ints.ts"; -import { adaptors, consumers, ranges, options, own, values } from "./iters.ts"; +import { adaptors, consumers, skips, ranges, options, own, values } from "./iters.ts"; import { keys } from "./keys.ts"; import { refs } from "./refs.ts"; import { copies, order, discriminants, loops, patterns, closures, library, flows } from "./shapes.ts"; @@ -26,7 +26,7 @@ export function run(input: rt.ByteSlice): rt.ByteVec { const _10: [rt.u8, rt.u8] = [input.data[input.start], input.data[input.start + 1]]; const op: rt.u8 = _10[0]; const kind: rt.u8 = _10[1]; - const _14: rt.u8 = rt.u8Rem(op, 51); + const _14: rt.u8 = rt.u8Rem(op, 52); if (_14 === 0) { u8Op(kind, new rt.ByteSlice(input.data, input.start + 2, input.length - 2), out); } else if (_14 === 1) { @@ -144,8 +144,10 @@ export function run(input: rt.ByteSlice): rt.ByteVec { combinators(kind, new rt.ByteSlice(input.data, input.start + 2, input.length - 2), out); } else if (_14 === 49) { splits(kind, new rt.ByteSlice(input.data, input.start + 2, input.length - 2), out); - } else { + } else if (_14 === 50) { refs(new rt.ByteSlice(input.data, input.start + 2, input.length - 2), out); + } else { + skips(kind, new rt.ByteSlice(input.data, input.start + 2, input.length - 2), out); } return out; } diff --git a/ts/fixtures/lang/expected/iters.ts b/ts/fixtures/lang/expected/iters.ts index 9f69940f2..d60fa1c8a 100644 --- a/ts/fixtures/lang/expected/iters.ts +++ b/ts/fixtures/lang/expected/iters.ts @@ -1,8 +1,8 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$Bumped } from "./lib.ts"; -import { unwrapOr$Option_i64, unwrapOr$Option_u64, unwrapOr$Option_u8, unwrapOr$Option_usize_u8, map$Option_u8_u8_options_closure3_closure0, mapOr$Option_Vec_u16_u8_consumers_closure23, mapOr$Option_u8_u8_options_closure5, mapOr$Option_usize_u8_consumers_closure8, mapOr$Option_usize_u8_u8_ranges_closure0 } from "./core/option.ts"; +import { copy$Bumped, copy$u8_u8 } from "./lib.ts"; +import { unwrapOr$Option_i64, unwrapOr$Option_u64, unwrapOr$Option_u8, unwrapOr$Option_usize_u8, map$Option_u8_u8_options_closure3_closure0, mapOr$Option_Vec_u16_u8_consumers_closure23, mapOr$Option_u8_u8_options_closure5, mapOr$Option_u8_u8_u8_btree_maps_closure0, mapOr$Option_u8_usize_shares_closure1, mapOr$Option_u8s_u8_skips_closure44, mapOr$Option_usize_u8_consumers_closure8, mapOr$Option_usize_u8_u8_ranges_closure0 } from "./core/option.ts"; import * as Bumped from "./iters.Bumped.ts"; import * as Countdown from "./iters.Countdown.ts"; import * as Doubled from "./iters.Doubled.ts"; @@ -125,7 +125,7 @@ export function adaptors(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const b3: rt.u8 = _2; return Uint8Array.of(b3, ~b3 & 0xff); })); - const copies: Uint8Array[] = rt.iterToArray(rt.iterMap(rt.iterMap(rt.iterSlice(pairs), rt.byteSliceFrom), rt.byteSliceToArray)); + const copies: Uint8Array[] = rt.iterToArray(rt.iterCopied(rt.iterMap(rt.iterSlice(pairs), rt.byteSliceFrom), rt.byteSliceToArray)); if (!((copies.length === 0))) { const _174: rt.ByteSlice = rt.byteSliceFrom(copies[rt.idx(copies, 0)]); _174.data[_174.start] = 85; @@ -260,7 +260,7 @@ export function consumers(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi const it: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); const _148: rt.Iter = it; const _150: rt.usize = rt.usizeRem(data.length, 3); - rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterToOption(rt.iterTake(rt.iterBorrow(_148), _150).nthBackItem(1)), 187)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterNthBack(rt.iterTake(rt.iterBorrow(_148), _150), 1), 187)); rt.byteVecPush(out, it.len() & 0xff); const _163: rt.Iter = it; const _165: rt.usize = rt.usizeRem(data.length, 5); @@ -310,6 +310,418 @@ export function rotateFree$RotateFree_u8(self: rt.u8): rt.u8 { return ((self << 1) & 0xff) | (self >> 7); } +/** + * `nth` and `nth_back` through each adaptor, of a source whose reads `by_ref` or + * `inspect` shows: each reads on past a `take`'s limit, or stops at it, as std's does. + */ +export function skips(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + let item!: rt.u8 | undefined; + let item2!: rt.u8 | undefined; + let item3!: rt.u8 | undefined; + let item4!: rt.u8 | undefined; + let item5!: rt.u8 | undefined; + let item6!: rt.u8 | undefined; + let item7!: rt.u8 | undefined; + let item8!: rt.u8 | undefined; + let item9!: rt.u8 | undefined; + let item10!: rt.u8 | undefined; + let item11!: rt.u8 | undefined; + let item12!: rt.u8 | undefined; + let item13!: rt.u8 | undefined; + let item14!: rt.u8 | undefined; + let item15!: rt.u8 | undefined; + let item16!: rt.u8 | undefined; + let item17!: rt.u8 | undefined; + let item18!: rt.u8 | undefined; + let item19!: rt.u8 | undefined; + let item20!: rt.u8 | undefined; + let item21!: [rt.usize, rt.u8] | undefined; + let item22!: [rt.usize, rt.u8] | undefined; + let item23!: rt.u8 | undefined; + let item24!: rt.u8 | undefined; + let item25!: rt.u8 | undefined; + let item26!: rt.u8 | undefined; + let item27!: [rt.u8, rt.u8] | undefined; + let item28!: Uint8Array | undefined; + const n: rt.usize = mapOr$Option_u8_usize_shares_closure1(rt.byteSliceFirst(data), 0, (_2: rt.u8): rt.usize => { + return rt.usizeRem(_2 as rt.usize, 4); + }); + const limit: rt.usize = mapOr$Option_u8_usize_shares_closure1(rt.byteSliceGet(data, 1), 0, (_22: rt.u8): rt.usize => { + return rt.usizeRem(_22 as rt.usize, 3); + }); + const back: boolean = (kind & 1) === 1; + const _10: rt.u8 = rt.u8Rem(rt.u8Div(kind, 2), 14); + if (_10 === 0) { + const rest: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const it: rt.Iter = rt.iterFuse(rt.iterTake(rt.iterBorrow(rest), limit)); + if (!back) { + item = rt.iterNth(it, n); + } else { + item = rt.iterNthBack(it, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item, 238, (_264: rt.u8): rt.u8 => { + return _264; + })); + rt.byteVecPush(out, rest.len() & 0xff); + const log: rt.ByteVec = new rt.ByteVec(); + const it2: rt.Iter = rt.iterFuse(rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_267: rt.u8): void => { + rt.byteVecPush(log, _267); + }), limit)); + if (!back) { + item2 = rt.iterNth(it2, n); + } else { + item2 = rt.iterNthBack(it2, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item2, 238, (_268: rt.u8): rt.u8 => { + return _268; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log)); + } else if (_10 === 1) { + const rest2: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const src3: rt.Iter = rest2; + const _50: rt.usize = rt.usizeAdd(limit, 1); + const it3: rt.Iter = rt.iterSkip(rt.iterTake(rt.iterBorrow(src3), _50), 1); + if (!back) { + item3 = rt.iterNth(it3, n); + } else { + item3 = rt.iterNthBack(it3, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item3, 238, (_261: rt.u8): rt.u8 => { + return _261; + })); + rt.byteVecPush(out, rest2.len() & 0xff); + const log2: rt.ByteVec = new rt.ByteVec(); + const it4: rt.Iter = rt.iterSkip(rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_262: rt.u8): void => { + rt.byteVecPush(log2, _262); + }), rt.usizeAdd(limit, 1)), 1); + if (!back) { + item4 = rt.iterNth(it4, n); + } else { + item4 = rt.iterNthBack(it4, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item4, 238, (_263: rt.u8): rt.u8 => { + return _263; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log2)); + } else if (_10 === 2) { + const rest3: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const it5: rt.Iter = rt.iterChain(rt.iterTake(rt.iterBorrow(rest3), limit), rt.iterSlice(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.of(17))))); + if (!back) { + item5 = rt.iterNth(it5, n); + } else { + item5 = rt.iterNthBack(it5, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item5, 238, (_255: rt.u8): rt.u8 => { + return _255; + })); + rt.byteVecPush(out, rest3.len() & 0xff); + const log3: rt.ByteVec = new rt.ByteVec(); + const it6: rt.Iter = rt.iterChain(rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_258: rt.u8): void => { + rt.byteVecPush(log3, _258); + }), limit), rt.iterSlice(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.of(17))))); + if (!back) { + item6 = rt.iterNth(it6, n); + } else { + item6 = rt.iterNthBack(it6, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item6, 238, (_260: rt.u8): rt.u8 => { + return _260; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log3)); + } else if (_10 === 3) { + const rest4: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const src7: rt.Iter = rest4; + const it7: rt.Iter = rt.iterChain(rt.iterSlice(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.of(17)))), rt.iterTake(rt.iterBorrow(src7), limit)); + if (!back) { + item7 = rt.iterNth(it7, n); + } else { + item7 = rt.iterNthBack(it7, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item7, 238, (_252: rt.u8): rt.u8 => { + return _252; + })); + rt.byteVecPush(out, rest4.len() & 0xff); + const log4: rt.ByteVec = new rt.ByteVec(); + const src8: rt.Iter = rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_253: rt.u8): void => { + rt.byteVecPush(log4, _253); + }); + const it8: rt.Iter = rt.iterChain(rt.iterSlice(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.of(17)))), rt.iterTake(src8, limit)); + if (!back) { + item8 = rt.iterNth(it8, n); + } else { + item8 = rt.iterNthBack(it8, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item8, 238, (_254: rt.u8): rt.u8 => { + return _254; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log4)); + } else if (_10 === 4) { + const rest5: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const src9: rt.Iter = rest5; + const _159: rt.usize = rt.usizeAdd(limit, 1); + const it9: rt.Iter = rt.iterStepBy(rt.iterTake(rt.iterBorrow(src9), _159), 2); + if (!back) { + item9 = rt.iterNth(it9, n); + } else { + item9 = rt.iterNthBack(it9, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item9, 238, (_245: rt.u8): rt.u8 => { + return _245; + })); + rt.byteVecPush(out, rest5.len() & 0xff); + const log5: rt.ByteVec = new rt.ByteVec(); + const it10: rt.Iter = rt.iterStepBy(rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_246: rt.u8): void => { + rt.byteVecPush(log5, _246); + }), rt.usizeAdd(limit, 1)), 2); + if (!back) { + item10 = rt.iterNth(it10, n); + } else { + item10 = rt.iterNthBack(it10, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item10, 238, (_251: rt.u8): rt.u8 => { + return _251; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log5)); + } else if (_10 === 5) { + const rest6: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const it11: rt.Peekable = rt.iterPeekable(rt.iterTake(rt.iterBorrow(rest6), limit)); + if (!back) { + item11 = rt.iterNth(it11, n); + } else { + item11 = rt.iterNthBack(it11, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item11, 238, (_240: rt.u8): rt.u8 => { + return _240; + })); + rt.byteVecPush(out, rest6.len() & 0xff); + const log6: rt.ByteVec = new rt.ByteVec(); + const it12: rt.Peekable = rt.iterPeekable(rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_241: rt.u8): void => { + rt.byteVecPush(log6, _241); + }), limit)); + if (!back) { + item12 = rt.iterNth(it12, n); + } else { + item12 = rt.iterNthBack(it12, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item12, 238, (_244: rt.u8): rt.u8 => { + return _244; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log6)); + } else if (_10 === 6) { + const rest7: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const src13: rt.Iter = rest7; + const _226: rt.usize = rt.usizeAdd(limit, 1); + const it14: rt.Peekable = rt.iterPeekable(rt.iterTake(rt.iterBorrow(src13), _226)); + rt.peekablePeek(it14); + const it13: rt.Peekable = it14; + if (!back) { + item13 = rt.iterNth(it13, n); + } else { + item13 = rt.iterNthBack(it13, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item13, 238, (_233: rt.u8): rt.u8 => { + return _233; + })); + rt.byteVecPush(out, rest7.len() & 0xff); + const log7: rt.ByteVec = new rt.ByteVec(); + const it16: rt.Peekable = rt.iterPeekable(rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_236: rt.u8): void => { + rt.byteVecPush(log7, _236); + }), rt.usizeAdd(limit, 1))); + rt.peekablePeek(it16); + const it15: rt.Peekable = it16; + if (!back) { + item14 = rt.iterNth(it15, n); + } else { + item14 = rt.iterNthBack(it15, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item14, 238, (_239: rt.u8): rt.u8 => { + return _239; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log7)); + } else if (_10 === 7) { + const rest8: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const it17: rt.Iter = rt.iterFlatten(rt.iterOnce(rt.iterTake(rt.iterBorrow(rest8), limit))); + if (!back) { + item15 = rt.iterNth(it17, n); + } else { + item15 = rt.iterNthBack(it17, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item15, 238, (_230: rt.u8): rt.u8 => { + return _230; + })); + rt.byteVecPush(out, rest8.len() & 0xff); + const log8: rt.ByteVec = new rt.ByteVec(); + const it18: rt.Iter = rt.iterFlatten(rt.iterOnce(rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_231: rt.u8): void => { + rt.byteVecPush(log8, _231); + }), limit))); + if (!back) { + item16 = rt.iterNth(it18, n); + } else { + item16 = rt.iterNthBack(it18, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item16, 238, (_232: rt.u8): rt.u8 => { + return _232; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log8)); + } else if (_10 === 8) { + const rest9: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const it19: rt.Iter = rt.iterTake(rt.iterBorrow(rest9), limit); + if (!back) { + item17 = rt.iterNth(it19, n); + } else { + item17 = rt.iterNthBack(it19, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item17, 238, (b18: rt.u8): rt.u8 => { + return b18; + })); + rt.byteVecPush(out, rest9.len() & 0xff); + const log9: rt.ByteVec = new rt.ByteVec(); + const it20: rt.Iter = rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_229: rt.u8): void => { + rt.byteVecPush(log9, _229); + }), limit); + if (!back) { + item18 = rt.iterNth(it20, n); + } else { + item18 = rt.iterNthBack(it20, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item18, 238, (b20: rt.u8): rt.u8 => { + return b20; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log9)); + } else if (_10 === 9) { + const rest10: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const it21: rt.Iter = rt.iterCloned(rt.iterTake(rt.iterBorrow(rest10), limit)); + if (!back) { + item19 = rt.iterNth(it21, n); + } else { + item19 = rt.iterNthBack(it21, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item19, 238, (b15: rt.u8): rt.u8 => { + return b15; + })); + rt.byteVecPush(out, rest10.len() & 0xff); + const log10: rt.ByteVec = new rt.ByteVec(); + const it22: rt.Iter = rt.iterCloned(rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_224: rt.u8): void => { + rt.byteVecPush(log10, _224); + }), limit)); + if (!back) { + item20 = rt.iterNth(it22, n); + } else { + item20 = rt.iterNthBack(it22, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item20, 238, (b17: rt.u8): rt.u8 => { + return b17; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log10)); + } else if (_10 === 10) { + const rest11: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const it23: rt.Iter<[rt.usize, rt.u8]> = rt.iterEnumerate(rt.iterTake(rt.iterBorrow(rest11), limit)); + if (!back) { + item21 = rt.iterNth(it23, n); + } else { + item21 = rt.iterNthBack(it23, n); + } + rt.byteVecPush(out, mapOr$Option_usize_u8_u8_ranges_closure0(item21, 238, (_221: [rt.usize, rt.u8]): rt.u8 => { + return _221[1] ^ (_221[0] & 0xff); + })); + rt.byteVecPush(out, rest11.len() & 0xff); + const log11: rt.ByteVec = new rt.ByteVec(); + const it24: rt.Iter<[rt.usize, rt.u8]> = rt.iterEnumerate(rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_222: rt.u8): void => { + rt.byteVecPush(log11, _222); + }), limit)); + if (!back) { + item22 = rt.iterNth(it24, n); + } else { + item22 = rt.iterNthBack(it24, n); + } + rt.byteVecPush(out, mapOr$Option_usize_u8_u8_ranges_closure0(item22, 238, (_223: [rt.usize, rt.u8]): rt.u8 => { + return _223[1] ^ (_223[0] & 0xff); + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log11)); + } else if (_10 === 11) { + const rest12: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const it25: rt.Iter = rt.iterRev(rt.iterTake(rt.iterBorrow(rest12), limit)); + if (!back) { + item23 = rt.iterNth(it25, n); + } else { + item23 = rt.iterNthBack(it25, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item23, 238, (_217: rt.u8): rt.u8 => { + return _217; + })); + rt.byteVecPush(out, rest12.len() & 0xff); + const log12: rt.ByteVec = new rt.ByteVec(); + const it26: rt.Iter = rt.iterRev(rt.iterTake(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_219: rt.u8): void => { + rt.byteVecPush(log12, _219); + }), limit)); + if (!back) { + item24 = rt.iterNth(it26, n); + } else { + item24 = rt.iterNthBack(it26, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item24, 238, (_220: rt.u8): rt.u8 => { + return _220; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log12)); + } else if (_10 === 12) { + const rest13: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); + const src25: rt.Iter = rest13; + const it27: rt.Iter = rt.iterChain(rt.iterSlice(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.of(17)))), rt.iterFuse(rt.iterTake(rt.iterBorrow(src25), limit))); + if (!back) { + item25 = rt.iterNth(it27, n); + } else { + item25 = rt.iterNthBack(it27, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item25, 238, (_212: rt.u8): rt.u8 => { + return _212; + })); + rt.byteVecPush(out, rest13.len() & 0xff); + const log13: rt.ByteVec = new rt.ByteVec(); + const src26: rt.Iter = rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_213: rt.u8): void => { + rt.byteVecPush(log13, _213); + }); + const it28: rt.Iter = rt.iterChain(rt.iterSlice(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.of(17)))), rt.iterFuse(rt.iterTake(src26, limit))); + if (!back) { + item26 = rt.iterNth(it28, n); + } else { + item26 = rt.iterNthBack(it28, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(item26, 238, (_214: rt.u8): rt.u8 => { + return _214; + })); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(log13)); + } else { + const rest14: rt.Iter<[rt.u8, rt.u8]> = rt.iterSlice(rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_25: rt.u8): [rt.u8, rt.u8] => { + const b3: rt.u8 = _25; + return [b3, ~b3 & 0xff] as [rt.u8, rt.u8]; + }))); + const it29: rt.Iter<[rt.u8, rt.u8]> = rt.iterCopied(rt.iterTake(rt.iterBorrow(rest14), limit), copy$u8_u8); + if (!back) { + item27 = rt.iterNth(it29, n); + } else { + item27 = rt.iterNthBack(it29, n); + } + rt.byteVecPush(out, mapOr$Option_u8_u8_u8_btree_maps_closure0(item27, 238, (_28: [rt.u8, rt.u8]): rt.u8 => { + return _28[0] ^ _28[1]; + })); + rt.byteVecPush(out, rest14.len() & 0xff); + const rest15: rt.Iter = rt.iterMap(rt.iterSlice(rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_29: rt.u8): Uint8Array => { + const b5: rt.u8 = _29; + return Uint8Array.of(b5, ~b5 & 0xff); + }))), rt.byteSliceFrom); + const it30: rt.Iter = rt.iterCopied(rt.iterTake(rt.iterBorrow(rest15), limit), rt.byteSliceToArray); + if (!back) { + item28 = rt.iterNth(it30, n); + } else { + item28 = rt.iterNthBack(it30, n); + } + rt.byteVecPush(out, mapOr$Option_u8s_u8_skips_closure44(item28, 238, (_211: Uint8Array): rt.u8 => { + return _211[0]; + })); + rt.byteVecPush(out, rest15.len() & 0xff); + } +} + /** Ranges as values and as iterators. */ export function ranges(data: rt.ByteSlice, out: rt.ByteVec): void { const a: rt.u8 = unwrapOr$Option_u8(rt.byteSliceFirst(data), 0); @@ -352,7 +764,7 @@ export function ranges(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, rt.rangeInclusiveContains(near, 255) ? 1 : 0); rt.byteVecPush(out, rt.rangeInclusiveContains(near, 100) ? 1 : 0); const low: rt.RangeInclusive = new rt.RangeInclusive(0, b, rt.u8Step); - rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterToOption(low.nthBackItem(rt.usizeRem(a as rt.usize, 16))), 238)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterNthBack(low, rt.usizeRem(a as rt.usize, 16)), 238)); rt.byteVecPush(out, rt.rangeInclusiveEnd(low)); rt.byteVecPush(out, rt.rangeInclusiveContains(low, rt.u8Div(b, 2)) ? 1 : 0); const reversed: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.u8Step); @@ -658,7 +1070,7 @@ export function values(data: rt.ByteSlice, out: rt.ByteVec): void { rt.iterExtendBytes(out, rt.iterMap(rt.iterMap(rt.iterSlice(bumps), Bumped.clone$Clone), (b5: Bumped.Bumped): rt.u8 => { return b5._0; })); - rt.iterExtendBytes(out, rt.iterMap(rt.iterMap(rt.iterSlice(bumps), copy$Bumped), (b6: Bumped.Bumped): rt.u8 => { + rt.iterExtendBytes(out, rt.iterMap(rt.iterCopied(rt.iterSlice(bumps), copy$Bumped), (b6: Bumped.Bumped): rt.u8 => { return b6._0; })); rt.iterExtendBytes(out, rt.iterMap(rt.iterMap(rt.iterSlice(rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_23: rt.u8): Wrapper.Wrapper => { diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 4e9f1cb1e..3288bdbff 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -355,7 +355,7 @@ export function shares(data: rt.ByteSlice, out: rt.ByteVec): void { lenses.push(copy$Lens(lens)); const _114: rt.Iter = rt.iterSlice([lens]); rt.iterExtend(lenses, rt.iterMap(_114, copy$Lens)); - const iter4: rt.Iter = rt.iterMap(rt.iterSlice(lenses), copy$Lens); + const iter4: rt.Iter = rt.iterCopied(rt.iterSlice(lenses), copy$Lens); while (true) { const _124: Lens.Lens | rt.Done = iter4.next(); if (_124 === rt.DONE) { diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 4e8dd0de3..03d1729b4 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -22,7 +22,7 @@ pub fn run(input: &[u8]) -> Vec { return out; }; let (op, kind) = (*op, *kind); - match op % 51 { + match op % 52 { 0 => ints::u8_op(kind, data, &mut out), 1 => ints::u16_op(kind, data, &mut out), 2 => ints::u32_op(kind, data, &mut out), @@ -83,7 +83,8 @@ pub fn run(input: &[u8]) -> Vec { 47 => durations::durations(kind, data, &mut out), 48 => combinators::combinators(kind, data, &mut out), 49 => splits::splits(kind, data, &mut out), - _ => refs::refs(data, &mut out), + 50 => refs::refs(data, &mut out), + _ => iters::skips(kind, data, &mut out), } out } diff --git a/ts/fixtures/lang/src/iters.rs b/ts/fixtures/lang/src/iters.rs index 42f821f7e..272e49a4d 100644 --- a/ts/fixtures/lang/src/iters.rs +++ b/ts/fixtures/lang/src/iters.rs @@ -221,6 +221,73 @@ impl RotateFree for u8 { } } +/// `nth` and `nth_back` through each adaptor, of a source whose reads `by_ref` or +/// `inspect` shows: each reads on past a `take`'s limit, or stops at it, as std's does. +pub fn skips(kind: u8, data: &[u8], out: &mut Vec) { + let n = data.first().map_or(0, |&b| b as usize % 4); + let limit = data.get(1).map_or(0, |&b| b as usize % 3); + let back = kind & 1 == 1; + // `nth` or `nth_back` of `$it`, as a byte by `$f`. + macro_rules! skip { + ($it:expr, $f:expr) => {{ + let mut it = $it; + let item = if back { it.nth_back(n) } else { it.nth(n) }; + out.push(item.map_or(0xee, $f)); + }}; + } + // `skip!` of `$adapt` over a `by_ref` source, then over an `inspect`ed one, and what each read. + macro_rules! sources { + (|$src:ident| $adapt:expr, $f:expr) => {{ + let mut rest = data.iter(); + { + let $src = rest.by_ref(); + skip!($adapt, $f); + } + out.push(rest.len() as u8); + let mut log = Vec::new(); + { + let $src = data.iter().inspect(|&&b| log.push(b)); + skip!($adapt, $f); + } + out.extend_from_slice(&log); + }}; + } + match (kind / 2) % 14 { + 0 => sources!(|src| src.take(limit).fuse(), |&b| b), + 1 => sources!(|src| src.take(limit + 1).skip(1), |&b| b), + 2 => sources!(|src| src.take(limit).chain([0x11].iter()), |&b| b), + 3 => sources!(|src| [0x11].iter().chain(src.take(limit)), |&b| b), + 4 => sources!(|src| src.take(limit + 1).step_by(2), |&b| b), + 5 => sources!(|src| src.take(limit).peekable(), |&b| b), + 6 => sources!( + |src| { + let mut it = src.take(limit + 1).peekable(); + it.peek(); + it + }, + |&b| b + ), + 7 => sources!(|src| std::iter::once(src.take(limit)).flatten(), |&b| b), + 8 => sources!(|src| src.take(limit).copied(), |b| b), + 9 => sources!(|src| src.take(limit).cloned(), |b| b), + 10 => sources!(|src| src.take(limit).enumerate(), |(i, &b)| b ^ i as u8), + 11 => sources!(|src| src.take(limit).rev(), |&b| b), + // `fuse` advances by `next`, where `take` would read on past its limit. + 12 => sources!(|src| [0x11].iter().chain(src.take(limit).fuse()), |&b| b), + _ => { + // Copies that JS makes by a function, which std's `copied` skips through. + let pairs: Vec<(u8, u8)> = data.iter().map(|&b| (b, !b)).collect(); + let mut rest = pairs.iter(); + skip!(rest.by_ref().take(limit).copied(), |(a, b)| a ^ b); + out.push(rest.len() as u8); + let arrays: Vec<[u8; 2]> = data.iter().map(|&b| [b, !b]).collect(); + let mut rest = arrays.iter(); + skip!(rest.by_ref().take(limit).copied(), |[a, _]| a); + out.push(rest.len() as u8); + } + } +} + /// Ranges as values and as iterators. pub fn ranges(data: &[u8], out: &mut Vec) { let a = data.first().copied().unwrap_or(0); diff --git a/ts/fixtures/task/expected/drops/iters.ts b/ts/fixtures/task/expected/drops/iters.ts index da21180eb..90a91b843 100644 --- a/ts/fixtures/task/expected/drops/iters.ts +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -197,7 +197,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const _162: Guard.Guard = guard(16); v3.push(_162); unwind = 327; - rest = rt.ownedTake(rt.ownedSkip(rt.iterSlice(v3, rt.drop), 1, rt.drop), 3, rt.drop); + rest = rt.iterTake(rt.iterSkip(rt.iterSlice(v3, rt.drop), 1, rt.drop), 3, rt.drop); unwind = 356; _610 = true; const part4 = mapOr$Option_Guard_u32_drained_closure4(rt.iterToOption(rest.next()), 0, (g5: Guard.Guard): rt.u32 => { @@ -295,7 +295,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { _607 = false; _275 = rt.iterRev(_276); unwind = 318; - nth = rt.ownedNth(_275, 1, rt.drop); + nth = rt.iterNth(_275, 1, rt.drop); unwind = 348; _606 = true; rt.drop(_275); @@ -408,7 +408,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const _418: Guard.Guard = guard(38); v12.push(_418); unwind = 314; - const _427: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedLast(rt.ownedStepBy(rt.iterSlice(v12, rt.drop), 2, rt.drop), rt.drop, rt.drop), 0, (g13: Guard.Guard): rt.u32 => { + const _427: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedLast(rt.iterStepBy(rt.iterSlice(v12, rt.drop), 2, rt.drop), rt.drop, rt.drop), 0, (g13: Guard.Guard): rt.u32 => { let unwind6: number = 0; try { unwind6 = 4; @@ -515,18 +515,18 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e9; } }; - _501 = rt.ownedSkip(rt.iterSlice(five(44), rt.drop), 2, rt.drop); + _501 = rt.iterSkip(rt.iterSlice(five(44), rt.drop), 2, rt.drop); unwind = 307; - _499 = rt.ownedNthBack(_501, 3, rt.drop); + _499 = rt.iterNthBack(_501, 3, rt.drop); unwind = 306; const skipped: boolean = _499 !== undefined; unwind = 307; rt.drop(_499); unwind = 344; rt.drop(_501); - _509 = rt.ownedStepBy(rt.iterSlice(five(49), rt.drop), 2, rt.drop); + _509 = rt.iterStepBy(rt.iterSlice(five(49), rt.drop), 2, rt.drop); unwind = 305; - const stepped: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedNthBack(_509, 1, rt.drop), 0, (g16: Guard.Guard): rt.u32 => { + const stepped: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.iterNthBack(_509, 1, rt.drop), 0, (g16: Guard.Guard): rt.u32 => { let unwind10: number = 0; try { unwind10 = 4; @@ -544,7 +544,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { }); unwind = 344; rt.drop(_509); - _518 = rt.iterRev(rt.ownedTake(rt.iterSlice(five(59), rt.drop), 3, rt.drop)); + _518 = rt.iterRev(rt.iterTake(rt.iterSlice(five(59), rt.drop), 3, rt.drop)); unwind = 342; _603 = true; const _524: Guard.Guard[] = []; @@ -552,7 +552,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { _517 = rt.iterChain(_518, rt.iterSlice(_524, rt.drop)); unwind = 304; _603 = false; - const taken: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedNth(_517, 1, rt.drop), 0, (g17: Guard.Guard): rt.u32 => { + const taken: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.iterNth(_517, 1, rt.drop), 0, (g17: Guard.Guard): rt.u32 => { let unwind11: number = 0; try { unwind11 = 4; @@ -570,7 +570,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { }); unwind = 344; rt.drop(_517); - _529 = rt.iterRev(rt.ownedSkip(rt.iterSlice(five(64), rt.drop), 2, rt.drop)); + _529 = rt.iterRev(rt.iterSkip(rt.iterSlice(five(64), rt.drop), 2, rt.drop)); unwind = 340; _602 = true; const _535: Guard.Guard[] = []; @@ -578,7 +578,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { _528 = rt.iterChain(_529, rt.iterSlice(_535, rt.drop)); unwind = 303; _602 = false; - const passed: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedNth(_528, 2, rt.drop), 0, (g18: Guard.Guard): rt.u32 => { + const passed: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.iterNth(_528, 2, rt.drop), 0, (g18: Guard.Guard): rt.u32 => { let unwind12: number = 0; try { unwind12 = 4; @@ -596,9 +596,9 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { }); unwind = 344; rt.drop(_528); - _539 = rt.ownedStepBy(rt.iterRev(rt.iterSlice(five(69), rt.drop)), 2, rt.drop); + _539 = rt.iterStepBy(rt.iterRev(rt.iterSlice(five(69), rt.drop)), 2, rt.drop); unwind = 302; - const strode: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedNth(_539, 2, rt.drop), 0, (g19: Guard.Guard): rt.u32 => { + const strode: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.iterNth(_539, 2, rt.drop), 0, (g19: Guard.Guard): rt.u32 => { let unwind13: number = 0; try { unwind13 = 4; @@ -616,8 +616,8 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { }); unwind = 344; rt.drop(_539); - const counted: rt.usize = rt.ownedCount(rt.ownedTake(rt.iterRev(rt.iterSlice(five(74), rt.drop)), 3, rt.drop), rt.drop, rt.drop); - const far: boolean = rt.iterToOption(rt.iterStepBy(new rt.Range(0, 10), 4294967295).nthBackItem(4294967295)) === undefined; + const counted: rt.usize = rt.ownedCount(rt.iterTake(rt.iterRev(rt.iterSlice(five(74), rt.drop)), 3, rt.drop), rt.drop, rt.drop); + const far: boolean = rt.iterNthBack(rt.iterStepBy(new rt.Range(0, 10), 4294967295), 4294967295) === undefined; const args24: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(skipped, f), (f: rt.Formatter) => rt.u32Display(stepped, f), (f: rt.Formatter) => rt.u32Display(taken, f), (f: rt.Formatter) => rt.u32Display(passed, f), (f: rt.Formatter) => rt.u32Display(strode, f), (f: rt.Formatter) => rt.usizeDisplay(counted, f), (f: rt.Formatter) => rt.fmtBool(far, f)]; Log.note(log, rt.fmtFormat(["back ", args24[0], " ", args24[1], " ", args24[2], " ", args24[3], " ", args24[4], " ", args24[5], " ", args24[6]])); unwind = 346; @@ -2266,11 +2266,11 @@ export function bombed(log: Log.Log, id: rt.u32, at: rt.u8): void { const _46: Bomb.Bomb = bomb(3, false); v2.push(_46); unwind = 0; - it2 = rt.ownedSkip(rt.iterSlice(v2, rt.drop), 1, rt.drop); + it2 = rt.iterSkip(rt.iterSlice(v2, rt.drop), 1, rt.drop); unwind = 114; _after = bomb(4, false); unwind = 113; - rt.drop(rt.ownedNth(it2, 4294967295, rt.drop)); + rt.drop(rt.iterNth(it2, 4294967295, rt.drop)); unwind = 114; rt.drop(_after); unwind = 0; @@ -2343,7 +2343,7 @@ export function bombed(log: Log.Log, id: rt.u32, at: rt.u8): void { const _153: Bomb.Bomb = bomb(3, false); v5.push(_153); unwind = 0; - rt.ownedCount(rt.ownedTake(rt.iterSlice(v5, rt.drop), 2, rt.drop), rt.drop, rt.drop); + rt.ownedCount(rt.iterTake(rt.iterSlice(v5, rt.drop), 2, rt.drop), rt.drop, rt.drop); } else { v6 = []; unwind = 108; @@ -2540,7 +2540,7 @@ export function spent(log: Log.Log, id: rt.u32, at: rt.u8): void { const _64: First.First = first(2); v.push(_64); unwind = 114; - rt.ownedCount(rt.ownedSkip(rt.iterSlice(v, rt.drop), 1, rt.drop), rt.drop, rt.drop); + rt.ownedCount(rt.iterSkip(rt.iterSlice(v, rt.drop), 1, rt.drop), rt.drop, rt.drop); } else if (at === 3) { unwind = 114; v2 = []; diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index 96a292a87..fce491dbe 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -12,10 +12,11 @@ // each, and drops those it still holds as it drops, by `[Symbol.dispose]`; an adaptor // drops what it wraps. Where std drops an item it skips, rejects, or replaces, the runtime // function is given what drops it, after its own arguments, and so is a consumer that -// takes the iterator by value, which drops it as std's does, a panic included. Where -// std's `nth`, `advance_by`, `count`, and `last` drop items in 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. +// takes the iterator by value, which drops it as std's does, a panic included. std's +// `nth`, `nth_back`, and `advance_by` read and drop items in an order each kind of +// iterator has its own, which functions dispatching on the kind follow. Where std's +// `count` and `last` drop items so, the `owned` functions do, so a bundle that never +// drops an item carries none of them. import { ByteVec, byteVecPush, Err, Ok, panic, type Result } from "../rt.ts"; import { BTreeIter, HashIter } from "./collections.ts"; @@ -45,23 +46,11 @@ export interface Iter { len(): number; } -/** `Iterator`: `next`, and the methods std's iterators each do their own way. */ +/** `Iterator`, by its `next`. */ export abstract class Iter implements Iterable { /** The next item, or `DONE`. */ abstract next(): T | Done; - /** `nth` of items that don't drop, as `next` returns it. */ - nthItem(n: number): T | Done { - for (let i = 0; i < n; i++) if (this.next() === DONE) return DONE; - return this.next(); - } - - /** `nth_back` of items that don't drop, as `next_back` returns it. */ - nthBackItem(n: number): T | Done { - for (let i = 0; i < n; i++) if (this.nextBack() === DONE) return DONE; - return this.nextBack(); - } - /** Its items, for a JS `for ... of`. */ *[Symbol.iterator](): Iterator { for (let item = this.next(); item !== DONE; item = this.next()) yield item; @@ -215,14 +204,14 @@ export function iterRev(it: Iter): Iter { return new RevIter(it); } -/** `Iterator::skip` of items that don't drop. */ -export function iterSkip(it: Iter, n: number): Iter { - return new SkipIter(it, n); +/** `Iterator::skip`, dropping what it skips by `drop`, through its iterator's own `nth`. */ +export function iterSkip(it: Iter, n: number, drop?: Drop): Iter { + return new SkipIter(it, n, drop); } -/** `Iterator::take` of items that don't drop. */ -export function iterTake(it: Iter, n: number): Iter { - return new TakeIter(it, n); +/** `Iterator::take`, dropping what `next_back` skips past its limit by `drop`. */ +export function iterTake(it: Iter, n: number, drop?: Drop): Iter { + return new TakeIter(it, n, drop); } /** `Iterator::skip_while`, dropping what it skips by `drop`. */ @@ -240,9 +229,22 @@ export function iterMapWhile(it: Iter, f: (item: T) => U | undefined): return new MapWhileIter(it, f); } -/** `Iterator::step_by` of items that don't drop, panicking on a step of 0. */ -export function iterStepBy(it: Iter, step: number): Iter { - return new StepByIter(it, step); +/** `Iterator::step_by`, panicking on a step of 0, and dropping what it steps over by `drop`. */ +export function iterStepBy(it: Iter, step: number, drop?: Drop): Iter { + return new StepByIter(it, step, drop); +} + +/** + * `Iterator::copied` of items JS copies by `copy`, which std's skips through: its `nth` + * and `advance_by` are its iterator's. + */ +export function iterCopied(it: Iter, copy: (item: R) => T): Iter { + return new CopiedIter(it, copy); +} + +/** `Iterator::cloned` of items that are JS values, whose `nth` reads by `next`, as std's does. */ +export function iterCloned(it: Iter): Iter { + return new MapIter(it, same); } /** `Iterator::inspect`, dropping the item `f` panics on by `drop`. */ @@ -297,9 +299,14 @@ export function iterLast(it: Iter): T | undefined { return iterToOption(last); } -/** `Iterator::nth` of items that don't drop. */ -export function iterNth(it: Iter, n: number): T | undefined { - return iterToOption(it.nthItem(n)); +/** `Iterator::nth`, dropping what it skips by `drop`, as its own `nth` does. */ +export function iterNth(it: Iter, n: number, drop?: Drop): T | undefined { + return iterToOption(nth(it, n, drop)); +} + +/** `DoubleEndedIterator::nth_back`, dropping what it skips by `drop`, as its own `nth_back` does. */ +export function iterNthBack(it: Iter, n: number, drop?: Drop): T | undefined { + return iterToOption(nthBack(it, n, drop)); } /** `Iterator::any`. */ @@ -574,9 +581,10 @@ export function iterCollectOption(it: Iter, into: (values: } // What std's iterators override to skip, count, or take the last: `nth`, `advance_by`, -// `count`, and `last`, each of which drops items in an order of its own kind's. These -// follow it, dispatching on the kind, rather than as methods every iterator would carry, -// and the translation calls them only where an item or the iterator drops. +// `count`, and `last`, each of which reads and drops items in an order of its own kind's. +// These follow it, dispatching on the kind, rather than as methods every iterator would +// carry. `count` and `last` read as `next` does, so the translation calls theirs only +// where an item or the iterator drops. /** `Iterator::count` of an iterator that drops what it holds: each item by `drop`, as its own `count` does, and then it by `dropIt`, a panic included. */ export function ownedCount(it: Iter, dropIt?: Drop>, drop?: Drop): number { @@ -601,31 +609,6 @@ export function ownedLast(it: Iter, dropIt?: Drop>, drop?: Drop return iterToOption(item); } -/** `Iterator::nth`, dropping what it skips by `drop`, as its own `nth` does. */ -export function ownedNth(it: Iter, n: number, drop: Drop): T | undefined { - return iterToOption(nth(it, n, drop)); -} - -/** `DoubleEndedIterator::nth_back`, dropping what it skips by `drop`, as its own `nth_back` does. */ -export function ownedNthBack(it: Iter, n: number, drop: Drop): T | undefined { - return iterToOption(nthBack(it, n, drop)); -} - -/** `Iterator::skip`, dropping what it skips by `drop`, through its iterator's own `nth`. */ -export function ownedSkip(it: Iter, n: number, drop: Drop): Iter { - return new OwnedSkip(it, n, drop); -} - -/** `Iterator::take`, dropping what `next_back` skips past its limit by `drop`. */ -export function ownedTake(it: Iter, n: number, drop: Drop): Iter { - return new OwnedTake(it, n, drop); -} - -/** `Iterator::step_by`, panicking on a step of 0, and dropping what it steps over by `drop`. */ -export function ownedStepBy(it: Iter, step: number, drop: Drop): Iter { - return new OwnedStepBy(it, step, drop); -} - /** `advance_by`: skip up to `n` items, each dropped by `drop`, and return how many it fell short. */ function advance(it: Iter, n: number, drop: Drop | undefined): number { if (it instanceof SliceIter) { @@ -637,6 +620,7 @@ function advance(it: Iter, n: number, drop: Drop | undefined): number { return n - step; } if (it instanceof Borrowed) return advance(it.inner, n, drop); + if (it instanceof CopiedIter) return advance(it.inner, n, undefined); if (it instanceof EnumerateIter) { // std's, which counts what its iterator skipped. const left = advance(it.inner, n, items(drop)); @@ -667,12 +651,6 @@ function advance(it: Iter, n: number, drop: Drop | undefined): number { it.n -= advanced; return n - advanced; } - if (it instanceof FuseIter) { - if (it.inner === undefined) return n; - const left = advance(it.inner, n, drop); - if (left > 0) it.clear(DONE); - return left; - } if (it instanceof FlattenIter) return flattenAdvance(it, n, drop); for (let i = 0; i < n; i++) { const item = it.next(); @@ -692,6 +670,7 @@ function advanceBack(it: Iter, n: number, drop: Drop | undefined): numb return n - step; } if (it instanceof Borrowed) return advanceBack(it.inner, n, drop); + if (it instanceof CopiedIter) return advanceBack(it.inner, n, undefined); if (it instanceof EnumerateIter) return advanceBack(it.inner, n, items(drop)); if (it instanceof ChainIter) { if (it.b !== undefined) { @@ -715,12 +694,6 @@ function advanceBack(it: Iter, n: number, drop: Drop | undefined): numb it.n -= advanced; return n - advanced; } - if (it instanceof FuseIter) { - if (it.inner === undefined) return n; - const left = advanceBack(it.inner, n, drop); - if (left > 0) it.clear(DONE); - return left; - } if (it instanceof FlattenIter) return flattenAdvanceBack(it, n, drop); for (let i = 0; i < n; i++) { const item = it.nextBack(); @@ -732,9 +705,13 @@ function advanceBack(it: Iter, n: number, drop: Drop | undefined): numb /** `nth`, as `next` returns it, dropping what it skips by `drop`. */ function nth(it: Iter, n: number, drop: Drop | undefined): T | Done { - // Skipping items that don't drop, each kind's own `nth` reads the same items. - if (drop === undefined) return it.nthItem(n); + if (it instanceof SliceIter) return advance(it, n, drop) === 0 ? it.next() : DONE; + if (it instanceof Range || it instanceof RangeInclusive) return it.nth(n); if (it instanceof Borrowed) return nth(it.inner, n, drop); + if (it instanceof CopiedIter) { + const item = nth(it.inner, n, undefined); + return item === DONE ? DONE : it.f(item); + } if (it instanceof EnumerateIter) { // std's, which counts only when it finds an item. const item = nth(it.inner, n, items(drop)); @@ -763,7 +740,7 @@ function nth(it: Iter, n: number, drop: Drop | undefined): T | Done { if (skip + n <= USIZE_MAX) return nth(it.inner, skip + n, drop); const item = nth(it.inner, skip - 1, drop); if (item === DONE) return DONE; - drop(item); + drop?.(item); return nth(it.inner, n, drop); } if (it instanceof TakeIter) { @@ -774,7 +751,7 @@ function nth(it: Iter, n: number, drop: Drop | undefined): T | Done { } if (it.n > 0) { const item = nth(it.inner, it.n - 1, drop); - if (item !== DONE) drop(item); + if (item !== DONE) drop?.(item); it.n = 0; } return DONE; @@ -791,11 +768,11 @@ function nth(it: Iter, n: number, drop: Drop | undefined): T | Done { try { item = nth(it.inner, n - 1, drop); } catch (e) { - drop(peeked); + drop?.(peeked); throw e; } // A panic here leaks the item, as std's unwinding does a returned value. - drop(peeked); + drop?.(peeked); return item; } return advance(it, n, drop) === 0 ? it.next() : DONE; @@ -805,19 +782,19 @@ function nth(it: Iter, n: number, drop: Drop | undefined): T | Done { * `StepBy::nth`, std's: the first item, dropped unless it is the one, then every step in * one `nth`, as many as a `usize` counts at a time. */ -function stepByNth(it: StepByIter, n: number, drop: Drop): T | Done { +function stepByNth(it: StepByIter, n: number, drop: Drop | undefined): T | Done { if (it.firstTake) { it.firstTake = false; const first = it.inner.next(); if (first === DONE || n === 0) return first; - drop(first); + drop?.(first); n -= 1; } let step = it.step + 1; if (n === USIZE_MAX) { const item = nth(it.inner, step - 1, drop); if (item === DONE) return DONE; - drop(item); + drop?.(item); } else { n += 1; } @@ -829,13 +806,14 @@ function stepByNth(it: StepByIter, n: number, drop: Drop): T | Done { else n -= Math.floor(USIZE_MAX / step); const item = nth(it.inner, Math.max(byN, byStep) - 1, drop); if (item === DONE) return DONE; - drop(item); + drop?.(item); } } /** `nth_back`, as `next_back` returns it. */ function nthBack(it: Iter, n: number, drop: Drop | undefined): T | Done { - if (drop === undefined) return it.nthBackItem(n); + if (it instanceof SliceIter) return advanceBack(it, n, drop) === 0 ? it.nextBack() : DONE; + if (it instanceof Range || it instanceof RangeInclusive) return it.nthBack(n); if (it instanceof Borrowed) return nthBack(it.inner, n, drop); if (it instanceof EnumerateIter) { const item = nthBack(it.inner, n, items(drop)); @@ -859,7 +837,7 @@ function nthBack(it: Iter, n: number, drop: Drop | undefined): T | Done if (n < len) return nthBack(it.inner, n, drop); if (len > 0) { const item = nthBack(it.inner, len - 1, drop); - if (item !== DONE) drop(item); + if (item !== DONE) drop?.(item); } return DONE; } @@ -873,7 +851,7 @@ function nthBack(it: Iter, n: number, drop: Drop | undefined): T | Done } if (len > 0) { const item = nthBack(it.inner, len - 1, drop); - if (item !== DONE) drop(item); + if (item !== DONE) drop?.(item); } return DONE; } @@ -1303,18 +1281,10 @@ class Borrowed extends Iter { override len(): number { return this.inner.len(); } - - override nthItem(n: number): T | Done { - return this.inner.nthItem(n); - } - - override nthBackItem(n: number): T | Done { - return this.inner.nthBackItem(n); - } } class MapIter extends Adaptor { - private readonly f: (item: T) => U; + readonly f: (item: T) => U; constructor(inner: Iter, f: (item: T) => U) { super(inner); @@ -1336,6 +1306,9 @@ class MapIter extends Adaptor { } } +/** `Copied` of items JS copies by a function: a `map` whose `nth` and `advance_by` are its iterator's. */ +class CopiedIter extends MapIter {} + class FilterIter extends Adaptor { private readonly f: (item: T) => boolean; private readonly drop: Drop | undefined; @@ -1393,20 +1366,6 @@ class EnumerateIter extends Adaptor { return item === DONE ? DONE : [this.index + this.inner.len(), item]; } - /** std's `nth`, which counts only when it finds an item. */ - override nthItem(n: number): [number, T] | Done { - const item = this.inner.nthItem(n); - if (item === DONE) return DONE; - const i = this.index + n; - this.index = i + 1; - return [i, item]; - } - - override nthBackItem(n: number): [number, T] | Done { - const item = this.inner.nthBackItem(n); - return item === DONE ? DONE : [this.index + this.inner.len(), item]; - } - override len(): number { return this.inner.len(); } @@ -1569,32 +1528,27 @@ class RevIter extends Adaptor { return this.inner.next(); } - override nthItem(n: number): T | Done { - return this.inner.nthBackItem(n); - } - - override nthBackItem(n: number): T | Done { - return this.inner.nthItem(n); - } - override len(): number { return this.inner.len(); } } +/** `Skip`, whose items drop by `drop` as its iterator's own `nth` skips them. */ class SkipIter extends Adaptor { n: number; + private readonly drop: Drop | undefined; - constructor(inner: Iter, n: number) { + constructor(inner: Iter, n: number, drop?: Drop) { super(inner); this.n = n; + this.drop = drop; } next(): T | Done { if (this.n === 0) return this.inner.next(); const n = this.n; this.n = 0; - return this.inner.nthItem(n); + return nth(this.inner, n, this.drop); } override nextBack(): T | Done { @@ -1606,29 +1560,15 @@ class SkipIter extends Adaptor { } } -/** `Skip` of items that drop, which drop as its iterator's own `nth` skips them. */ -class OwnedSkip extends SkipIter { - private readonly drop: Drop; - - constructor(inner: Iter, n: number, drop: Drop) { - super(inner, n); - this.drop = drop; - } - - override next(): T | Done { - if (this.n === 0) return this.inner.next(); - const n = this.n; - this.n = 0; - return nth(this.inner, n, this.drop); - } -} - +/** `Take`, of which what its iterator holds past the limit drops by `drop` as `next_back` reads through it. */ class TakeIter extends Adaptor { n: number; + private readonly drop: Drop | undefined; - constructor(inner: Iter, n: number) { + constructor(inner: Iter, n: number, drop?: Drop) { super(inner); this.n = n; + this.drop = drop; } next(): T | Done { @@ -1641,32 +1581,7 @@ class TakeIter extends Adaptor { override nextBack(): T | Done { if (this.n === 0) return DONE; const n = this.n--; - return this.inner.nthBackItem(Math.max(this.inner.len() - n, 0)); - } - - /** std's `nth`: past the limit, it reads the rest of the limit through and ends. */ - override nthItem(n: number): T | Done { - if (this.n > n) { - this.n -= n + 1; - return this.inner.nthItem(n); - } - if (this.n > 0) { - this.inner.nthItem(this.n - 1); - this.n = 0; - } - return DONE; - } - - /** std's `nth_back`: past the limit, it reads the whole rest from the back, even at a limit of 0. */ - override nthBackItem(n: number): T | Done { - const len = this.inner.len(); - if (this.n > n) { - const m = Math.max(len - this.n, 0) + n; - this.n -= n + 1; - return this.inner.nthBackItem(m); - } - if (len > 0) this.inner.nthBackItem(len - 1); - return DONE; + return nthBack(this.inner, Math.max(this.inner.len() - n, 0), this.drop); } override len(): number { @@ -1674,22 +1589,6 @@ class TakeIter extends Adaptor { } } -/** `Take` of items that drop, which what its iterator holds past the limit drops as `next_back` reads through. */ -class OwnedTake extends TakeIter { - private readonly drop: Drop; - - constructor(inner: Iter, n: number, drop: Drop) { - super(inner, n); - this.drop = drop; - } - - override nextBack(): T | Done { - if (this.n === 0) return DONE; - const n = this.n--; - return nthBack(this.inner, Math.max(this.inner.len() - n, 0), this.drop); - } -} - class SkipWhileIter extends Adaptor { private readonly f: (item: T) => boolean; private readonly drop: Drop | undefined; @@ -1753,11 +1652,13 @@ class MapWhileIter extends Adaptor { } } +/** `StepBy`, whose items drop by `drop` as its iterator's own `nth` and `nth_back` step over them. */ class StepByIter extends Adaptor { readonly step: number; firstTake = true; + private readonly drop: Drop | undefined; - constructor(inner: Iter, step: number) { + constructor(inner: Iter, step: number, drop?: Drop) { super(inner); // The iterator it was given drops as the panic unwinds. if (step === 0) { @@ -1765,16 +1666,17 @@ class StepByIter extends Adaptor { panic("assertion failed: step != 0"); } this.step = step - 1; + this.drop = drop; } next(): T | Done { const n = this.firstTake ? 0 : this.step; this.firstTake = false; - return this.inner.nthItem(n); + return nth(this.inner, n, this.drop); } override nextBack(): T | Done { - return this.inner.nthBackItem(this.backIndex()); + return nthBack(this.inner, this.backIndex(), this.drop); } /** How far from the back its last item is. */ @@ -1790,26 +1692,6 @@ class StepByIter extends Adaptor { } } -/** `StepBy` of items that drop, which drop as its iterator's own `nth` and `nth_back` step over them. */ -class OwnedStepBy extends StepByIter { - private readonly drop: Drop; - - constructor(inner: Iter, step: number, drop: Drop) { - super(inner, step); - this.drop = drop; - } - - override next(): T | Done { - const n = this.firstTake ? 0 : this.step; - this.firstTake = false; - return nth(this.inner, n, this.drop); - } - - override nextBack(): T | Done { - return nthBack(this.inner, this.backIndex(), this.drop); - } -} - class InspectIter extends Adaptor { private readonly f: (item: T) => void; private readonly drop: Drop | undefined; @@ -2130,7 +2012,7 @@ export class Range extends Iter { } /** std's `nth`, in one step: past the end, the range ends. */ - override nthItem(n: number): T | Done { + nth(n: number): T | Done { const item = step(this.start, n, this.int); if (item !== undefined && lt(item, this.end)) { this.start = step(item, 1, this.int)!; @@ -2141,7 +2023,7 @@ export class Range extends Iter { } /** std's `nth_back`, in one step. */ - override nthBackItem(n: number): T | Done { + nthBack(n: number): T | Done { const item = step(this.end, -n, this.int); if (item !== undefined && lt(this.start, item)) { this.end = step(item, -1, this.int)!; @@ -2207,7 +2089,7 @@ export class RangeInclusive extends Iter { } /** std's `nth`: `start` moves past the item, wrapping if it overflows, which ends the range. */ - override nthItem(n: number): T | Done { + nth(n: number): T | Done { if (rangeInclusiveIsEmpty(this)) return DONE; const [item, over] = overflowing(this.lo, n, this.int); const [after, overAfter] = overflowing(item, 1, this.int); @@ -2217,7 +2099,7 @@ export class RangeInclusive extends Iter { } /** std's `nth_back`, from the end. */ - override nthBackItem(n: number): T | Done { + nthBack(n: number): T | Done { if (rangeInclusiveIsEmpty(this)) return DONE; const [item, over] = overflowing(this.hi, -n, this.int); const [before, overBefore] = overflowing(item, -1, this.int); @@ -2265,3 +2147,8 @@ function overflowing(n: T, by: number, int: Step | undefined): [T, boolean function itself(iter: Iter): Iter { return iter; } + +/** A value as itself: what `cloned` makes of a JS value. */ +function same(value: T): T { + return value; +} diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index 1931aa134..d3392f155 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -339,10 +339,7 @@ pub fn call<'tcx>( "next_back" => recv.member("nextBack").call(Vec::new()), _ => { let dropper = b.t.dropper(item, span); - if !undefined(&dropper) { - return Some(Expr::rt("ownedNthBack", [vec![recv], rest, vec![dropper]].concat())); - } - recv.member("nthBackItem").call(rest) + return Some(Expr::rt("iterNthBack", tail([vec![recv], rest].concat(), vec![dropper]))); } }; return Some(Expr::rt("iterToOption", vec![item])); @@ -380,14 +377,10 @@ pub fn call<'tcx>( method(&camel, rest) } // What each drops: an item it skips or rejects, or one it peeked. - "filter" | "skip_while" | "take_while" | "inspect" | "peekable" => { + "filter" | "skip_while" | "take_while" | "inspect" | "peekable" | "skip" | "take" | "step_by" => { let dropper = b.t.dropper(item, span); method(&camel, tail(rest, vec![dropper])) } - "skip" | "take" | "step_by" => { - let dropper = b.t.dropper(item, span); - owned(&camel, rest, vec![dropper]) - } "fuse" => { let fused = fused(b, self_ty); method(name, tail(rest, vec![fused])) @@ -416,13 +409,15 @@ pub fn call<'tcx>( } // `ExactSizeIterator::len` is each iterator's own. "len" => Some(recv.member("len").call(rest)), - "last" | "nth" => { + "last" => { option_ok(b, item, span); - let droppers = match name { - "last" => vec![iter_dropper(b, self_ty, span), b.t.dropper(item, span)], - _ => vec![b.t.dropper(item, span)], - }; - owned(&camel, rest, droppers) + let droppers = vec![iter_dropper(b, self_ty, span), b.t.dropper(item, span)]; + owned(name, rest, droppers) + } + "nth" => { + option_ok(b, item, span); + let dropper = b.t.dropper(item, span); + method(name, tail(rest, vec![dropper])) } "find" | "peek" | "next_if" => { option_ok(b, item, span); @@ -505,25 +500,28 @@ pub fn call<'tcx>( let ty::Ref(_, inner, _) = item.kind() else { return None; }; + let clone = |b: &mut Body<'_, '_, 'tcx>| { + let clone = tcx.lang_items().clone_fn()?; + Some(b.fn_value(clone, tcx.mk_args(&[(*inner).into()]), span)) + }; // A `Clone` written by hand may do other than copy, even for a `Copy` type. - let clones = name == "cloned" && !library::clone_copies(b.t, *inner); - match () { - _ if clones => { - let clone = tcx.lang_items().clone_fn()?; - let clone = b.fn_value(clone, tcx.mk_args(&[(*inner).into()]), span); - method("map", vec![clone]) - } + let copies = name == "copied" || library::clone_copies(b.t, *inner); + let copy = match () { + _ if !copies => Some(clone(b)?), // Out of the slice each item is. - _ if super::byte_array(*inner) => method("map", vec![Expr::Rt("byteSliceToArray".into())]), - _ if b.t.needs_copy(*inner) => method("map", b.t.copy_fn(*inner, span).into_iter().collect()), + _ if super::byte_array(*inner) => Some(Expr::Rt("byteSliceToArray".into())), + _ if b.t.needs_copy(*inner) => b.t.copy_fn(*inner, span), // A JS string is a value already. - _ if b.t.is_copy(*inner) || library::string(tcx, *inner) => Some(recv), + _ if b.t.is_copy(*inner) || library::string(tcx, *inner) => None, // Each item through its `Clone`. - _ => { - let clone = tcx.lang_items().clone_fn()?; - let clone = b.fn_value(clone, tcx.mk_args(&[(*inner).into()]), span); - method("map", vec![clone]) - } + _ => Some(clone(b)?), + }; + // std's `copied` skips through its iterator's `nth`, and `cloned` by its own `next`. + match (name, copy) { + ("copied", Some(copy)) => method("copied", vec![copy]), + ("copied", None) => Some(recv), + (_, Some(copy)) => method("map", vec![copy]), + (_, None) => method("cloned", Vec::new()), } } "collect" => collect(b, targ(1)?, item, recv, self_ty, span), From 52bb36a85c1a36152af1637435ac1b41ec232a98 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:00:21 -0700 Subject: [PATCH 3/3] fix(ts): skip through each iterator's own nth, as std's does nth, nth_back, and advance_by are methods with std's defaults on rt.Iter, overridden where std's adaptors override them, so a by_ref source or an inspect closure sees std's reads with or without a dropper. Co-Authored-By: Claude Opus 5.5 --- quest/m2/README.md | 1 - quest/m2/ts-iter-nth.md | 23 -- ts/MIGRATE.md | 4 + ts/README.md | 3 +- ts/runtime/rt/iter.ts | 736 +++++++++++++++++++++------------------- ts/src/lower/iter.rs | 4 +- 6 files changed, 403 insertions(+), 368 deletions(-) delete mode 100644 quest/m2/ts-iter-nth.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 9fbd0db2c..2d71a933a 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -30,7 +30,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - every value that drops in moq-net and kio drops where Rust drops it - [Async in the TypeScript translator](/quest/m2/ts-async.md) - moq-net's and kio's async code translates with Rust's lazy futures - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values -- [Iterator skips that read as std's](/quest/m2/ts-iter-nth.md) - `nth` and `nth_back` of what drops nothing read the items std's do - [Translate moq-net's model to TypeScript](/quest/m2/ts-model/README.md) - the model translates with kio, moq-clock, and moq-pattern, for moq to compare against WASM - [Waiting: Swift 6.4 in nixpkgs-unstable](/quest/m2/uniffi-swift-arm.md) - the nightly UniFFI fixtures move back to arm - [Waiting: ubrn reads UniFFI 0.32](/quest/m2/ubrn-release.md) - the binding benchmark's browser runner pins a ubrn release, not an open PR diff --git a/quest/m2/ts-iter-nth.md b/quest/m2/ts-iter-nth.md deleted file mode 100644 index 65aa0ad4c..000000000 --- a/quest/m2/ts-iter-nth.md +++ /dev/null @@ -1,23 +0,0 @@ -# [S] Iterator skips that read as std's - -## Goal - -rust2-ts's `nth`, `nth_back`, and the adaptors built on them read the same items std's -do of an iterator that drops nothing, so a `by_ref` source or an `inspect` closure sees -std's reads, proven by differential tests against native Rust. - -## Plan - -Found by review of [#101](https://github.com/kixelated/rust2/pull/101) on 2026-10-27. -Without a dropper, `rt.iterNth` and `nthBackItem` are `main`'s methods, which only -`Enumerate`, `Rev`, `Take`, `Range`, and the `by_ref` wrapper override. std's `Fuse`, -`Skip`, `Chain`, `StepBy`, `Peekable`, `Flatten`, and `Copied` forward to -what they wrap, and `Take`'s `nth_back` and `advance_back_by` read past its limit, so -`(0..3).by_ref().take(0).fuse().nth_back(0)` leaves the range empty in Rust but not here. -#101's `rt.owned*` dispatchers already follow std's order where an item drops. - -- Weigh calling those dispatchers without a dropper against methods on each class: the - codec's bundle carries every class a dispatcher names. -- Cover `by_ref` and `inspect` sources under each adaptor. - -Public API: the translator's output. diff --git a/ts/MIGRATE.md b/ts/MIGRATE.md index ad1fc755c..563cd4a88 100644 --- a/ts/MIGRATE.md +++ b/ts/MIGRATE.md @@ -2,6 +2,10 @@ ## Unreleased +- The runtime no longer exports `ownedNth`, `ownedNthBack`, `ownedSkip`, `ownedTake`, or + `ownedStepBy`: `iterNth`, `iterNthBack`, `iterSkip`, `iterTake`, and `iterStepBy` take + what drops an item last. `rt.Iter`'s `nthItem` and `nthBackItem` are `nth` and + `nthBack`, which return `rt.DONE` past the end. - Translation builds std from source for `wasm32-unknown-unknown`, so the toolchain needs its `rust-src` component, as the flake's has, and the first run compiles std. - `Option`'s and `Result`'s combinators lower from core's MIR into `core/option.ts` and diff --git a/ts/README.md b/ts/README.md index 03c6410ae..528ef7939 100644 --- a/ts/README.md +++ b/ts/README.md @@ -133,7 +133,8 @@ would: `rt.fmtToString((f) => DecodeError.fmt$Display(err, f))` and An iterator's `next()` returns its next item or `rt.DONE`, never `undefined`, so an iterator of `Option` keeps each `None` apart from its end. std's adaptors and consumers are runtime functions taking the iterator first, `rt.iterMap(it, f)`, lazy and -short-circuiting as std's are, and call their closures in the same order and as often. +short-circuiting as std's are, and call their closures, and read what they wrap, in +the same order and as often, a skip by `nth` included. An iterator over a slice, array, or `Vec`, or a small range, that only its `next` and moves read steps in place, as two variables: the array and an index into it, or the range's bounds, with no `rt.Iter` made. The crate's own `impl Iterator` returns `rt.DONE` from its `next` too, and joins diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index fce491dbe..59f3f2e7f 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -12,11 +12,11 @@ // each, and drops those it still holds as it drops, by `[Symbol.dispose]`; an adaptor // drops what it wraps. Where std drops an item it skips, rejects, or replaces, the runtime // function is given what drops it, after its own arguments, and so is a consumer that -// takes the iterator by value, which drops it as std's does, a panic included. std's -// `nth`, `nth_back`, and `advance_by` read and drop items in an order each kind of -// iterator has its own, which functions dispatching on the kind follow. Where std's -// `count` and `last` drop items so, the `owned` functions do, so a bundle that never -// drops an item carries none of them. +// takes the iterator by value, which drops it as std's does, a panic included. Each kind's +// `nth`, `nth_back`, and `advance_by` are its own, as std's are, reading and dropping what +// they skip in its order. Where std's `count` and `last` drop items in 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, Ok, panic, type Result } from "../rt.ts"; import { BTreeIter, HashIter } from "./collections.ts"; @@ -46,11 +46,41 @@ export interface Iter { len(): number; } -/** `Iterator`, by its `next`. */ +/** `Iterator`: `next`, and the methods std's iterators each do their own way. */ export abstract class Iter implements Iterable { /** The next item, or `DONE`. */ abstract next(): T | Done; + /** `advance_by`: skip up to `n` items, each dropped by `drop`, and return how many it fell short. */ + advanceBy(n: number, drop?: Drop): number { + for (let i = 0; i < n; i++) { + const item = this.next(); + if (item === DONE) return n - i; + drop?.(item); + } + return 0; + } + + /** `advance_back_by`, from the back. */ + advanceBackBy(n: number, drop?: Drop): number { + for (let i = 0; i < n; i++) { + const item = this.nextBack(); + if (item === DONE) return n - i; + drop?.(item); + } + return 0; + } + + /** `nth`, as `next` returns it, dropping what it skips by `drop`. */ + nth(n: number, drop?: Drop): T | Done { + return this.advanceBy(n, drop) === 0 ? this.next() : DONE; + } + + /** `nth_back`, as `next_back` returns it. */ + nthBack(n: number, drop?: Drop): T | Done { + return this.advanceBackBy(n, drop) === 0 ? this.nextBack() : DONE; + } + /** Its items, for a JS `for ... of`. */ *[Symbol.iterator](): Iterator { for (let item = this.next(); item !== DONE; item = this.next()) yield item; @@ -301,12 +331,12 @@ export function iterLast(it: Iter): T | undefined { /** `Iterator::nth`, dropping what it skips by `drop`, as its own `nth` does. */ export function iterNth(it: Iter, n: number, drop?: Drop): T | undefined { - return iterToOption(nth(it, n, drop)); + return iterToOption(it.nth(n, drop)); } /** `DoubleEndedIterator::nth_back`, dropping what it skips by `drop`, as its own `nth_back` does. */ export function iterNthBack(it: Iter, n: number, drop?: Drop): T | undefined { - return iterToOption(nthBack(it, n, drop)); + return iterToOption(it.nthBack(n, drop)); } /** `Iterator::any`. */ @@ -580,11 +610,10 @@ export function iterCollectOption(it: Iter, into: (values: return undefined; } -// What std's iterators override to skip, count, or take the last: `nth`, `advance_by`, -// `count`, and `last`, each of which reads and drops items in an order of its own kind's. -// These follow it, dispatching on the kind, rather than as methods every iterator would -// carry. `count` and `last` read as `next` does, so the translation calls theirs only -// where an item or the iterator drops. +// What std's iterators override to count or take the last: `count` and `last`, each of +// which drops items in an order of its own kind's. These follow it, dispatching on the +// kind, rather than as methods every iterator would carry, and the translation calls them +// only where an item or the iterator drops. /** `Iterator::count` of an iterator that drops what it holds: each item by `drop`, as its own `count` does, and then it by `dropIt`, a panic included. */ export function ownedCount(it: Iter, dropIt?: Drop>, drop?: Drop): number { @@ -609,261 +638,6 @@ export function ownedLast(it: Iter, dropIt?: Drop>, drop?: Drop return iterToOption(item); } -/** `advance_by`: skip up to `n` items, each dropped by `drop`, and return how many it fell short. */ -function advance(it: Iter, n: number, drop: Drop | undefined): number { - if (it instanceof SliceIter) { - // std's, of a `Vec`'s: past them all first, then each dropped, as a slice drops. - const step = Math.min(n, it.back - it.front); - const from = it.front; - it.front += step; - if (drop !== undefined) dropRange(it.s, drop, from, it.front); - return n - step; - } - if (it instanceof Borrowed) return advance(it.inner, n, drop); - if (it instanceof CopiedIter) return advance(it.inner, n, undefined); - if (it instanceof EnumerateIter) { - // std's, which counts what its iterator skipped. - const left = advance(it.inner, n, items(drop)); - it.index += n - left; - return left; - } - if (it instanceof ChainIter) { - if (it.a !== undefined) { - n = advance(it.a, n, drop); - if (n === 0) return 0; - it.endA(); - } - return it.b === undefined ? n : advance(it.b, n, drop); - } - if (it instanceof RevIter) return advanceBack(it.inner, n, drop); - if (it instanceof SkipIter) { - // std's: what it skips and `n` more in one step. Past a `usize`'s greatest, std's - // splits it, but no iterator that drops holds that many. - const skip = it.n; - const left = advance(it.inner, skip + n, drop); - const advanced = skip + n - left; - it.n = Math.max(skip - advanced, 0); - return n - Math.max(advanced - skip, 0); - } - if (it instanceof TakeIter) { - const min = Math.min(it.n, n); - const advanced = min - advance(it.inner, min, drop); - it.n -= advanced; - return n - advanced; - } - if (it instanceof FlattenIter) return flattenAdvance(it, n, drop); - for (let i = 0; i < n; i++) { - const item = it.next(); - if (item === DONE) return n - i; - drop?.(item); - } - return 0; -} - -/** `advance_back_by`, from the back. */ -function advanceBack(it: Iter, n: number, drop: Drop | undefined): number { - if (it instanceof SliceIter) { - // std's: those it skips drop front to back, as a slice drops. - const step = Math.min(n, it.back - it.front); - it.back -= step; - if (drop !== undefined) dropRange(it.s, drop, it.back, it.back + step); - return n - step; - } - if (it instanceof Borrowed) return advanceBack(it.inner, n, drop); - if (it instanceof CopiedIter) return advanceBack(it.inner, n, undefined); - if (it instanceof EnumerateIter) return advanceBack(it.inner, n, items(drop)); - if (it instanceof ChainIter) { - if (it.b !== undefined) { - n = advanceBack(it.b, n, drop); - if (n === 0) return 0; - it.endB(); - } - return it.a === undefined ? n : advanceBack(it.a, n, drop); - } - if (it instanceof RevIter) return advance(it.inner, n, drop); - if (it instanceof SkipIter) { - // std's: its iterator advanced from the back in one step, short of what it skips. - const min = Math.min(it.len(), n); - advanceBack(it.inner, min, drop); - return n - min; - } - if (it instanceof TakeIter) { - // std's: its iterator advanced from the back past the limit and `n` more, in one step. - const trim = Math.max(it.inner.len() - it.n, 0); - const advanced = trim + n - advanceBack(it.inner, trim + n, drop) - trim; - it.n -= advanced; - return n - advanced; - } - if (it instanceof FlattenIter) return flattenAdvanceBack(it, n, drop); - for (let i = 0; i < n; i++) { - const item = it.nextBack(); - if (item === DONE) return n - i; - drop?.(item); - } - return 0; -} - -/** `nth`, as `next` returns it, dropping what it skips by `drop`. */ -function nth(it: Iter, n: number, drop: Drop | undefined): T | Done { - if (it instanceof SliceIter) return advance(it, n, drop) === 0 ? it.next() : DONE; - if (it instanceof Range || it instanceof RangeInclusive) return it.nth(n); - if (it instanceof Borrowed) return nth(it.inner, n, drop); - if (it instanceof CopiedIter) { - const item = nth(it.inner, n, undefined); - return item === DONE ? DONE : it.f(item); - } - if (it instanceof EnumerateIter) { - // std's, which counts only when it finds an item. - const item = nth(it.inner, n, items(drop)); - if (item === DONE) return DONE; - const i = it.index + n; - it.index = i + 1; - return [i, item] as T; - } - if (it instanceof ChainIter) { - if (it.a !== undefined) { - n = advance(it.a, n, drop); - if (n === 0) { - const item = it.a.next(); - if (item !== DONE) return item; - } - it.endA(); - } - return it.b === undefined ? DONE : nth(it.b, n, drop); - } - if (it instanceof RevIter) return nthBack(it.inner, n, drop); - if (it instanceof SkipIter) { - // std's: what it still skips and then `n` more, in one step, or past a `usize`'s - // greatest, what it skips in one and `n` in another. - const skip = it.n; - it.n = 0; - if (skip + n <= USIZE_MAX) return nth(it.inner, skip + n, drop); - const item = nth(it.inner, skip - 1, drop); - if (item === DONE) return DONE; - drop?.(item); - return nth(it.inner, n, drop); - } - if (it instanceof TakeIter) { - // std's: past the limit, it reads the rest of the limit through, drops it, and ends. - if (it.n > n) { - it.n -= n + 1; - return nth(it.inner, n, drop); - } - if (it.n > 0) { - const item = nth(it.inner, it.n - 1, drop); - if (item !== DONE) drop?.(item); - it.n = 0; - } - return DONE; - } - if (it instanceof StepByIter) return stepByNth(it, n, drop); - if (it instanceof FuseIter) return it.inner === undefined ? DONE : it.clear(nth(it.inner, n, drop)); - if (it instanceof Peekable) { - // std's: the item it peeked drops after what its iterator skips. - if (!it.peeked) return nth(it.inner, n, drop); - const peeked = it.take(); - if (peeked === DONE) return DONE; - if (n === 0) return peeked; - let item: T | Done; - try { - item = nth(it.inner, n - 1, drop); - } catch (e) { - drop?.(peeked); - throw e; - } - // A panic here leaks the item, as std's unwinding does a returned value. - drop?.(peeked); - return item; - } - return advance(it, n, drop) === 0 ? it.next() : DONE; -} - -/** - * `StepBy::nth`, std's: the first item, dropped unless it is the one, then every step in - * one `nth`, as many as a `usize` counts at a time. - */ -function stepByNth(it: StepByIter, n: number, drop: Drop | undefined): T | Done { - if (it.firstTake) { - it.firstTake = false; - const first = it.inner.next(); - if (first === DONE || n === 0) return first; - drop?.(first); - n -= 1; - } - let step = it.step + 1; - if (n === USIZE_MAX) { - const item = nth(it.inner, step - 1, drop); - if (item === DONE) return DONE; - drop?.(item); - } else { - n += 1; - } - for (;;) { - if (n * step <= USIZE_MAX) return nth(it.inner, n * step - 1, drop); - const byN = Math.floor(USIZE_MAX / n) * n; - const byStep = Math.floor(USIZE_MAX / step) * step; - if (byN > byStep) step -= Math.floor(USIZE_MAX / n); - else n -= Math.floor(USIZE_MAX / step); - const item = nth(it.inner, Math.max(byN, byStep) - 1, drop); - if (item === DONE) return DONE; - drop?.(item); - } -} - -/** `nth_back`, as `next_back` returns it. */ -function nthBack(it: Iter, n: number, drop: Drop | undefined): T | Done { - if (it instanceof SliceIter) return advanceBack(it, n, drop) === 0 ? it.nextBack() : DONE; - if (it instanceof Range || it instanceof RangeInclusive) return it.nthBack(n); - if (it instanceof Borrowed) return nthBack(it.inner, n, drop); - if (it instanceof EnumerateIter) { - const item = nthBack(it.inner, n, items(drop)); - return item === DONE ? DONE : ([it.index + it.inner.len(), item] as T); - } - if (it instanceof ChainIter) { - if (it.b !== undefined) { - n = advanceBack(it.b, n, drop); - if (n === 0) { - const item = it.b.nextBack(); - if (item !== DONE) return item; - } - it.endB(); - } - return it.a === undefined ? DONE : nthBack(it.a, n, drop); - } - if (it instanceof RevIter) return nth(it.inner, n, drop); - if (it instanceof SkipIter) { - // std's: past what it doesn't skip, its iterator read from the back through what it does. - const len = it.len(); - if (n < len) return nthBack(it.inner, n, drop); - if (len > 0) { - const item = nthBack(it.inner, len - 1, drop); - if (item !== DONE) drop?.(item); - } - return DONE; - } - if (it instanceof TakeIter) { - // std's: past the limit, it reads the whole rest from the back, even at a limit of 0. - const len = it.inner.len(); - if (it.n > n) { - const m = Math.max(len - it.n, 0) + n; - it.n -= n + 1; - return nthBack(it.inner, m, drop); - } - if (len > 0) { - const item = nthBack(it.inner, len - 1, drop); - if (item !== DONE) drop?.(item); - } - return DONE; - } - if (it instanceof StepByIter) { - // std's: every step from the back in one, saturating at a `usize`'s greatest. - const steps = Math.min(n * (it.step + 1), USIZE_MAX); - return nthBack(it.inner, Math.min(steps + it.backIndex(), USIZE_MAX), drop); - } - if (it instanceof FuseIter) return it.inner === undefined ? DONE : it.clear(nthBack(it.inner, n, drop)); - return advanceBack(it, n, drop) === 0 ? it.nextBack() : DONE; -} - /** `count`, dropping each item by `drop`. */ function count(it: Iter, drop: Drop | undefined): number { if (it instanceof EnumerateIter) return count(it.inner, items(drop)); @@ -886,7 +660,7 @@ function count(it: Iter, drop: Drop | undefined): number { if (it.n === 0) return 0; const n = it.n; it.n = 0; - return n - advance(it.inner, n, drop); + return n - it.inner.advanceBy(n, drop); } if (it instanceof FuseIter) { const inner = it.inner; @@ -1037,74 +811,12 @@ function skipped(it: SkipIter, drop: Drop | undefined): boolean { if (it.n === 0) return false; const n = it.n; it.n = 0; - const item = nth(it.inner, n - 1, drop); + const item = it.inner.nth(n - 1, drop); if (item === DONE) return true; drop?.(item); return false; } -/** - * `Flatten::advance_by`, std's, by `try_fold`: each iterator in turn advanced by its own - * `advance_by`, one that falls short dropped only as the next replaces it, and the source - * dropped once it ends unless it is fused. - */ -function flattenAdvance(it: FlattenIter, n: number, drop: Drop | undefined): number { - if (it.front !== undefined) { - n = advance(it.front, n, drop); - if (n === 0) return 0; - } - it.setFront(undefined); - const outer = it.outer; - if (outer !== undefined) { - for (let inner = outer.next(); inner !== DONE; inner = outer.next()) { - const front = it.into(inner); - it.setFront(front); - n = advance(front, n, drop); - if (n === 0) return 0; - } - if (!it.fused) { - it.outer = undefined; - dispose(outer); - } - } - it.setFront(undefined); - if (it.back !== undefined) { - n = advance(it.back, n, drop); - if (n === 0) return 0; - } - it.setBack(undefined); - return n; -} - -/** `Flatten::advance_back_by`, from the back. */ -function flattenAdvanceBack(it: FlattenIter, n: number, drop: Drop | undefined): number { - if (it.back !== undefined) { - n = advanceBack(it.back, n, drop); - if (n === 0) return 0; - } - it.setBack(undefined); - const outer = it.outer; - if (outer !== undefined) { - for (let inner = outer.nextBack(); inner !== DONE; inner = outer.nextBack()) { - const back = it.into(inner); - it.setBack(back); - n = advanceBack(back, n, drop); - if (n === 0) return 0; - } - if (!it.fused) { - it.outer = undefined; - dispose(outer); - } - } - it.setBack(undefined); - if (it.front !== undefined) { - n = advanceBack(it.front, n, drop); - if (n === 0) return 0; - } - it.setFront(undefined); - return n; -} - /** * Run `f` on each iterator of `it` in turn, the front, each of the source's, and the back, * as std's `fold` takes them by value; the source drops once read through. @@ -1196,6 +908,23 @@ class SliceIter extends Iter implements Disposable { this.front = this.back; dropRange(this.s, this.drop, from, this.back); } + + /** std's, of a `Vec`'s: past them all first, then each dropped, as a slice drops. */ + override advanceBy(n: number, drop?: Drop): number { + const step = Math.min(n, this.back - this.front); + const from = this.front; + this.front += step; + if (drop !== undefined) dropRange(this.s, drop, from, this.front); + return n - step; + } + + /** std's: those it skips drop front to back, as a slice drops. */ + override advanceBackBy(n: number, drop?: Drop): number { + const step = Math.min(n, this.back - this.front); + this.back -= step; + if (drop !== undefined) dropRange(this.s, drop, this.back, this.back + step); + return n - step; + } } /** `option::IntoIter`, `Once`, and `Empty`: at most one item. */ @@ -1281,6 +1010,22 @@ class Borrowed extends Iter { override len(): number { return this.inner.len(); } + + override advanceBy(n: number, drop?: Drop): number { + return this.inner.advanceBy(n, drop); + } + + override advanceBackBy(n: number, drop?: Drop): number { + return this.inner.advanceBackBy(n, drop); + } + + override nth(n: number, drop?: Drop): T | Done { + return this.inner.nth(n, drop); + } + + override nthBack(n: number, drop?: Drop): T | Done { + return this.inner.nthBack(n, drop); + } } class MapIter extends Adaptor { @@ -1307,7 +1052,20 @@ class MapIter extends Adaptor { } /** `Copied` of items JS copies by a function: a `map` whose `nth` and `advance_by` are its iterator's. */ -class CopiedIter extends MapIter {} +class CopiedIter extends MapIter { + override advanceBy(n: number): number { + return this.inner.advanceBy(n); + } + + override advanceBackBy(n: number): number { + return this.inner.advanceBackBy(n); + } + + override nth(n: number): T | Done { + const item = this.inner.nth(n); + return item === DONE ? DONE : this.f(item); + } +} class FilterIter extends Adaptor { private readonly f: (item: T) => boolean; @@ -1369,6 +1127,31 @@ class EnumerateIter extends Adaptor { override len(): number { return this.inner.len(); } + + /** std's, which counts what its iterator skipped. */ + override advanceBy(n: number, drop?: Drop<[number, T]>): number { + const left = this.inner.advanceBy(n, items(drop)); + this.index += n - left; + return left; + } + + override advanceBackBy(n: number, drop?: Drop<[number, T]>): number { + return this.inner.advanceBackBy(n, items(drop)); + } + + /** std's, which counts only when it finds an item. */ + override nth(n: number, drop?: Drop<[number, T]>): [number, T] | Done { + const item = this.inner.nth(n, items(drop)); + if (item === DONE) return DONE; + const i = this.index + n; + this.index = i + 1; + return [i, item]; + } + + override nthBack(n: number, drop?: Drop<[number, T]>): [number, T] | Done { + const item = this.inner.nthBack(n, items(drop)); + return item === DONE ? DONE : [this.index + this.inner.len(), item]; + } } /** @@ -1423,6 +1206,48 @@ class ChainIter extends Iter implements Disposable { () => this.endB(), ); } + + override advanceBy(n: number, drop?: Drop): number { + if (this.a !== undefined) { + n = this.a.advanceBy(n, drop); + if (n === 0) return 0; + this.endA(); + } + return this.b === undefined ? n : this.b.advanceBy(n, drop); + } + + override advanceBackBy(n: number, drop?: Drop): number { + if (this.b !== undefined) { + n = this.b.advanceBackBy(n, drop); + if (n === 0) return 0; + this.endB(); + } + return this.a === undefined ? n : this.a.advanceBackBy(n, drop); + } + + override nth(n: number, drop?: Drop): T | Done { + if (this.a !== undefined) { + n = this.a.advanceBy(n, drop); + if (n === 0) { + const item = this.a.next(); + if (item !== DONE) return item; + } + this.endA(); + } + return this.b === undefined ? DONE : this.b.nth(n, drop); + } + + override nthBack(n: number, drop?: Drop): T | Done { + if (this.b !== undefined) { + n = this.b.advanceBackBy(n, drop); + if (n === 0) { + const item = this.b.nextBack(); + if (item !== DONE) return item; + } + this.endB(); + } + return this.a === undefined ? DONE : this.a.nthBack(n, drop); + } } class ZipIter extends Iter<[A, B]> implements Disposable { @@ -1531,6 +1356,22 @@ class RevIter extends Adaptor { override len(): number { return this.inner.len(); } + + override advanceBy(n: number, drop?: Drop): number { + return this.inner.advanceBackBy(n, drop); + } + + override advanceBackBy(n: number, drop?: Drop): number { + return this.inner.advanceBy(n, drop); + } + + override nth(n: number, drop?: Drop): T | Done { + return this.inner.nthBack(n, drop); + } + + override nthBack(n: number, drop?: Drop): T | Done { + return this.inner.nth(n, drop); + } } /** `Skip`, whose items drop by `drop` as its iterator's own `nth` skips them. */ @@ -1548,7 +1389,7 @@ class SkipIter extends Adaptor { if (this.n === 0) return this.inner.next(); const n = this.n; this.n = 0; - return nth(this.inner, n, this.drop); + return this.inner.nth(n, this.drop); } override nextBack(): T | Done { @@ -1558,6 +1399,50 @@ class SkipIter extends Adaptor { override len(): number { return Math.max(this.inner.len() - this.n, 0); } + + /** std's: what it skips and `n` more in one step, and the rest of `n` if that saturated a `usize`. */ + override advanceBy(n: number, drop?: Drop): number { + const skip = this.n; + const both = Math.min(skip + n, USIZE_MAX); + const left = this.inner.advanceBy(both, drop); + const advanced = both - left; + n -= Math.max(advanced - skip, 0); + this.n = Math.max(skip - advanced, 0); + if (left === 0 && n > 0) n = this.inner.advanceBy(n, drop); + return n; + } + + /** std's: its iterator advanced from the back in one step, short of what it skips. */ + override advanceBackBy(n: number, drop?: Drop): number { + const min = Math.min(this.len(), n); + this.inner.advanceBackBy(min, drop); + return n - min; + } + + /** + * std's: what it still skips and then `n` more, in one step, or past a `usize`'s + * greatest, what it skips in one and `n` in another. + */ + override nth(n: number, drop?: Drop): T | Done { + const skip = this.n; + this.n = 0; + if (skip + n <= USIZE_MAX) return this.inner.nth(skip + n, drop); + const item = this.inner.nth(skip - 1, drop); + if (item === DONE) return DONE; + drop?.(item); + return this.inner.nth(n, drop); + } + + /** std's: past what it doesn't skip, its iterator read from the back through what it does. */ + override nthBack(n: number, drop?: Drop): T | Done { + const len = this.len(); + if (n < len) return this.inner.nthBack(n, drop); + if (len > 0) { + const item = this.inner.nthBack(len - 1, drop); + if (item !== DONE) drop?.(item); + } + return DONE; + } } /** `Take`, of which what its iterator holds past the limit drops by `drop` as `next_back` reads through it. */ @@ -1581,12 +1466,56 @@ class TakeIter extends Adaptor { override nextBack(): T | Done { if (this.n === 0) return DONE; const n = this.n--; - return nthBack(this.inner, Math.max(this.inner.len() - n, 0), this.drop); + return this.inner.nthBack(Math.max(this.inner.len() - n, 0), this.drop); } override len(): number { return Math.min(this.inner.len(), this.n); } + + override advanceBy(n: number, drop?: Drop): number { + const min = Math.min(this.n, n); + const advanced = min - this.inner.advanceBy(min, drop); + this.n -= advanced; + return n - advanced; + } + + /** std's: its iterator advanced from the back past the limit and `n` more, in one step. */ + override advanceBackBy(n: number, drop?: Drop): number { + const trim = Math.max(this.inner.len() - this.n, 0); + const advanced = trim + n - this.inner.advanceBackBy(trim + n, drop) - trim; + this.n -= advanced; + return n - advanced; + } + + /** std's: past the limit, it reads the rest of the limit through, drops it, and ends. */ + override nth(n: number, drop?: Drop): T | Done { + if (this.n > n) { + this.n -= n + 1; + return this.inner.nth(n, drop); + } + if (this.n > 0) { + const item = this.inner.nth(this.n - 1, drop); + if (item !== DONE) drop?.(item); + this.n = 0; + } + return DONE; + } + + /** std's: past the limit, it reads the whole rest from the back, even at a limit of 0. */ + override nthBack(n: number, drop?: Drop): T | Done { + const len = this.inner.len(); + if (this.n > n) { + const m = Math.max(len - this.n, 0) + n; + this.n -= n + 1; + return this.inner.nthBack(m, drop); + } + if (len > 0) { + const item = this.inner.nthBack(len - 1, drop); + if (item !== DONE) drop?.(item); + } + return DONE; + } } class SkipWhileIter extends Adaptor { @@ -1672,11 +1601,11 @@ class StepByIter extends Adaptor { next(): T | Done { const n = this.firstTake ? 0 : this.step; this.firstTake = false; - return nth(this.inner, n, this.drop); + return this.inner.nth(n, this.drop); } override nextBack(): T | Done { - return nthBack(this.inner, this.backIndex(), this.drop); + return this.inner.nthBack(this.backIndex(), this.drop); } /** How far from the back its last item is. */ @@ -1690,6 +1619,44 @@ class StepByIter extends Adaptor { if (this.firstTake) return n === 0 ? 0 : 1 + Math.floor((n - 1) / (this.step + 1)); return Math.floor(n / (this.step + 1)); } + + /** + * std's: the first item, dropped unless it is the one, then every step in one `nth`, + * as many as a `usize` counts at a time. + */ + override nth(n: number, drop?: Drop): T | Done { + if (this.firstTake) { + this.firstTake = false; + const first = this.inner.next(); + if (first === DONE || n === 0) return first; + drop?.(first); + n -= 1; + } + let step = this.step + 1; + if (n === USIZE_MAX) { + const item = this.inner.nth(step - 1, drop); + if (item === DONE) return DONE; + drop?.(item); + } else { + n += 1; + } + for (;;) { + if (n * step <= USIZE_MAX) return this.inner.nth(n * step - 1, drop); + const byN = Math.floor(USIZE_MAX / n) * n; + const byStep = Math.floor(USIZE_MAX / step) * step; + if (byN > byStep) step -= Math.floor(USIZE_MAX / n); + else n -= Math.floor(USIZE_MAX / step); + const item = this.inner.nth(Math.max(byN, byStep) - 1, drop); + if (item === DONE) return DONE; + drop?.(item); + } + } + + /** std's: every step from the back in one, saturating at a `usize`'s greatest. */ + override nthBack(n: number, drop?: Drop): T | Done { + const steps = Math.min(n * (this.step + 1), USIZE_MAX); + return this.inner.nthBack(Math.min(steps + this.backIndex(), USIZE_MAX), drop); + } } class InspectIter extends Adaptor { @@ -1761,6 +1728,14 @@ class FuseIter extends Iter implements Disposable { this.inner = undefined; dispose(inner); } + + override nth(n: number, drop?: Drop): T | Done { + return this.inner === undefined ? DONE : this.clear(this.inner.nth(n, drop)); + } + + override nthBack(n: number, drop?: Drop): T | Done { + return this.inner === undefined ? DONE : this.clear(this.inner.nthBack(n, drop)); + } } /** @@ -1865,6 +1840,67 @@ class FlattenIter extends Iter implements Disposable { ), ); } + + /** + * std's, by `try_fold`: each iterator in turn advanced by its own `advance_by`, one + * that falls short dropped only as the next replaces it, and the source dropped once + * it ends unless it is fused. + */ + override advanceBy(n: number, drop?: Drop): number { + if (this.front !== undefined) { + n = this.front.advanceBy(n, drop); + if (n === 0) return 0; + } + this.setFront(undefined); + const outer = this.outer; + if (outer !== undefined) { + for (let inner = outer.next(); inner !== DONE; inner = outer.next()) { + const front = this.into(inner); + this.setFront(front); + n = front.advanceBy(n, drop); + if (n === 0) return 0; + } + if (!this.fused) { + this.outer = undefined; + dispose(outer); + } + } + this.setFront(undefined); + if (this.back !== undefined) { + n = this.back.advanceBy(n, drop); + if (n === 0) return 0; + } + this.setBack(undefined); + return n; + } + + override advanceBackBy(n: number, drop?: Drop): number { + if (this.back !== undefined) { + n = this.back.advanceBackBy(n, drop); + if (n === 0) return 0; + } + this.setBack(undefined); + const outer = this.outer; + if (outer !== undefined) { + for (let inner = outer.nextBack(); inner !== DONE; inner = outer.nextBack()) { + const back = this.into(inner); + this.setBack(back); + n = back.advanceBackBy(n, drop); + if (n === 0) return 0; + } + if (!this.fused) { + this.outer = undefined; + dispose(outer); + } + } + this.setBack(undefined); + if (this.front !== undefined) { + n = this.front.advanceBackBy(n, drop); + if (n === 0) return 0; + } + this.setFront(undefined); + return n; + } } /** `Peekable`, which drops the item it peeked by `drop`. */ @@ -1916,6 +1952,24 @@ export class Peekable extends Adaptor { }, ); } + + /** std's: the item it peeked drops after what its iterator skips. */ + override nth(n: number, drop?: Drop): T | Done { + if (!this.peeked) return this.inner.nth(n, drop); + const peeked = this.take(); + if (peeked === DONE) return DONE; + if (n === 0) return peeked; + let item: T | Done; + try { + item = this.inner.nth(n - 1, drop); + } catch (e) { + drop?.(peeked); + throw e; + } + // A panic here leaks the item, as std's unwinding does a returned value. + drop?.(peeked); + return item; + } } /** `Peekable::peek`. */ @@ -2012,7 +2066,7 @@ export class Range extends Iter { } /** std's `nth`, in one step: past the end, the range ends. */ - nth(n: number): T | Done { + override nth(n: number): T | Done { const item = step(this.start, n, this.int); if (item !== undefined && lt(item, this.end)) { this.start = step(item, 1, this.int)!; @@ -2023,7 +2077,7 @@ export class Range extends Iter { } /** std's `nth_back`, in one step. */ - nthBack(n: number): T | Done { + override nthBack(n: number): T | Done { const item = step(this.end, -n, this.int); if (item !== undefined && lt(this.start, item)) { this.end = step(item, -1, this.int)!; @@ -2089,7 +2143,7 @@ export class RangeInclusive extends Iter { } /** std's `nth`: `start` moves past the item, wrapping if it overflows, which ends the range. */ - nth(n: number): T | Done { + override nth(n: number): T | Done { if (rangeInclusiveIsEmpty(this)) return DONE; const [item, over] = overflowing(this.lo, n, this.int); const [after, overAfter] = overflowing(item, 1, this.int); @@ -2099,7 +2153,7 @@ export class RangeInclusive extends Iter { } /** std's `nth_back`, from the end. */ - nthBack(n: number): T | Done { + override nthBack(n: number): T | Done { if (rangeInclusiveIsEmpty(this)) return DONE; const [item, over] = overflowing(this.hi, -n, this.int); const [before, overBefore] = overflowing(item, -1, this.int); diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index d3392f155..4a0fcef1c 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -338,8 +338,8 @@ pub fn call<'tcx>( "next" => next(b, self_ty, recv), "next_back" => recv.member("nextBack").call(Vec::new()), _ => { - let dropper = b.t.dropper(item, span); - return Some(Expr::rt("iterNthBack", tail([vec![recv], rest].concat(), vec![dropper]))); + let args = tail([vec![recv], rest].concat(), vec![b.t.dropper(item, span)]); + return Some(Expr::rt("iterNthBack", args)); } }; return Some(Expr::rt("iterToOption", vec![item]));