From 7ed151099bc88b7f06facaeff40d18d3189b5596 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 06:44:10 -0700 Subject: [PATCH 1/9] chore(quest): claim quest/m2/ts-model/bytes.md Quest-Claim: 52d3e75868421f10 From 009c097027ad75088f81dda7da932c9255c6617a Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 07:49:58 -0700 Subject: [PATCH 2/9] feat(ts): map bytes' BytesMut, Buf, and BufMut without config BytesMut is an rt.BytesMut, a window of storage that split_to, split, and freeze share without overlapping. Buf and BufMut of Bytes, BytesMut, &[u8], and Vec map to rt/bytes.ts with bytes' panics; the rest of bytes translates from its MIR. BytesMut's capacity, which depends on whether other handles dropped, is refused. moq's model.toml drops its BytesMut binding. Co-Authored-By: Claude Opus 5.5 --- quest/m2/README.md | 1 + quest/m2/ts-bench-forms.md | 21 + quest/m2/ts-model/README.md | 1 - quest/m2/ts-model/bytes.md | 22 - quest/m3/README.md | 1 + quest/m3/ts-mut-ref.md | 25 + quest/m3/ts-unsafe.md | 4 + ts/MIGRATE.md | 2 + ts/README.md | 28 +- ts/fixtures/reject/census.md | 197 +++---- ts/fixtures/reject/expected.txt | 61 ++- ts/fixtures/reject/src/lib.rs | 9 + ts/fixtures/reject/ts.toml | 1 + ts/fixtures/stock/expected/buf.Ops.ts | 37 ++ ts/fixtures/stock/expected/buf.Pieces.ts | 395 +++++++++++++ ts/fixtures/stock/expected/buf.ts | 467 ++++++++++++++++ .../stock/expected/bytes.TryGetError.ts | 19 + ts/fixtures/stock/expected/bytes.ts | 14 + .../stock/expected/bytes/buf/buf_impl.ts | 113 ++++ ts/fixtures/stock/expected/core/option.ts | 12 + ts/fixtures/stock/expected/core/result.ts | 12 + ts/fixtures/stock/expected/harness.ts | 3 +- ts/fixtures/stock/src/buf.rs | 313 +++++++++++ ts/fixtures/stock/src/harness.rs | 11 +- ts/fixtures/stock/src/lib.rs | 1 + ts/moq/model.toml | 2 - ts/runtime/rt.ts | 2 +- ts/runtime/rt/bytes.ts | 406 +++++++++++++- ts/src/census.rs | 1 + ts/src/lower/fmt.rs | 1 + ts/src/lower/library.rs | 2 + ts/src/lower/mir/decided.rs | 10 +- ts/src/lower/mod.rs | 47 +- ts/src/lower/pointer.rs | 6 +- ts/src/lower/stock.rs | 518 +++++++++++++++++- 35 files changed, 2550 insertions(+), 215 deletions(-) create mode 100644 quest/m2/ts-bench-forms.md delete mode 100644 quest/m2/ts-model/bytes.md create mode 100644 quest/m3/ts-mut-ref.md create mode 100644 ts/fixtures/stock/expected/buf.Ops.ts create mode 100644 ts/fixtures/stock/expected/buf.Pieces.ts create mode 100644 ts/fixtures/stock/expected/buf.ts create mode 100644 ts/fixtures/stock/expected/bytes.TryGetError.ts create mode 100644 ts/fixtures/stock/expected/bytes.ts create mode 100644 ts/fixtures/stock/expected/bytes/buf/buf_impl.ts create mode 100644 ts/fixtures/stock/expected/core/option.ts create mode 100644 ts/fixtures/stock/expected/core/result.ts create mode 100644 ts/fixtures/stock/src/buf.rs diff --git a/quest/m2/README.md b/quest/m2/README.md index c32ab1dd8..2486bb2c9 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -31,6 +31,7 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export/README - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values - [Held values that name a reassigned variable](/quest/m2/ts-aliases.md) - a held place or folded value reads what Rust read, in and across loop iterations - [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 +- [The bench's varint forms at moq's pin](/quest/m2/ts-bench-forms.md) - `just ts bench` runs to its report, its hand-written route decoding each varint form - [Translate against the prebuilt std](/quest/m2/ts-std-build.md) - measure whether `-Zbuild-std` is still needed now that panics abort, and drop it if not - [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-bench-forms.md b/quest/m2/ts-bench-forms.md new file mode 100644 index 000000000..0a50c2865 --- /dev/null +++ b/quest/m2/ts-bench-forms.md @@ -0,0 +1,21 @@ +# [S] The bench's varint forms at moq's pin + +## Goal + +`just ts bench` runs to its report at the moq pin, its hand-written route decoding each +varint form as the codec fixture encodes it. + +## Plan + +Found by [#222](https://github.com/kixelated/rust2/pull/222) on 2026-10-29: #196's pin +dropped `Ietf.DRAFT_16` and `DRAFT_17` from moq's `js/net`, so `bench/moq.ts`'s `FORMS` +passes `undefined` as both versions. moq's `isLeadingOnes` takes any version but lite's +first six as leading ones, so the hand-written decode of `varint/quic/2B` and wider reads +QUIC wire as leading ones and fails the output check. Bun runs `bench/` untyped, so +nothing caught it. + +- Pick each form's version from those moq still has: `Lite.DRAFT_06` for QUIC, and + `Lite.DRAFT_07` or `Ietf.DRAFT_18` for leading ones. #222 measured with `Lite.DRAFT_06`. +- Type-check `bench/` in `just check`, so a pin bump that drops a version fails there. + +Public API: none. diff --git a/quest/m2/ts-model/README.md b/quest/m2/ts-model/README.md index f2acaa588..fc049db58 100644 --- a/quest/m2/ts-model/README.md +++ b/quest/m2/ts-model/README.md @@ -52,5 +52,4 @@ Public API: the translator's output for moq-net's model. - [std gaps kio reaches](/quest/m2/ts-model/kio-std.md) - `array::from_fn`, `Default` of arrays and `()`, maps of `Option`s, and `trailing_zeros` - [hashbrown as the runtime's map](/quest/m2/ts-model/hashbrown.md) - hashlink's `hashbrown` tables translate as `rt.HashMap`, with std's capacity - [A write through a mutable reference to a library object](/quest/m2/ts-model/library-place.md) - `*r = v` out of an `Option` writes the slot, not a copy, and `mem::take` of a `&mut Vec` and writes through guards and map lookups translate -- [bytes' BytesMut, Buf, and BufMut](/quest/m2/ts-model/bytes.md) - map without config, so the model's `BytesMut` binding goes - [Async in the TypeScript translator](/quest/m2/ts-async.md) - kio's producers and consumers are futures diff --git a/quest/m2/ts-model/bytes.md b/quest/m2/ts-model/bytes.md deleted file mode 100644 index 76b070797..000000000 --- a/quest/m2/ts-model/bytes.md +++ /dev/null @@ -1,22 +0,0 @@ -# [M] bytes' BytesMut, Buf, and BufMut - -## Goal - -rust2-ts maps `bytes::BytesMut` and the `Buf` and `BufMut` traits with no config, as -[#147](https://github.com/kixelated/rust2/pull/147) maps `Bytes`, so `ts/moq/model.toml` -drops its `BytesMut` binding and moq-net's code generic over `Buf` and `BufMut` translates. -Proven by differential tests against native Rust. - -## Plan - -Found by #147 on 2026-10-27: the model reaches `BytesMut`, which is bound because its -`unsafe` doesn't translate, and moq-net's codec is generic over `Buf` and `BufMut`. - -- Share `Bytes`'s representation where `BytesMut` freezes into one or splits off, and match - `bytes`' observable behavior: `capacity`, `reserve`'s growth, and what `split_to` and - `freeze` share. -- `Buf` and `BufMut` as generic bounds belong here; `dyn Buf` belongs to - [trait objects](/quest/m3/ts-dyn.md). -- Measure the codec on the [TS benchmark](/ts/README.md#bench) before and after. - -Public API: the translator's output. diff --git a/quest/m3/README.md b/quest/m3/README.md index 23b8a271f..de9b8bd2c 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -17,6 +17,7 @@ generic std gap is planned here even when moq never calls it. - [Relink without rebuilding](/quest/m3/relink.md) - measure upstream's skip of dependency-only rebuilds on moq's edits once it reaches nightly - [Unsafe code the translator can model](/quest/m3/ts-unsafe.md) - a dependency using only `unsafe` the translator can model translates from source - [f32](/quest/m3/ts-f32.md) - `f32` and `Duration`'s `f32` methods translate as `f64` does +- [A mutable reference to a reference](/quest/m3/ts-mut-ref.md) - `&mut &[u8]` and `&mut &mut T` translate, so `Buf` of a `&[u8]` and `bytes`' forwarding impls do - [Trait objects](/quest/m3/ts-dyn.md) - `dyn Error`, `dyn Iterator`, and `dyn Buf` translate, so a consumer neither rewrites nor binds them - [Waiting: type-check in process with tsrs](/quest/m3/ts-tsrs.md) - rust2-ts checks bindings through tsrs instead of `tsc` once it is a stable library - [An inclusive range folded through an adaptor](/quest/m3/ts-range-fold.md) - a `RangeInclusive` folded through `map`, `filter`, or `rev` ends in core's state, and `by_ref` of one type-checks diff --git a/quest/m3/ts-mut-ref.md b/quest/m3/ts-mut-ref.md new file mode 100644 index 000000000..cf0f2fab0 --- /dev/null +++ b/quest/m3/ts-mut-ref.md @@ -0,0 +1,25 @@ +# [M] A mutable reference to a reference + +## Goal + +[rust2-ts](/ts/README.md) translates a `&mut` to a reference, such as `&mut &[u8]` and +`&mut &mut T`, proven by differential tests against native Rust. Then `bytes`' `Buf` of a +`&[u8]` advances, the `Buf` and `BufMut` impls forwarding through `&mut T` translate from +`bytes`' MIR, and so does `Buf::copy_to_bytes` of a crate's own buffer, which reads it +through a `Take<&mut Self>`. + +## Plan + +Found by [#222](https://github.com/kixelated/rust2/pull/222) on 2026-10-29: a `&mut` to a +type JS copies is an `rt.Place`, but a reference is never one, so `&mut &[u8]` is refused +where it is made. moq-net's census refuses `<&mut &[u8] as Buf>::remaining` and +`has_remaining` and `<&[u8] as Buf>::copy_to_bytes` in `transport/memory.rs`, which writes +a `&[u8]` through `poll_write_buf`. + +- Writing a whole reference through it, `*r = &r[n..]`, is what `<&[u8] as Buf>::advance` + does, so a place of the reference is the likely shape, as for a value JS copies. +- Where only what the inner reference points at is read or written, as the forwarding + impls do, the outer reference could be the inner one's value instead. Measure whether + the codec's decode on the [TS benchmark](/ts/README.md#bench) cares. + +Public API: the translator's output. diff --git a/quest/m3/ts-unsafe.md b/quest/m3/ts-unsafe.md index 13551cb41..734e363c4 100644 --- a/quest/m3/ts-unsafe.md +++ b/quest/m3/ts-unsafe.md @@ -38,5 +38,9 @@ none of its own `unsafe`. object there, judged by type over the whole program: a generic function writing a whole `T` counts for every `T` its bounds allow. Judge by the instances translation reaches if a consumer's pointer is refused only by that. +- A slice's pointer cast to an array's of its length, `*(s as *const [u8] as *const + [u8; N])`, which `bytes`' `Buf::get_u16` and wider read a crate's own buffer through + ([#222](https://github.com/kixelated/rust2/pull/222)): the bytes keep their type, so + this reinterprets nothing. Those getters also need `<[u8]>::get` of a range. Public API: the translator's output. diff --git a/ts/MIGRATE.md b/ts/MIGRATE.md index 8db95f8e0..fe4566ae0 100644 --- a/ts/MIGRATE.md +++ b/ts/MIGRATE.md @@ -2,6 +2,8 @@ ## Unreleased +- `bytes::BytesMut` can't be bound: translation maps it, as an `rt.BytesMut`. Delete its + `[bind]` entry and the file it names. - A binding's path names a dependency the package renames (`foo = { package = "bar" }`) as the package does, `foo::Item`, no longer by its crate name, `bar::Item`. - A panic aborts, as on wasm32: the output throws `rt.Panic` without running any cleanup, diff --git a/ts/README.md b/ts/README.md index 64fd9aa0b..20cd26542 100644 --- a/ts/README.md +++ b/ts/README.md @@ -112,6 +112,7 @@ crate translation reaches is refused, and so are two versions of one crate it re | `pin!(x)`, `poll_fn(f)`, `future::pending()` | `x`; `rt.PollFn`, which drops `f` with itself; `rt.NEVER` | | `Box::pin(x)`, `dyn Future` | `x`; `rt.Future`: an `async` body or std's future as it is, and another future as an `rt.DynFuture` over its `poll`, which drops it with itself unless borrowed | | `bytes::Bytes` | `rt.ByteSlice`, as `&[u8]` is: its clones and slices share bytes that never change | +| `bytes::BytesMut` | `rt.BytesMut`: a window of storage, which what it splits off and freezes share without overlapping | | `rand::rngs::ThreadRng` | `rt.ThreadRng`, which holds no state | `Vec` storage and `[x; N]` byte arrays up to 1 KiB share 8 KiB `ArrayBuffer`s, as Node's @@ -306,9 +307,25 @@ of them: - `bytes::Bytes` is an `rt.ByteSlice`. Its constructors, `len`, `is_empty`, `slice`, `Clone`, `Deref`, `AsRef`, `PartialEq` with bytes, `Default`, `Debug`, and `From` between it and `Vec`, `String`, `&'static [u8]`, and `&'static str` map to - `rt/bytes.ts`, panicking as `bytes` does. `Bytes::from_owner` reads its owner's bytes - once, as `bytes` does, and is refused for an owner that drops, which would drop with the - last clone of what it makes. + `rt/bytes.ts`, panicking as `bytes` does, and so do `split_to`, `split_off`, + `truncate`, `clear`, and `slice_ref`, whose panic names no addresses. `Bytes::from_owner` + reads its owner's bytes once, as `bytes` does, and is refused for an owner that drops, + which would drop with the last clone of what it makes. +- `bytes::BytesMut` is an `rt.BytesMut`: a window of storage that the handles `split_to` + and `split` make and the `Bytes` that `freeze` makes share without overlapping, as + `bytes`' do. Its constructors, `len`, `is_empty`, `freeze`, `split_to`, `split`, + `truncate`, `clear`, `resize`, `reserve`, `extend_from_slice`, `unsplit`, `Clone`, + `Deref`, `DerefMut`, `AsRef`, `AsMut`, `PartialEq` with bytes, `Default`, `Debug`, and + `From` between it and `Bytes`, `Vec`, `&[u8]`, and `&str` map, panicking as `bytes` + does. Its capacity is refused, and so are `split_off`, `try_reclaim`, `try_unsplit`, + and `spare_capacity_mut`, which read it: `bytes`' depends on whether the other handles + of its storage dropped, such as a `Bytes` it froze, which nothing here counts. +- `Buf` and `BufMut` of a `Bytes`, a `BytesMut`, a `&[u8]`, and a `Vec` map: the + required methods, `has_remaining`, `copy_to_slice`, `copy_to_bytes`, each `get_` and + `put_` of an integer or `f64`, `put_slice`, `put_bytes`, and `put`, whose panics are + `bytes`'. `put` of the crate's own `Buf` reads it through its methods as `bytes` does. + The rest of `bytes`, such as the provided methods of the crate's own `Buf` and the impls + forwarding through a `&mut` or a `Box`, translates from its MIR, refused where that is. - `rand::rng()` is an `rt.ThreadRng`, whose `random` of an integer or `bool` and `random_range` of an integer range map to `rt/rand.ts`. Each value comes from `crypto.getRandomValues`, uniform as `rand`'s are, though no seed reproduces them, as @@ -600,7 +617,10 @@ built natively for wasm32 and run beside its translation on the same inputs by - `stock` calls `bytes`, `rand`, and `tracing` with no config, against native Rust, whose `rand::rng()` reads the fixture's own getrandom backend on wasm32. It checks `Bytes`'s slices and panics, how each is made and printed, that no event evaluates a field, and - that each random value is in its range, every value of a small range drawn. + that each random value is in its range, every value of a small range drawn. It splits, + freezes, grows, and writes a `BytesMut` by ops its input picks, ending with every + piece's bytes, and reads and writes through `Buf` and `BufMut` generically, a buffer of + its own included. - `bind` binds `buf::Blob`, a renamed dependency's type with `unsafe` inside, and a function and a type of its own that read through raw pointers, the type dropping an `Arc` where Rust drops it, to the TS in `bind/`. Its differential test runs them against native Rust. `wrong.toml` binds TS that doesn't match diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index ea31b3a82..a3c19f70e 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 95 -- Function instances: 104 +- Refusals: 96 +- Function instances: 105 - Generic functions no instance reached, lowered over their type parameters: 7 ## By construct @@ -17,8 +17,8 @@ | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | fixtures/reject/src/lib.rs:16:15 | | 2 | `_` of `_`, whose `None` is `rt.None`, which is not supported yet | fixtures/reject/src/lib.rs:41:42 | | 2 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | fixtures/reject/src/lib.rs:247:16 | -| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | fixtures/reject/src/lib.rs:479:23 | -| 2 | a coercion to `_`, which is not supported yet | fixtures/reject/src/lib.rs:470:40 | +| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | fixtures/reject/src/lib.rs:488:23 | +| 2 | a coercion to `_`, which is not supported yet | fixtures/reject/src/lib.rs:479:40 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:159:1 | | 2 | constructing `_` from another crate | fixtures/reject/src/lib.rs:145:23 | | 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:139:2 | @@ -28,45 +28,46 @@ | 1 | `_` is not supported yet | fixtures/reject/src/lib.rs:393:18 | | 1 | `_` is not supported: its `Pending` and `Ready` would both be `rt.OuterPending` | fixtures/reject/src/lib.rs:105:20 | | 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `None` would be `rt.None` as `_` | fixtures/reject/src/lib.rs:31:2 | -| 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` | fixtures/reject/src/lib.rs:517:2 | +| 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` | fixtures/reject/src/lib.rs:526:2 | | 1 | `_` of `_` by `_`, which is not supported yet | fixtures/reject/src/lib.rs:286:6 | | 1 | `_` of `_`, which drops `_`, which is not supported yet | fixtures/reject/src/lib.rs:53:13 | -| 1 | `_` of `_`, which is not supported yet | fixtures/reject/src/lib.rs:560:4 | +| 1 | `_` of `_`, which is not supported yet | fixtures/reject/src/lib.rs:569:4 | | 1 | `_` through a held type's own, which is not supported yet | fixtures/reject/src/lib.rs:318:2 | -| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | fixtures/reject/src/lib.rs:536:12 | +| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | fixtures/reject/src/lib.rs:545:12 | | 1 | `_`, a trait object of another crate's trait, which is not supported yet | fixtures/reject/src/lib.rs:11:16 | | 1 | `_`, which is not supported yet | fixtures/reject/src/lib.rs:294:9 | -| 1 | `f64::mul_add`, which rounds once, where JS would round twice | fixtures/reject/src/lib.rs:449:4 | +| 1 | `_`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported | fixtures/reject/src/lib.rs:434:6 | +| 1 | `f64::mul_add`, which rounds once, where JS would round twice | fixtures/reject/src/lib.rs:458:4 | | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | fixtures/reject/src/lib.rs:221:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | fixtures/reject/src/lib.rs:172:51 | | 1 | a cast from `_` to `_` | fixtures/reject/src/lib.rs:96:2 | -| 1 | a cast from a pointer to `_` to one to `_`, which reads the bytes of one type as another | fixtures/reject/src/lib.rs:577:27 | +| 1 | a cast from a pointer to `_` to one to `_`, which reads the bytes of one type as another | fixtures/reject/src/lib.rs:586:27 | | 1 | a coercion to `_` | fixtures/reject/src/lib.rs:341:2 | | 1 | a constant of type `_` | fixtures/reject/src/lib.rs:80:2 | -| 1 | a dangling pointer to `_`, a value of no bytes made of more than structs and tuples | fixtures/reject/src/lib.rs:662:11 | +| 1 | a dangling pointer to `_`, a value of no bytes made of more than structs and tuples | fixtures/reject/src/lib.rs:671:11 | | 1 | a future of `_`, which can be `rt.Pending`, as the future's own `Pending` is | fixtures/reject/src/lib.rs:110:34 | | 1 | a mutable borrow of a subslice of `_`, which JS would copy, having no views | fixtures/reject/src/lib.rs:226:13 | | 1 | a mutable reference into a `Result`'s payload, passed on or kept | fixtures/reject/src/lib.rs:413:12 | -| 1 | a pointer's address, which JS has no counterpart of | fixtures/reject/src/lib.rs:582:17 | +| 1 | a pointer's address, which JS has no counterpart of | fixtures/reject/src/lib.rs:591:17 | | 1 | a printable type must implement `Display` or `Debug` | fixtures/reject/src/lib.rs:92:1 | -| 1 | a raw pointer to `_` behind a reference, which is the object and not where it is kept | fixtures/reject/src/lib.rs:599:10 | -| 1 | a raw pointer to `_` in `_`, which the crate may put another object in place of | fixtures/reject/src/lib.rs:630:10 | -| 1 | a raw pointer to `_` in a variable assigned again while it may point there | fixtures/reject/src/lib.rs:638:10 | -| 1 | a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet | fixtures/reject/src/lib.rs:646:10 | +| 1 | a raw pointer to `_` behind a reference, which is the object and not where it is kept | fixtures/reject/src/lib.rs:608:10 | +| 1 | a raw pointer to `_` in `_`, which the crate may put another object in place of | fixtures/reject/src/lib.rs:639:10 | +| 1 | a raw pointer to `_` in a variable assigned again while it may point there | fixtures/reject/src/lib.rs:647:10 | +| 1 | a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet | fixtures/reject/src/lib.rs:655:10 | | 1 | a scalar constant of type `_` | fixtures/reject/src/lib.rs:8:2 | -| 1 | a trait object of `_`, which is not supported yet | fixtures/reject/src/lib.rs:496:26 | +| 1 | a trait object of `_`, which is not supported yet | fixtures/reject/src/lib.rs:505:26 | | 1 | a zero-sized constant of type `_` | fixtures/reject/src/lib.rs:62:2 | -| 1 | an upcast from `_` to `_`, which is not supported yet | fixtures/reject/src/lib.rs:554:32 | +| 1 | an upcast from `_` to `_`, which is not supported yet | fixtures/reject/src/lib.rs:563:32 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:8:2 | | 1 | collecting `_`, whose `None` is `rt.None`, which is not supported yet | fixtures/reject/src/lib.rs:36:43 | | 1 | comparing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:268:52 | -| 1 | comparing pointers to `()`, which has no bytes and so no address of its own | fixtures/reject/src/lib.rs:653:2 | -| 1 | comparing pointers to `_`, each a place JS makes of its own | fixtures/reject/src/lib.rs:618:2 | +| 1 | comparing pointers to `()`, which has no bytes and so no address of its own | fixtures/reject/src/lib.rs:662:2 | +| 1 | comparing pointers to `_`, each a place JS makes of its own | fixtures/reject/src/lib.rs:627:2 | | 1 | constructing `_` | fixtures/reject/src/lib.rs:400:53 | | 1 | hashing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:268:52 | | 1 | hashing `_` through `_`'s own `Hash::hash_slice`, which is not supported yet | fixtures/reject/src/lib.rs:360:16 | | 1 | passing `_`, which drops, to `_`, which is not supported yet | fixtures/reject/src/lib.rs:377:4 | -| 1 | union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart | fixtures/reject/src/lib.rs:604:1 | +| 1 | union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart | fixtures/reject/src/lib.rs:613:1 | ## By API @@ -82,54 +83,55 @@ The type or module each refused type or path belongs to. | 4 | `std::vec::Vec` | fixtures/reject/src/lib.rs:268:52 | | 4 | `u32` | fixtures/reject/src/lib.rs:226:13 | | 4 | `u8` | fixtures/reject/src/lib.rs:80:2 | -| 3 | `(u32, u32)` | fixtures/reject/src/lib.rs:630:10 | +| 3 | `(u32, u32)` | fixtures/reject/src/lib.rs:639:10 | | 3 | `{closure}` | fixtures/reject/src/lib.rs:369:13 | | 2 | `HashMap` | fixtures/reject/src/lib.rs:263:6 | | 2 | `Meters` | fixtures/reject/src/lib.rs:85:2 | | 2 | `Poll` | fixtures/reject/src/lib.rs:105:20 | -| 2 | `Scaled` | fixtures/reject/src/lib.rs:479:23 | -| 2 | `dyn Scaled` | fixtures/reject/src/lib.rs:479:23 | -| 2 | `dyn std::any::Any` | fixtures/reject/src/lib.rs:554:32 | -| 2 | `std::any::TypeId` | fixtures/reject/src/lib.rs:560:2 | +| 2 | `Scaled` | fixtures/reject/src/lib.rs:488:23 | +| 2 | `dyn Scaled` | fixtures/reject/src/lib.rs:488:23 | +| 2 | `dyn std::any::Any` | fixtures/reject/src/lib.rs:563:32 | +| 2 | `std::any::TypeId` | fixtures/reject/src/lib.rs:569:2 | | 2 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:53:13 | | 2 | `std::iter::Iterator` | fixtures/reject/src/lib.rs:247:16 | | 2 | `std::iter::Map` | fixtures/reject/src/lib.rs:145:23 | | 2 | `std::ops::Range` | fixtures/reject/src/lib.rs:180:8 | | 2 | `std::pin::Pin` | fixtures/reject/src/lib.rs:116:2 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:21:4 | -| 2 | `std::std` | fixtures/reject/src/lib.rs:589:11 | -| 2 | `std::vec::IntoIter` | fixtures/reject/src/lib.rs:444:17 | +| 2 | `std::std` | fixtures/reject/src/lib.rs:598:11 | +| 2 | `std::vec::IntoIter` | fixtures/reject/src/lib.rs:453:17 | | 1 | `Batched` | fixtures/reject/src/lib.rs:360:16 | -| 1 | `Bits` | fixtures/reject/src/lib.rs:604:1 | +| 1 | `Bits` | fixtures/reject/src/lib.rs:613:1 | +| 1 | `BytesMut` | fixtures/reject/src/lib.rs:434:6 | | 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:159:1 | | 1 | `Entry` | fixtures/reject/src/lib.rs:369:13 | | 1 | `FusedIterator` | fixtures/reject/src/lib.rs:213:1 | | 1 | `Hasher` | fixtures/reject/src/lib.rs:294:9 | | 1 | `Maybe` | fixtures/reject/src/lib.rs:31:2 | | 1 | `Noisy` | fixtures/reject/src/lib.rs:53:13 | -| 1 | `Only` | fixtures/reject/src/lib.rs:662:11 | -| 1 | `Span2` | fixtures/reject/src/lib.rs:630:10 | +| 1 | `Only` | fixtures/reject/src/lib.rs:671:11 | +| 1 | `Span2` | fixtures/reject/src/lib.rs:639:10 | | 1 | `T \| undefined` | fixtures/reject/src/lib.rs:31:2 | -| 1 | `Tail` | fixtures/reject/src/lib.rs:506:30 | -| 1 | `Waiting` | fixtures/reject/src/lib.rs:517:2 | +| 1 | `Tail` | fixtures/reject/src/lib.rs:515:30 | +| 1 | `Waiting` | fixtures/reject/src/lib.rs:526:2 | | 1 | `[u16; 1]` | fixtures/reject/src/lib.rs:240:22 | -| 1 | `[u8; 4]` | fixtures/reject/src/lib.rs:496:26 | -| 1 | `dyn Keyed` | fixtures/reject/src/lib.rs:554:32 | +| 1 | `[u8; 4]` | fixtures/reject/src/lib.rs:505:26 | +| 1 | `dyn Keyed` | fixtures/reject/src/lib.rs:563:32 | | 1 | `dyn std::iter::Iterator` | fixtures/reject/src/lib.rs:11:16 | -| 1 | `f64` | fixtures/reject/src/lib.rs:454:2 | +| 1 | `f64` | fixtures/reject/src/lib.rs:463:2 | | 1 | `into_keys` | fixtures/reject/src/lib.rs:53:13 | -| 1 | `poll` | fixtures/reject/src/lib.rs:517:2 | -| 1 | `rt.Poll` | fixtures/reject/src/lib.rs:517:2 | -| 1 | `std::any::Any` | fixtures/reject/src/lib.rs:560:4 | +| 1 | `poll` | fixtures/reject/src/lib.rs:526:2 | +| 1 | `rt.Poll` | fixtures/reject/src/lib.rs:526:2 | +| 1 | `std::any::Any` | fixtures/reject/src/lib.rs:569:4 | | 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:172:51 | | 1 | `std::iter::Rev` | fixtures/reject/src/lib.rs:166:14 | | 1 | `std::option::Option` | fixtures/reject/src/lib.rs:420:2 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:126:11 | -| 1 | `std::std::Layout` | fixtures/reject/src/lib.rs:587:15 | +| 1 | `std::std::Layout` | fixtures/reject/src/lib.rs:596:15 | | 1 | `std::string::String` | fixtures/reject/src/lib.rs:74:10 | | 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:121:2 | -| 1 | `std::sync::Mutex` | fixtures/reject/src/lib.rs:536:12 | -| 1 | `std::sync::Weak` | fixtures/reject/src/lib.rs:470:40 | +| 1 | `std::sync::Mutex` | fixtures/reject/src/lib.rs:545:12 | +| 1 | `std::sync::Weak` | fixtures/reject/src/lib.rs:479:40 | | 1 | `std::task::Poll` | fixtures/reject/src/lib.rs:110:34 | | 1 | `str` | fixtures/reject/src/lib.rs:377:4 | | 1 | `u64` | fixtures/reject/src/lib.rs:96:2 | @@ -143,53 +145,54 @@ The type or module each refused type or path belongs to. | 4 | a variant of `_`, which is not supported: either is the same JS string | `std::borrow::Cow` | fixtures/reject/src/lib.rs:382:2 | | 3 | unsupported type `_` | `f32` | fixtures/reject/src/lib.rs:7:14 | | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | `Option` | fixtures/reject/src/lib.rs:16:15 | -| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | `dyn Scaled`, `Scaled` | fixtures/reject/src/lib.rs:479:23 | +| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | `dyn Scaled`, `Scaled` | fixtures/reject/src/lib.rs:488:23 | | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:116:2 | | 2 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:85:2 | -| 2 | unsupported call to `_` | `::sum` | fixtures/reject/src/lib.rs:444:17 | +| 2 | unsupported call to `_` | `::sum` | fixtures/reject/src/lib.rs:453:17 | | 1 | `Bytes::from_owner` of `_`, which would drop with the last clone of what it makes, which is not supported | `std::sync::Arc` | fixtures/reject/src/lib.rs:425:2 | | 1 | `_` is not supported yet | `std::borrow::Cow` | fixtures/reject/src/lib.rs:393:18 | | 1 | `_` is not supported: its `Pending` and `Ready` would both be `rt.OuterPending` | `Poll` | fixtures/reject/src/lib.rs:105:20 | | 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `None` would be `rt.None` as `_` | `Maybe`, `value`, `Option`, `T \| undefined`, `Option` | fixtures/reject/src/lib.rs:31:2 | -| 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` | `Waiting`, `poll`, `Poll`, `rt.Poll`, `Poll` | fixtures/reject/src/lib.rs:517:2 | +| 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` | `Waiting`, `poll`, `Poll`, `rt.Poll`, `Poll` | fixtures/reject/src/lib.rs:526:2 | | 1 | `_` of `_` by `_`, which is not supported yet | `HashMap::contains_key`, `std::collections::HashMap`, `u8` | fixtures/reject/src/lib.rs:286:6 | | 1 | `_` of `_`, which drops `_`, which is not supported yet | `into_keys`, `std::collections::HashMap`, `Noisy` | fixtures/reject/src/lib.rs:53:13 | -| 1 | `_` of `_`, which is not supported yet | `std::any::Any::type_id`, `dyn std::any::Any` | fixtures/reject/src/lib.rs:560:4 | +| 1 | `_` of `_`, which is not supported yet | `std::any::Any::type_id`, `dyn std::any::Any` | fixtures/reject/src/lib.rs:569:4 | | 1 | `_` of `_`, whose `None` is `rt.None`, which is not supported yet | `HashMap::get`, `Option` | fixtures/reject/src/lib.rs:263:6 | | 1 | `_` of `_`, whose `None` is `rt.None`, which is not supported yet | `Iterator::find`, `Option` | fixtures/reject/src/lib.rs:41:42 | | 1 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | `std::iter::Iterator::count` | fixtures/reject/src/lib.rs:247:38 | | 1 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | `std::iter::Iterator::filter` | fixtures/reject/src/lib.rs:247:16 | | 1 | `_` through a held type's own, which is not supported yet | `::ne` | fixtures/reject/src/lib.rs:318:2 | -| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::sync::Mutex::get_mut` | fixtures/reject/src/lib.rs:536:12 | +| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::sync::Mutex::get_mut` | fixtures/reject/src/lib.rs:545:12 | | 1 | `_`, a trait object of another crate's trait, which is not supported yet | `dyn std::iter::Iterator` | fixtures/reject/src/lib.rs:11:16 | | 1 | `_`, which is not supported yet | `Hasher::write` | fixtures/reject/src/lib.rs:294:9 | +| 1 | `_`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported | `BytesMut::capacity` | fixtures/reject/src/lib.rs:434:6 | | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | `std::iter::Map`, `std::ops::Range` | fixtures/reject/src/lib.rs:221:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | `std::iter::Chain` | fixtures/reject/src/lib.rs:172:51 | | 1 | a cast from `_` to `_` | `u64`, `f32` | fixtures/reject/src/lib.rs:96:2 | -| 1 | a cast from a pointer to `_` to one to `_`, which reads the bytes of one type as another | `u32`, `u8` | fixtures/reject/src/lib.rs:577:27 | +| 1 | a cast from a pointer to `_` to one to `_`, which reads the bytes of one type as another | `u32`, `u8` | fixtures/reject/src/lib.rs:586:27 | | 1 | a coercion to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:341:2 | -| 1 | a coercion to `_`, which is not supported yet | `&Tail` | fixtures/reject/src/lib.rs:506:30 | -| 1 | a coercion to `_`, which is not supported yet | `std::sync::Weak` | fixtures/reject/src/lib.rs:470:40 | +| 1 | a coercion to `_`, which is not supported yet | `&Tail` | fixtures/reject/src/lib.rs:515:30 | +| 1 | a coercion to `_`, which is not supported yet | `std::sync::Weak` | fixtures/reject/src/lib.rs:479:40 | | 1 | a constant of type `_` | `&u8` | fixtures/reject/src/lib.rs:80:2 | -| 1 | a dangling pointer to `_`, a value of no bytes made of more than structs and tuples | `Only` | fixtures/reject/src/lib.rs:662:11 | +| 1 | a dangling pointer to `_`, a value of no bytes made of more than structs and tuples | `Only` | fixtures/reject/src/lib.rs:671:11 | | 1 | a future of `_`, which can be `rt.Pending`, as the future's own `Pending` is | `std::task::Poll` | fixtures/reject/src/lib.rs:110:34 | | 1 | a mutable borrow of a subslice of `_`, which JS would copy, having no views | `u32` | fixtures/reject/src/lib.rs:226:13 | -| 1 | a raw pointer to `_` behind a reference, which is the object and not where it is kept | `std::vec::Vec` | fixtures/reject/src/lib.rs:599:10 | -| 1 | a raw pointer to `_` in `_`, which the crate may put another object in place of | `(u32, u32)`, `Span2` | fixtures/reject/src/lib.rs:630:10 | -| 1 | a raw pointer to `_` in a variable assigned again while it may point there | `(u32, u32)` | fixtures/reject/src/lib.rs:638:10 | -| 1 | a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet | `(u32, u32)` | fixtures/reject/src/lib.rs:646:10 | +| 1 | a raw pointer to `_` behind a reference, which is the object and not where it is kept | `std::vec::Vec` | fixtures/reject/src/lib.rs:608:10 | +| 1 | a raw pointer to `_` in `_`, which the crate may put another object in place of | `(u32, u32)`, `Span2` | fixtures/reject/src/lib.rs:639:10 | +| 1 | a raw pointer to `_` in a variable assigned again while it may point there | `(u32, u32)` | fixtures/reject/src/lib.rs:647:10 | +| 1 | a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet | `(u32, u32)` | fixtures/reject/src/lib.rs:655:10 | | 1 | a scalar constant of type `_` | `f32` | fixtures/reject/src/lib.rs:8:2 | -| 1 | a trait object of `_`, which is not supported yet | `[u8; 4]` | fixtures/reject/src/lib.rs:496:26 | +| 1 | a trait object of `_`, which is not supported yet | `[u8; 4]` | fixtures/reject/src/lib.rs:505:26 | | 1 | a zero-sized constant of type `_` | `{async closure}` | fixtures/reject/src/lib.rs:62:2 | | 1 | an assignment through a reference to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:101:2 | | 1 | an assignment through a reference to `_` | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:121:2 | | 1 | an iterator of the crate implementing `_`, which is not supported yet | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:159:1 | | 1 | an iterator of the crate implementing `_`, which is not supported yet | `FusedIterator` | fixtures/reject/src/lib.rs:213:1 | -| 1 | an upcast from `_` to `_`, which is not supported yet | `dyn Keyed`, `dyn std::any::Any` | fixtures/reject/src/lib.rs:554:32 | +| 1 | an upcast from `_` to `_`, which is not supported yet | `dyn Keyed`, `dyn std::any::Any` | fixtures/reject/src/lib.rs:563:32 | | 1 | arithmetic on `_` | `f32` | fixtures/reject/src/lib.rs:8:2 | | 1 | collecting `_`, whose `None` is `rt.None`, which is not supported yet | `Option` | fixtures/reject/src/lib.rs:36:43 | | 1 | comparing `_` as a key, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:268:52 | -| 1 | comparing pointers to `_`, each a place JS makes of its own | `u32` | fixtures/reject/src/lib.rs:618:2 | +| 1 | comparing pointers to `_`, each a place JS makes of its own | `u32` | fixtures/reject/src/lib.rs:627:2 | | 1 | constructing `_` | `std::borrow::Cow` | fixtures/reject/src/lib.rs:400:53 | | 1 | constructing `_` from another crate | `std::iter::Map` | fixtures/reject/src/lib.rs:145:23 | | 1 | constructing `_` from another crate | `std::iter::Rev` | fixtures/reject/src/lib.rs:166:14 | @@ -201,21 +204,21 @@ The type or module each refused type or path belongs to. | 1 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | `{closure}`, `Iterator::for_each` | fixtures/reject/src/lib.rs:370:16 | | 1 | passing `_`, which drops, to `_`, which is not supported yet | `{closure}`, `str::contains` | fixtures/reject/src/lib.rs:377:4 | | 1 | replacing the value behind a reference to `_` | `[u16; 1]` | fixtures/reject/src/lib.rs:240:22 | -| 1 | union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart | `Bits`, `u32` | fixtures/reject/src/lib.rs:604:1 | -| 1 | unsupported call to `_` | `::fmt` | fixtures/reject/src/lib.rs:454:2 | -| 1 | unsupported call to `_` | `::eq` | fixtures/reject/src/lib.rs:560:2 | +| 1 | union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart | `Bits`, `u32` | fixtures/reject/src/lib.rs:613:1 | +| 1 | unsupported call to `_` | `::fmt` | fixtures/reject/src/lib.rs:463:2 | +| 1 | unsupported call to `_` | `::eq` | fixtures/reject/src/lib.rs:569:2 | | 1 | unsupported call to `_` | `::deref` | fixtures/reject/src/lib.rs:394:2 | | 1 | unsupported call to `_` | `::eq` | fixtures/reject/src/lib.rs:420:2 | | 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:126:11 | | 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:74:10 | | 1 | unsupported call to `_` | `::hash` | fixtures/reject/src/lib.rs:351:10 | -| 1 | unsupported call to `_` | `std::any::TypeId::of` | fixtures/reject/src/lib.rs:560:17 | +| 1 | unsupported call to `_` | `std::any::TypeId::of` | fixtures/reject/src/lib.rs:569:17 | | 1 | unsupported call to `_` | `std::ops::Range::contains` | fixtures/reject/src/lib.rs:180:8 | | 1 | unsupported call to `_` | `std::slice::copy_within` | fixtures/reject/src/lib.rs:336:4 | | 1 | unsupported call to `_` | `std::slice::rotate_left` | fixtures/reject/src/lib.rs:21:4 | -| 1 | unsupported call to `_` | `std::std::Layout::new` | fixtures/reject/src/lib.rs:587:15 | -| 1 | unsupported call to `_` | `std::std::alloc` | fixtures/reject/src/lib.rs:589:11 | -| 1 | unsupported call to `_` | `std::std::dealloc` | fixtures/reject/src/lib.rs:592:3 | +| 1 | unsupported call to `_` | `std::std::Layout::new` | fixtures/reject/src/lib.rs:596:15 | +| 1 | unsupported call to `_` | `std::std::alloc` | fixtures/reject/src/lib.rs:598:11 | +| 1 | unsupported call to `_` | `std::std::dealloc` | fixtures/reject/src/lib.rs:601:3 | ## Spans @@ -229,14 +232,14 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:351:10: unsupported call to `::hash::` - fixtures/reject/src/lib.rs:394:2: unsupported call to ` as std::ops::Deref>::deref` - fixtures/reject/src/lib.rs:420:2: unsupported call to ` as std::cmp::PartialEq>::eq` -- fixtures/reject/src/lib.rs:444:17: unsupported call to ` as std::iter::Iterator>::sum::` -- fixtures/reject/src/lib.rs:444:38: unsupported call to ` as std::iter::Iterator>::sum::` -- fixtures/reject/src/lib.rs:454:2: unsupported call to `::fmt` -- fixtures/reject/src/lib.rs:560:2: unsupported call to `::eq` -- fixtures/reject/src/lib.rs:560:17: unsupported call to `std::any::TypeId::of::` -- fixtures/reject/src/lib.rs:587:15: unsupported call to `std::alloc::Layout::new::` -- fixtures/reject/src/lib.rs:589:11: unsupported call to `std::alloc::alloc` -- fixtures/reject/src/lib.rs:592:3: unsupported call to `std::alloc::dealloc` +- fixtures/reject/src/lib.rs:453:17: unsupported call to ` as std::iter::Iterator>::sum::` +- fixtures/reject/src/lib.rs:453:38: unsupported call to ` as std::iter::Iterator>::sum::` +- fixtures/reject/src/lib.rs:463:2: unsupported call to `::fmt` +- fixtures/reject/src/lib.rs:569:2: unsupported call to `::eq` +- fixtures/reject/src/lib.rs:569:17: unsupported call to `std::any::TypeId::of::` +- fixtures/reject/src/lib.rs:596:15: unsupported call to `std::alloc::Layout::new::` +- fixtures/reject/src/lib.rs:598:11: unsupported call to `std::alloc::alloc` +- fixtures/reject/src/lib.rs:601:3: unsupported call to `std::alloc::dealloc` @@ -261,8 +264,8 @@ The type or module each refused type or path belongs to.
a copy of a closure that changes what it captured (3) - fixtures/reject/src/lib.rs:257:14: a copy of a closure that changes what it captured -- fixtures/reject/src/lib.rs:529:14: a copy of a closure that changes what it captured -- fixtures/reject/src/lib.rs:530:14: a copy of a closure that changes what it captured +- fixtures/reject/src/lib.rs:538:14: a copy of a closure that changes what it captured +- fixtures/reject/src/lib.rs:539:14: a copy of a closure that changes what it captured
@@ -305,15 +308,15 @@ The type or module each refused type or path belongs to.
`_`, a trait object of the generic trait `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:479:23: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet -- fixtures/reject/src/lib.rs:480:4: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet +- fixtures/reject/src/lib.rs:488:23: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet +- fixtures/reject/src/lib.rs:489:4: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet
a coercion to `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:470:40: a coercion to `std::sync::Weak`, which is not supported yet -- fixtures/reject/src/lib.rs:506:30: a coercion to `&Tail`, which is not supported yet +- fixtures/reject/src/lib.rs:479:40: a coercion to `std::sync::Weak`, which is not supported yet +- fixtures/reject/src/lib.rs:515:30: a coercion to `&Tail`, which is not supported yet
@@ -377,7 +380,7 @@ The type or module each refused type or path belongs to.
`_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` (1) -- fixtures/reject/src/lib.rs:517:2: `Waiting>` is not supported: its field `poll` is `Poll`, typed `rt.Poll`, whose `Pending` would be `rt.OuterPending` as `Poll>` +- fixtures/reject/src/lib.rs:526:2: `Waiting>` is not supported: its field `poll` is `Poll`, typed `rt.Poll`, whose `Pending` would be `rt.OuterPending` as `Poll>`
@@ -395,7 +398,7 @@ The type or module each refused type or path belongs to.
`_` of `_`, which is not supported yet (1) -- fixtures/reject/src/lib.rs:560:4: `std::any::Any::type_id` of `dyn std::any::Any`, which is not supported yet +- fixtures/reject/src/lib.rs:569:4: `std::any::Any::type_id` of `dyn std::any::Any`, which is not supported yet
@@ -407,7 +410,7 @@ The type or module each refused type or path belongs to.
`_` with a mutable reference to a value JS copies, which its mapping would copy (1) -- fixtures/reject/src/lib.rs:536:12: `std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy +- fixtures/reject/src/lib.rs:545:12: `std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy
@@ -423,9 +426,15 @@ The type or module each refused type or path belongs to. +
`_`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported (1) + +- fixtures/reject/src/lib.rs:434:6: `BytesMut::capacity`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported + +
+
`f64::mul_add`, which rounds once, where JS would round twice (1) -- fixtures/reject/src/lib.rs:449:4: `f64::mul_add`, which rounds once, where JS would round twice +- fixtures/reject/src/lib.rs:458:4: `f64::mul_add`, which rounds once, where JS would round twice
@@ -449,7 +458,7 @@ The type or module each refused type or path belongs to.
a cast from a pointer to `_` to one to `_`, which reads the bytes of one type as another (1) -- fixtures/reject/src/lib.rs:577:27: a cast from a pointer to `u32` to one to `u8`, which reads the bytes of one type as another +- fixtures/reject/src/lib.rs:586:27: a cast from a pointer to `u32` to one to `u8`, which reads the bytes of one type as another
@@ -467,7 +476,7 @@ The type or module each refused type or path belongs to.
a dangling pointer to `_`, a value of no bytes made of more than structs and tuples (1) -- fixtures/reject/src/lib.rs:662:11: a dangling pointer to `Only`, a value of no bytes made of more than structs and tuples +- fixtures/reject/src/lib.rs:671:11: a dangling pointer to `Only`, a value of no bytes made of more than structs and tuples
@@ -491,7 +500,7 @@ The type or module each refused type or path belongs to.
a pointer's address, which JS has no counterpart of (1) -- fixtures/reject/src/lib.rs:582:17: a pointer's address, which JS has no counterpart of +- fixtures/reject/src/lib.rs:591:17: a pointer's address, which JS has no counterpart of
@@ -503,25 +512,25 @@ The type or module each refused type or path belongs to.
a raw pointer to `_` behind a reference, which is the object and not where it is kept (1) -- fixtures/reject/src/lib.rs:599:10: a raw pointer to `std::vec::Vec` behind a reference, which is the object and not where it is kept +- fixtures/reject/src/lib.rs:608:10: a raw pointer to `std::vec::Vec` behind a reference, which is the object and not where it is kept
a raw pointer to `_` in `_`, which the crate may put another object in place of (1) -- fixtures/reject/src/lib.rs:630:10: a raw pointer to `(u32, u32)` in `Span2`, which the crate may put another object in place of +- fixtures/reject/src/lib.rs:639:10: a raw pointer to `(u32, u32)` in `Span2`, which the crate may put another object in place of
a raw pointer to `_` in a variable assigned again while it may point there (1) -- fixtures/reject/src/lib.rs:638:10: a raw pointer to `(u32, u32)` in a variable assigned again while it may point there +- fixtures/reject/src/lib.rs:647:10: a raw pointer to `(u32, u32)` in a variable assigned again while it may point there
a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet (1) -- fixtures/reject/src/lib.rs:646:10: a raw pointer to `(u32, u32)` in an element, a payload, or a union field, which is not supported yet +- fixtures/reject/src/lib.rs:655:10: a raw pointer to `(u32, u32)` in an element, a payload, or a union field, which is not supported yet
@@ -533,7 +542,7 @@ The type or module each refused type or path belongs to.
a trait object of `_`, which is not supported yet (1) -- fixtures/reject/src/lib.rs:496:26: a trait object of `[u8; 4]`, which is not supported yet +- fixtures/reject/src/lib.rs:505:26: a trait object of `[u8; 4]`, which is not supported yet
@@ -545,7 +554,7 @@ The type or module each refused type or path belongs to.
an upcast from `_` to `_`, which is not supported yet (1) -- fixtures/reject/src/lib.rs:554:32: an upcast from `dyn Keyed` to `dyn std::any::Any`, which is not supported yet +- fixtures/reject/src/lib.rs:563:32: an upcast from `dyn Keyed` to `dyn std::any::Any`, which is not supported yet
@@ -569,13 +578,13 @@ The type or module each refused type or path belongs to.
comparing pointers to `()`, which has no bytes and so no address of its own (1) -- fixtures/reject/src/lib.rs:653:2: comparing pointers to `()`, which has no bytes and so no address of its own +- fixtures/reject/src/lib.rs:662:2: comparing pointers to `()`, which has no bytes and so no address of its own
comparing pointers to `_`, each a place JS makes of its own (1) -- fixtures/reject/src/lib.rs:618:2: comparing pointers to `u32`, each a place JS makes of its own +- fixtures/reject/src/lib.rs:627:2: comparing pointers to `u32`, each a place JS makes of its own
@@ -605,6 +614,6 @@ The type or module each refused type or path belongs to.
union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart (1) -- fixtures/reject/src/lib.rs:604:1: union `Bits`, whose fields overlap in `u32` and `f64`, which JS keeps apart +- fixtures/reject/src/lib.rs:613:1: union `Bits`, whose fields overlap in `u32` and `f64`, which JS keeps apart
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 002db3fef..6d7542e77 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -54,39 +54,40 @@ hashing `std::vec::Vec` through `Batched`'s own `Hash::hash_slice`, whi passing `{closure@fixtures/reject/src/lib.rs:369:28: 369:35}`, a closure that owns a value that drops, to `Entry::or_insert_with`, which is not supported yet at fixtures/reject/src/lib.rs:369:13 passing `{closure@fixtures/reject/src/lib.rs:370:25: 370:33}`, a closure that owns a value that drops, to `Iterator::for_each`, which is not supported yet at fixtures/reject/src/lib.rs:370:16 passing `{closure@fixtures/reject/src/lib.rs:377:13: 377:27}`, which drops, to `str::contains`, which is not supported yet at fixtures/reject/src/lib.rs:377:4 -unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:444:17 -unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:444:38 +unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:453:17 +unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:453:38 a mutable reference into a `Result`'s payload, passed on or kept at fixtures/reject/src/lib.rs:413:12 unsupported call to ` as std::cmp::PartialEq>::eq` at fixtures/reject/src/lib.rs:420:2 `Bytes::from_owner` of `std::sync::Arc<[u8]>`, which would drop with the last clone of what it makes, which is not supported at fixtures/reject/src/lib.rs:425:2 -`f64::mul_add`, which rounds once, where JS would round twice at fixtures/reject/src/lib.rs:449:4 -unsupported call to `::fmt` at fixtures/reject/src/lib.rs:454:11 -a coercion to `std::sync::Weak`, which is not supported yet at fixtures/reject/src/lib.rs:470:40 -`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:479:23 -`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:480:4 -a trait object of `[u8; 4]`, which is not supported yet at fixtures/reject/src/lib.rs:496:26 -a coercion to `&Tail`, which is not supported yet at fixtures/reject/src/lib.rs:506:30 -`std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:536:12 -`Waiting>` is not supported: its field `poll` is `Poll`, typed `rt.Poll`, whose `Pending` would be `rt.OuterPending` as `Poll>` at fixtures/reject/src/lib.rs:517:2 -a copy of a closure that changes what it captured at fixtures/reject/src/lib.rs:529:14 -a copy of a closure that changes what it captured at fixtures/reject/src/lib.rs:530:14 -an upcast from `dyn Keyed` to `dyn std::any::Any`, which is not supported yet at fixtures/reject/src/lib.rs:554:32 -`std::any::Any::type_id` of `dyn std::any::Any`, which is not supported yet at fixtures/reject/src/lib.rs:560:4 -unsupported call to `std::any::TypeId::of::` at fixtures/reject/src/lib.rs:560:17 -unsupported call to `::eq` at fixtures/reject/src/lib.rs:560:2 -a cast from a pointer to `u32` to one to `u8`, which reads the bytes of one type as another at fixtures/reject/src/lib.rs:577:27 -a pointer's address, which JS has no counterpart of at fixtures/reject/src/lib.rs:582:17 -unsupported call to `std::alloc::Layout::new::` at fixtures/reject/src/lib.rs:587:15 -unsupported call to `std::alloc::alloc` at fixtures/reject/src/lib.rs:589:11 -unsupported call to `std::alloc::dealloc` at fixtures/reject/src/lib.rs:592:3 -a raw pointer to `std::vec::Vec` behind a reference, which is the object and not where it is kept at fixtures/reject/src/lib.rs:599:10 -union `Bits`, whose fields overlap in `u32` and `f64`, which JS keeps apart at fixtures/reject/src/lib.rs:610:10 -comparing pointers to `u32`, each a place JS makes of its own at fixtures/reject/src/lib.rs:618:2 -a raw pointer to `(u32, u32)` in `Span2`, which the crate may put another object in place of at fixtures/reject/src/lib.rs:630:10 -a raw pointer to `(u32, u32)` in a variable assigned again while it may point there at fixtures/reject/src/lib.rs:638:10 -a raw pointer to `(u32, u32)` in an element, a payload, or a union field, which is not supported yet at fixtures/reject/src/lib.rs:646:10 -comparing pointers to `()`, which has no bytes and so no address of its own at fixtures/reject/src/lib.rs:653:2 -a dangling pointer to `Only`, a value of no bytes made of more than structs and tuples at fixtures/reject/src/lib.rs:662:11 +`BytesMut::capacity`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported at fixtures/reject/src/lib.rs:434:6 +`f64::mul_add`, which rounds once, where JS would round twice at fixtures/reject/src/lib.rs:458:4 +unsupported call to `::fmt` at fixtures/reject/src/lib.rs:463:11 +a coercion to `std::sync::Weak`, which is not supported yet at fixtures/reject/src/lib.rs:479:40 +`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:488:23 +`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:489:4 +a trait object of `[u8; 4]`, which is not supported yet at fixtures/reject/src/lib.rs:505:26 +a coercion to `&Tail`, which is not supported yet at fixtures/reject/src/lib.rs:515:30 +`std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:545:12 +`Waiting>` is not supported: its field `poll` is `Poll`, typed `rt.Poll`, whose `Pending` would be `rt.OuterPending` as `Poll>` at fixtures/reject/src/lib.rs:526:2 +a copy of a closure that changes what it captured at fixtures/reject/src/lib.rs:538:14 +a copy of a closure that changes what it captured at fixtures/reject/src/lib.rs:539:14 +an upcast from `dyn Keyed` to `dyn std::any::Any`, which is not supported yet at fixtures/reject/src/lib.rs:563:32 +`std::any::Any::type_id` of `dyn std::any::Any`, which is not supported yet at fixtures/reject/src/lib.rs:569:4 +unsupported call to `std::any::TypeId::of::` at fixtures/reject/src/lib.rs:569:17 +unsupported call to `::eq` at fixtures/reject/src/lib.rs:569:2 +a cast from a pointer to `u32` to one to `u8`, which reads the bytes of one type as another at fixtures/reject/src/lib.rs:586:27 +a pointer's address, which JS has no counterpart of at fixtures/reject/src/lib.rs:591:17 +unsupported call to `std::alloc::Layout::new::` at fixtures/reject/src/lib.rs:596:15 +unsupported call to `std::alloc::alloc` at fixtures/reject/src/lib.rs:598:11 +unsupported call to `std::alloc::dealloc` at fixtures/reject/src/lib.rs:601:3 +a raw pointer to `std::vec::Vec` behind a reference, which is the object and not where it is kept at fixtures/reject/src/lib.rs:608:10 +union `Bits`, whose fields overlap in `u32` and `f64`, which JS keeps apart at fixtures/reject/src/lib.rs:619:10 +comparing pointers to `u32`, each a place JS makes of its own at fixtures/reject/src/lib.rs:627:2 +a raw pointer to `(u32, u32)` in `Span2`, which the crate may put another object in place of at fixtures/reject/src/lib.rs:639:10 +a raw pointer to `(u32, u32)` in a variable assigned again while it may point there at fixtures/reject/src/lib.rs:647:10 +a raw pointer to `(u32, u32)` in an element, a payload, or a union field, which is not supported yet at fixtures/reject/src/lib.rs:655:10 +comparing pointers to `()`, which has no bytes and so no address of its own at fixtures/reject/src/lib.rs:662:2 +a dangling pointer to `Only`, a value of no bytes made of more than structs and tuples at fixtures/reject/src/lib.rs:671:11 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:139:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:159:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:193:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index c739c603e..f58f75912 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -425,6 +425,15 @@ pub fn owned_bytes(owner: std::sync::Arc<[u8]>) -> usize { bytes::Bytes::from_owner(owner).len() } +/// A `BytesMut`'s capacity, which `bytes` reclaims only once the `Bytes` it froze drops. +pub fn bytes_mut_capacity(n: usize) -> usize { + let mut buf = bytes::BytesMut::with_capacity(n); + buf.extend_from_slice(b"frame"); + drop(buf.split_to(2).freeze()); + buf.reserve(n); + buf.capacity() +} + pub struct Part(pub u64); impl std::iter::Sum for std::time::Duration { diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 1ad180351..e8921bf65 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -52,6 +52,7 @@ roots = [ "ok_passed", "places_equal", "owned_bytes", + "bytes_mut_capacity", "fma", "float_printed", "weak_object", diff --git a/ts/fixtures/stock/expected/buf.Ops.ts b/ts/fixtures/stock/expected/buf.Ops.ts new file mode 100644 index 000000000..d264f4fef --- /dev/null +++ b/ts/fixtures/stock/expected/buf.Ops.ts @@ -0,0 +1,37 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { unwrapOr$Option_u8 } from "./core/option.ts"; + +/** The bytes of a case's input, taken from the front. */ +export interface Ops { + _0: rt.ByteSlice; +} + +export function next(self: Ops): rt.u8 | undefined { + const slice: rt.ByteSlice = self._0; + if (slice.length !== 0) { + const first: rt.u8 = slice.data[slice.start]; + self._0 = new rt.ByteSlice(slice.data, slice.start + 1, slice.length - 1); + return first; + } + return undefined; +} + +export function byte(self: Ops): rt.u8 { + return unwrapOr$Option_u8(next(self), 0); +} + +export function take(self: Ops, n: rt.usize): rt.ByteSlice { + const _7: rt.ByteSlice = self._0; + const _5: rt.usize = rt.min(n, self._0.length); + const slice: rt.ByteSlice = _7; + if (_5 > slice.length) { + rt.panic("mid > len"); + } + const taken: rt.ByteSlice = new rt.ByteSlice(slice.data, slice.start, _5); + self._0 = new rt.ByteSlice(slice.data, slice.start + _5, slice.length - _5); + return taken; +} + +//# sourceMappingURL=buf.Ops.ts.map diff --git a/ts/fixtures/stock/expected/buf.Pieces.ts b/ts/fixtures/stock/expected/buf.Pieces.ts new file mode 100644 index 000000000..1fd25467f --- /dev/null +++ b/ts/fixtures/stock/expected/buf.Pieces.ts @@ -0,0 +1,395 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { panicAdvance } from "./bytes.ts"; +import type * as TryGetError from "./bytes.TryGetError.ts"; +import { unwrapOrElse$Result_unit_TryGetError_copy_to_slice_closure0 } from "./core/result.ts"; + +/** A buffer of the crate's own, in pieces: `Buf`'s provided methods read across them. */ +export interface Pieces { + /** None empty, so `chunk` is empty only once nothing remains, as `Buf` requires. */ + parts: rt.ByteVec[]; + /** How far into the first part reads are. */ + at: rt.usize; +} + +/** `input` in two parts, cut at `cut`. */ +function new_(input: rt.ByteSlice, cut: rt.usize): Pieces { + if (cut > input.length) { + rt.panic("mid > len"); + } + const parts: rt.ByteVec[] = [rt.byteSliceToByteVec(new rt.ByteSlice(input.data, input.start, cut)), rt.byteSliceToByteVec(new rt.ByteSlice(input.data, input.start + cut, input.length - cut))]; + rt.vecRetain(parts, (part: rt.ByteVec): boolean => { + return !((part.length === 0)); + }); + return { parts, at: 0 }; +} + +/** + * Returns the number of bytes between the current position and the end of + * the buffer. + * + * This value is greater than or equal to the length of the slice returned + * by `chunk()`. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"hello world"[..]; + * + * assert_eq!(buf.remaining(), 11); + * + * buf.get_u8(); + * + * assert_eq!(buf.remaining(), 10); + * ``` + * + * # Implementer notes + * + * Implementations of `remaining` should ensure that the return value does + * not change unless a call is made to `advance` or any other function that + * is documented to change the `Buf`'s current position. + */ +export function remaining$Buf(self: Pieces): rt.usize { + return rt.usizeSub(rt.iterSum(rt.iterMap(rt.iterSlice(self.parts), (a0: rt.ByteVec): rt.usize => { + return a0.length; + }), rt.usizeAdd, 0), self.at); +} + +/** + * Returns a slice starting at the current position and of length between 0 + * and `Buf::remaining()`. Note that this *can* return a shorter slice (this + * allows non-continuous internal representation). + * + * This is a lower level function. Most operations are done with other + * functions. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"hello world"[..]; + * + * assert_eq!(buf.chunk(), &b"hello world"[..]); + * + * buf.advance(6); + * + * assert_eq!(buf.chunk(), &b"world"[..]); + * ``` + * + * # Implementer notes + * + * This function should never panic. `chunk()` should return an empty + * slice **if and only if** `remaining()` returns 0. In other words, + * `chunk()` returning an empty slice implies that `remaining()` will + * return 0 and `remaining()` returning 0 implies that `chunk()` will + * return an empty slice. + */ +export function chunk$Buf(self: Pieces): rt.ByteSlice { + const _3: rt.ByteVec | undefined = rt.sliceFirst(self.parts); + if (_3 === undefined) { + return rt.byteSliceFrom(Uint8Array.of()); + } + const part = self.at; + return rt.byteSliceRange(rt.byteVecSlice(_3), part); +} + +/** + * Advance the internal cursor of the Buf + * + * The next call to `chunk()` will return a slice starting `cnt` bytes + * further into the underlying buffer. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"hello world"[..]; + * + * assert_eq!(buf.chunk(), &b"hello world"[..]); + * + * buf.advance(6); + * + * assert_eq!(buf.chunk(), &b"world"[..]); + * ``` + * + * # Panics + * + * This function **may** panic if `cnt > self.remaining()`. + * + * # Implementer notes + * + * It is recommended for implementations of `advance` to panic if `cnt > + * self.remaining()`. If the implementation does not panic, the call must + * behave as if `cnt == self.remaining()`. + * + * A call with `cnt == 0` should never panic and be a no-op. + */ +export function advance$Buf(self: Pieces, cnt: rt.usize): void { + while (cnt > 0) { + const left: rt.usize = rt.usizeSub(self.parts[rt.idx(self.parts, 0)].length, self.at); + if (!(cnt < left)) { + cnt = rt.usizeSub(cnt, left); + rt.vecRemove(self.parts, 0); + self.at = 0; + } else { + self.at = rt.usizeAdd(self.at, cnt); + break; + } + } +} + +/** + * Consumes `len` bytes inside self and returns new instance of `Bytes` + * with this data. + * + * This function may be optimized by the underlying type to avoid actual + * copies. For example, `Bytes` implementation will do a shallow copy + * (ref-count increment). + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let bytes = (&b"hello world"[..]).copy_to_bytes(5); + * assert_eq!(&bytes[..], &b"hello"[..]); + * ``` + * + * # Panics + * + * This function panics if `len > self.remaining()`. + */ +export function copyToBytes$Buf(self: Pieces, len: rt.usize): rt.ByteSlice { + const out: rt.BytesMut = rt.bytesMutWithCapacity(len); + while (out.length < len) { + const take: rt.usize = rt.min(chunk$Buf$2(self).length, rt.usizeSub(len, out.length)); + const _17: rt.ByteSlice = rt.byteSliceRange(chunk$Buf$2(self), 0, take); + rt.bytesMutExtend(out, _17); + advance$Buf(self, take); + } + return rt.bytesMutFreeze(out); +} + +/** + * Returns true if there are any more bytes to consume + * + * This is equivalent to `self.remaining() != 0`. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"a"[..]; + * + * assert!(buf.has_remaining()); + * + * buf.get_u8(); + * + * assert!(!buf.has_remaining()); + * ``` + */ +export function hasRemaining$Buf(self: Pieces): boolean { + return remaining$Buf(self) > 0; +} + +/** + * Copies bytes from `self` into `dst`. + * + * The cursor is advanced by the number of bytes copied. `self` must have + * enough remaining bytes to fill `dst`. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"hello world"[..]; + * let mut dst = [0; 5]; + * + * buf.copy_to_slice(&mut dst); + * assert_eq!(&b"hello"[..], &dst); + * assert_eq!(6, buf.remaining()); + * ``` + * + * # Panics + * + * This function panics if `self.remaining() < dst.len()`. + */ +export function copyToSlice$Buf(self: Pieces, dst: rt.ByteSlice): void { + unwrapOrElse$Result_unit_TryGetError_copy_to_slice_closure0(tryCopyToSlice$Buf(self, dst), (error: TryGetError.TryGetError): void => { + panicAdvance(error); + }); +} + +/** + * Gets an unsigned 8 bit integer from `self`. + * + * The current position is advanced by 1. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"\x08 hello"[..]; + * assert_eq!(8, buf.get_u8()); + * ``` + * + * # Panics + * + * This function panics if there is no more remaining data in `self`. + */ +export function getU8$Buf(self: Pieces): rt.u8 { + if (!(remaining$Buf$2(self) < 1)) { + const _7: rt.ByteSlice = chunk$Buf$2(self); + rt.idx(_7, 0); + const ret: rt.u8 = _7.data[_7.start]; + advance$Buf(self, 1); + return ret; + } + panicAdvance({ requested: 1, available: 0 }); +} + +/** + * Copies bytes from `self` into `dst`. + * + * The cursor is advanced by the number of bytes copied. `self` must have + * enough remaining bytes to fill `dst`. + * + * Returns `Err(TryGetError)` when there are not enough + * remaining bytes to read the value. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"hello world"[..]; + * let mut dst = [0; 5]; + * + * assert_eq!(Ok(()), buf.try_copy_to_slice(&mut dst)); + * assert_eq!(&b"hello"[..], &dst); + * assert_eq!(6, buf.remaining()); + * ``` + * + * ``` + * use bytes::{Buf, TryGetError}; + * + * let mut buf = &b"hello world"[..]; + * let mut dst = [0; 12]; + * + * assert_eq!(Err(TryGetError{requested: 12, available: 11}), buf.try_copy_to_slice(&mut dst)); + * assert_eq!(11, buf.remaining()); + * ``` + */ +export function tryCopyToSlice$Buf(self: Pieces, dst: rt.ByteSlice): rt.Result { + if (!(remaining$Buf$2(self) < dst.length)) { + while (!(dst.length === 0)) { + const src: rt.ByteSlice = chunk$Buf$2(self); + const cnt: rt.usize = rt.min(src.length, dst.length); + rt.byteSliceCopyFromSlice(rt.byteSliceRange(dst, 0, cnt), rt.byteSliceRange(src, 0, cnt)); + dst = rt.byteSliceRange(dst, cnt); + advance$Buf(self, cnt); + } + return rt.OK; + } + return rt.Err({ requested: dst.length, available: remaining$Buf$2(self) }); +} + +/** + * Returns a slice starting at the current position and of length between 0 + * and `Buf::remaining()`. Note that this *can* return a shorter slice (this + * allows non-continuous internal representation). + * + * This is a lower level function. Most operations are done with other + * functions. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"hello world"[..]; + * + * assert_eq!(buf.chunk(), &b"hello world"[..]); + * + * buf.advance(6); + * + * assert_eq!(buf.chunk(), &b"world"[..]); + * ``` + * + * # Implementer notes + * + * This function should never panic. `chunk()` should return an empty + * slice **if and only if** `remaining()` returns 0. In other words, + * `chunk()` returning an empty slice implies that `remaining()` will + * return 0 and `remaining()` returning 0 implies that `chunk()` will + * return an empty slice. + */ +export function chunk$Buf$2(self: Pieces): rt.ByteSlice { + return chunk$Buf(self); +} + +/** + * Returns true if there are any more bytes to consume + * + * This is equivalent to `self.remaining() != 0`. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"a"[..]; + * + * assert!(buf.has_remaining()); + * + * buf.get_u8(); + * + * assert!(!buf.has_remaining()); + * ``` + */ +export function hasRemaining$Buf$2(self: Pieces): boolean { + return hasRemaining$Buf(self); +} + +/** + * Returns the number of bytes between the current position and the end of + * the buffer. + * + * This value is greater than or equal to the length of the slice returned + * by `chunk()`. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"hello world"[..]; + * + * assert_eq!(buf.remaining(), 11); + * + * buf.get_u8(); + * + * assert_eq!(buf.remaining(), 10); + * ``` + * + * # Implementer notes + * + * Implementations of `remaining` should ensure that the return value does + * not change unless a call is made to `advance` or any other function that + * is documented to change the `Buf`'s current position. + */ +export function remaining$Buf$2(self: Pieces): rt.usize { + return remaining$Buf(self); +} + +export { new_ as new }; + +//# sourceMappingURL=buf.Pieces.ts.map diff --git a/ts/fixtures/stock/expected/buf.ts b/ts/fixtures/stock/expected/buf.ts new file mode 100644 index 000000000..522fa55d8 --- /dev/null +++ b/ts/fixtures/stock/expected/buf.ts @@ -0,0 +1,467 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import * as Ops from "./buf.Ops.ts"; +import * as Pieces from "./buf.Pieces.ts"; +import { hasRemaining$Buf_Bytes, hasRemaining$Buf_BytesMut, remaining$Buf_Bytes, remaining$Buf_BytesMut } from "./bytes/buf/buf_impl.ts"; + +/** + * A `BytesMut` split, frozen, grown, and written, ending with every piece's bytes: a + * write to one that reached another would show. + */ +export function bytesMut(data: rt.ByteSlice, out: rt.ByteVec): void { + let _61!: rt.usize; + const ops: Ops.Ops = { _0: data }; + const buf: rt.BytesMut = rt.bytesMutWithCapacity(rt.usizeRem(Ops.byte(ops) as rt.usize, 24)); + const pieces: rt.BytesMut[] = []; + const frozen: rt.ByteSlice[] = []; + while (true) { + const _13: rt.u8 | undefined = Ops.next(ops); + if (_13 !== undefined) { + const op: rt.u8 = _13; + const n: rt.usize = Ops.byte(ops) as rt.usize; + const _20: rt.u8 = rt.u8Rem(op, 18); + if (_20 === 0) { + const _23: rt.ByteSlice = Ops.take(ops, rt.usizeRem(n, 12)); + rt.bytesMutExtend(buf, _23); + } else if (_20 === 1) { + rt.bytesMutPutWord(buf, n & 0xff, 1, false); + } else if (_20 === 2) { + rt.bytesMutPutWord(buf, rt.u16Mul(n & 0xffff, 257), 2, false); + } else if (_20 === 3) { + const _34: rt.BytesMut = rt.bytesMutSplitTo(buf, rt.usizeRem(n, rt.usizeAdd(buf.length, 2))); + pieces.push(_34); + } else if (_20 === 4) { + const _42: rt.BytesMut | undefined = pieces.pop(); + if (_42 !== undefined) { + const _48: rt.ByteSlice = rt.bytesMutFreeze(_42); + frozen.push(_48); + } + } else if (_20 === 5) { + rt.bytesMutTruncate(buf, rt.usizeRem(n, rt.usizeAdd(buf.length, 2))); + } else if (_20 === 6) { + rt.bytesMutResize(buf, rt.usizeRem(n, 40), n & 0xff); + } else if (_20 === 7) { + const _62: rt.usize = rt.usizeRem(n, 4); + if (_62 === 0) { + _61 = rt.usizeSub(4294967295, n); + } else if (_62 === 1) { + _61 = rt.usizeAdd(rt.usizeSub(2147483647, buf.length), 1); + } else { + _61 = n; + } + rt.bytesMutReserve(buf, _61); + } else if (_20 === 8) { + const _71: rt.BytesMut | undefined = pieces.pop(); + if (_71 !== undefined) { + rt.bytesMutUnsplit(buf, _71); + } + } else if (_20 === 9) { + rt.bytesMutAdvance(buf, rt.usizeRem(n, rt.usizeAdd(buf.length, 2))); + } else if (_20 === 10) { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u128ToBeBytes(read$BytesMut(buf, n)))); + } else if (_20 === 11) { + rt.bytesMutTruncate(buf, 0); + } else if (_20 === 12) { + const buf2 = buf; + const _91: rt.BytesMut = rt.bytesMutSplitTo(buf2, buf2.length); + pieces.push(_91); + } else if (_20 === 13) { + const _94: rt.ByteSlice = rt.bytesMutFreeze(rt.bytesMutSplitTo(buf, rt.usizeRem(n, rt.usizeAdd(buf.length, 2)))); + frozen.push(_94); + } else if (_20 === 14) { + rt.bytesMutPutFill(buf, n & 0xff, rt.usizeRem(n, 9)); + } else if (_20 === 15) { + if (!((buf.length === 0))) { + const at: rt.usize = rt.usizeRem(n, buf.length); + const _112: rt.ByteSlice = rt.bytesMutView(buf); + rt.idx(_112, at); + _112.data[_112.start + at] = _112.data[_112.start + at] ^ 255; + } + const _117: rt.BytesMut | undefined = rt.sliceLast(pieces); + if (_117 !== undefined) { + rt.bytesMutExtend(_117, rt.byteSliceFrom(Uint8Array.of(120, 121))); + } + } else if (_20 === 16) { + const _126: rt.ByteSlice = rt.bytesCopyFromSlice(Ops.take(ops, rt.usizeRem(n, 5))); + rt.bytesMutExtend(buf, _126); + } else { + const source: rt.BytesMut = rt.bytesMutFrom(Ops.take(ops, rt.usizeRem(n, 6))); + const first: rt.u8 = getU8Checked$Checked_BytesMut(source); + rt.bytesMutPutWord(buf, first, 1, false); + rt.bytesMutExtend(buf, rt.bytesMutView(source)); + } + } else { + break; + } + } + const tail: rt.BytesMut = rt.bytesMutFrom(rt.byteSliceRange(rt.byteSliceFrom(Uint8Array.of(116, 97, 105, 108)), 0)); + rt.byteVecPush(out, rt.byteSliceEq(rt.bytesMutView(buf), rt.bytesMutView(tail)) ? 1 : 0); + const _155: rt.BytesMut = rt.bytesMutFrom(rt.bytesMutView(buf)); + const _157: rt.ByteSlice = rt.byteSliceRange(rt.bytesMutView(buf), 0); + rt.byteVecPush(out, rt.byteSliceEq(rt.bytesMutView(_155), _157) ? 1 : 0); + const _168: rt.usize = buf.length; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(rt.bytesMutView(buf), f), (f: rt.Formatter) => rt.usizeDisplay(_168, f)]; + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0], " ", args2[1], "\n"]))); + for (const _179 of pieces) { + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(rt.bytesMutView(_179), f)]; + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args4[0], "\n"]))); + } + for (const _198 of frozen) { + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(_198, f)]; + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args6[0], "\n"]))); + } + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rt.bytesMutToByteVec(buf))); +} + +/** The next byte, or 0 if none remains. */ +export function getU8Checked$Checked_BytesMut(self: rt.BytesMut): rt.u8 { + if (!hasRemaining$Buf_BytesMut(self)) { + return 0; + } + return rt.bytesMutReadWord(self, 1, false) as rt.u8; +} + +/** A scalar read off the front of a buffer by `n`'s pick, as a `u128`'s bytes. */ +export function read$Bytes(buf: rt.Place, n: rt.usize): rt.u128 { + const _3: rt.usize = rt.usizeRem(n, 14); + if (_3 === 0) { + return ((rt.bytesReadWord(buf, 1, false) as rt.u8)) as rt.u128; + } + if (_3 === 1) { + return rt.u128Cast((rt.bytesReadWord(buf, 1, false) << 24) >> 24 as rt.i8); + } + if (_3 === 2) { + return ((rt.bytesReadWord(buf, 2, false) as rt.u16)) as rt.u128; + } + if (_3 === 3) { + return rt.u128Cast((rt.bytesReadWord(buf, 2, true) << 16) >> 16 as rt.i16); + } + if (_3 === 4) { + return ((rt.bytesReadWord(buf, 4, true) as rt.u32)) as rt.u128; + } + if (_3 === 5) { + return rt.u128Cast((rt.bytesReadWord(buf, 4, false) | 0) as rt.i32); + } + if (_3 === 6) { + return rt.u128Cast(rt.u64FromBeBytes(rt.bytesRead(buf, 8, false))); + } + if (_3 === 7) { + return rt.u128Cast(rt.i64FromBeBytes(rt.bytesRead(buf, 8, true))); + } + if (_3 === 8) { + return rt.u128FromBeBytes(rt.bytesRead(buf, 16, true)); + } + if (_3 === 9) { + return rt.u128Cast(rt.i128FromBeBytes(rt.bytesRead(buf, 16, false))); + } + if (_3 === 10) { + return rt.u128Cast(rt.u64FromBeBytes(rt.bytesReadInt(buf, 8, rt.usizeRem(n, 10), false, false))); + } + if (_3 === 11) { + return rt.u128Cast(rt.i64FromBeBytes(rt.bytesReadInt(buf, 8, rt.usizeRem(n, 10), true, true))); + } + if (_3 === 12) { + return rt.u128Cast(rt.f64ToBits(rt.f64FromBeBytes(rt.bytesRead(buf, 8, false)))); + } + const dst: Uint8Array = rt.bytes(3); + const part = rt.usizeRem(n, 4); + rt.bytesCopyToSlice(buf, rt.byteSliceRange(rt.byteSliceFrom(dst), 0, part)); + return ((dst[0] << 16) | (dst[1] << 8) | dst[2]) as rt.u128; +} + +/** A scalar read off the front of a buffer by `n`'s pick, as a `u128`'s bytes. */ +export function read$BytesMut(buf: rt.BytesMut, n: rt.usize): rt.u128 { + const _3: rt.usize = rt.usizeRem(n, 14); + if (_3 === 0) { + return ((rt.bytesMutReadWord(buf, 1, false) as rt.u8)) as rt.u128; + } + if (_3 === 1) { + return rt.u128Cast((rt.bytesMutReadWord(buf, 1, false) << 24) >> 24 as rt.i8); + } + if (_3 === 2) { + return ((rt.bytesMutReadWord(buf, 2, false) as rt.u16)) as rt.u128; + } + if (_3 === 3) { + return rt.u128Cast((rt.bytesMutReadWord(buf, 2, true) << 16) >> 16 as rt.i16); + } + if (_3 === 4) { + return ((rt.bytesMutReadWord(buf, 4, true) as rt.u32)) as rt.u128; + } + if (_3 === 5) { + return rt.u128Cast((rt.bytesMutReadWord(buf, 4, false) | 0) as rt.i32); + } + if (_3 === 6) { + return rt.u128Cast(rt.u64FromBeBytes(rt.bytesMutRead(buf, 8, false))); + } + if (_3 === 7) { + return rt.u128Cast(rt.i64FromBeBytes(rt.bytesMutRead(buf, 8, true))); + } + if (_3 === 8) { + return rt.u128FromBeBytes(rt.bytesMutRead(buf, 16, true)); + } + if (_3 === 9) { + return rt.u128Cast(rt.i128FromBeBytes(rt.bytesMutRead(buf, 16, false))); + } + if (_3 === 10) { + return rt.u128Cast(rt.u64FromBeBytes(rt.bytesMutReadInt(buf, 8, rt.usizeRem(n, 10), false, false))); + } + if (_3 === 11) { + return rt.u128Cast(rt.i64FromBeBytes(rt.bytesMutReadInt(buf, 8, rt.usizeRem(n, 10), true, true))); + } + if (_3 === 12) { + return rt.u128Cast(rt.f64ToBits(rt.f64FromBeBytes(rt.bytesMutRead(buf, 8, false)))); + } + const dst: Uint8Array = rt.bytes(3); + const part = rt.usizeRem(n, 4); + rt.bytesMutCopyToSlice(buf, rt.byteSliceRange(rt.byteSliceFrom(dst), 0, part)); + return ((dst[0] << 16) | (dst[1] << 8) | dst[2]) as rt.u128; +} + +/** + * The same reads off a `Bytes`, a `BytesMut`, and a buffer in pieces: each scalar, and + * what remains. + */ +export function reads(data: rt.ByteSlice, out: rt.ByteVec): void { + let rest!: rt.ByteVec; + if (data.length >= 2) { + const mid: number = rt.usizeDiv(data.length - 2, 2); + if (mid > data.length - 2) { + rt.panic("mid > len"); + } + const input: rt.ByteSlice = new rt.ByteSlice(data.data, data.start + 2 + mid, data.length - 2 - mid); + const cut: rt.usize = rt.usizeRem(data.data[data.start + 1] as rt.usize, rt.usizeAdd(input.length, 1)); + const _22: rt.u8 = rt.u8Rem(data.data[data.start], 3); + if (_22 === 0) { + let _24: rt.ByteSlice = rt.bytesCopyFromSlice(input); + rest = readAll$Bytes(rt.place(() => _24, (value) => _24 = value), new rt.ByteSlice(data.data, data.start + 2, mid), read$Bytes, out); + } else if (_22 === 1) { + rest = readAll$BytesMut(rt.bytesMutFrom(input), new rt.ByteSlice(data.data, data.start + 2, mid), read$BytesMut, out); + } else { + rest = readAll$Pieces(Pieces.new(input, cut), new rt.ByteSlice(data.data, data.start + 2, mid), readPieces, out); + } + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rest)); + const put: rt.BytesMut = rt.bytesMutWithCapacity(rt.usizeRem(data.data[data.start] as rt.usize, 2)); + const _42: Pieces.Pieces = Pieces.new(input, cut); + rt.bytesMutPutBuf(put, _42, Pieces.hasRemaining$Buf, Pieces.remaining$Buf, Pieces.chunk$Buf, Pieces.advance$Buf, Pieces.copyToBytes$Buf); + const vec: rt.ByteVec = new rt.ByteVec(); + const _46: Pieces.Pieces = Pieces.new(input, cut); + rt.byteVecPutBuf(vec, _46, Pieces.hasRemaining$Buf, Pieces.remaining$Buf, Pieces.chunk$Buf, Pieces.advance$Buf); + rt.byteVecPush(out, rt.byteSliceEq(rt.bytesMutView(put), rt.byteVecSlice(vec)) ? 1 : 0); + rt.byteVecExtendFromSlice(out, rt.bytesMutView(put)); + const slice: rt.ByteSlice = input; + rt.byteVecPush(out, slice.length === input.length ? 1 : 0); + rt.byteVecPush(out, rt.byteSliceEq(slice, input) ? 1 : 0); + rt.byteVecPush(out, slice.length !== 0 ? 1 : 0); + } +} + +/** + * The reads of `Buf`'s provided methods that translate for a buffer of the crate's own: + * those whose MIR reads no bytes as another type. + */ +export function readPieces(buf: Pieces.Pieces, n: rt.usize): rt.u128 { + if (rt.usizeRem(n, 2) === 0) { + return Pieces.getU8$Buf(buf) as rt.u128; + } + const dst: Uint8Array = rt.bytes(3); + const part = rt.usizeRem(n, 4); + Pieces.copyToSlice$Buf(buf, rt.byteSliceRange(rt.byteSliceFrom(dst), 0, part)); + return ((dst[0] << 16) | (dst[1] << 8) | dst[2]) as rt.u128; +} + +/** `read`s by each of `ops`, then the rest, as `copy_to_bytes` takes it. */ +export function readAll$Bytes(buf: rt.Place, ops: rt.ByteSlice, read: (a0: rt.Place, a1: rt.usize) => rt.u128, out: rt.ByteVec): rt.ByteVec { + for (const op of rt.byteSliceView(ops)) { + if (!(op === 255)) { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u128ToBeBytes(read(buf, op as rt.usize)))); + rt.byteVecPush(out, hasRemaining$Buf_Bytes(buf) ? 1 : 0); + } else { + rt.bytesAdvance(buf, 1); + } + } + const n: rt.usize = remaining$Buf_Bytes(buf); + return rt.byteSliceToByteVec(rt.bytesSplitTo(buf, n)); +} + +/** `read`s by each of `ops`, then the rest, as `copy_to_bytes` takes it. */ +export function readAll$BytesMut(buf: rt.BytesMut, ops: rt.ByteSlice, read: (a0: rt.BytesMut, a1: rt.usize) => rt.u128, out: rt.ByteVec): rt.ByteVec { + for (const op of rt.byteSliceView(ops)) { + if (!(op === 255)) { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u128ToBeBytes(read(buf, op as rt.usize)))); + rt.byteVecPush(out, hasRemaining$Buf_BytesMut(buf) ? 1 : 0); + } else { + rt.bytesMutAdvance(buf, 1); + } + } + const n: rt.usize = remaining$Buf_BytesMut(buf); + return rt.byteSliceToByteVec(rt.bytesMutFreeze(rt.bytesMutSplitTo(buf, n))); +} + +/** `read`s by each of `ops`, then the rest, as `copy_to_bytes` takes it. */ +export function readAll$Pieces(buf: Pieces.Pieces, ops: rt.ByteSlice, read: (a0: Pieces.Pieces, a1: rt.usize) => rt.u128, out: rt.ByteVec): rt.ByteVec { + for (const op of rt.byteSliceView(ops)) { + if (!(op === 255)) { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u128ToBeBytes(read(buf, op as rt.usize)))); + rt.byteVecPush(out, Pieces.hasRemaining$Buf$2(buf) ? 1 : 0); + } else { + Pieces.advance$Buf(buf, 1); + } + } + const n: rt.usize = Pieces.remaining$Buf$2(buf); + return rt.byteSliceToByteVec(Pieces.copyToBytes$Buf(buf, n)); +} + +/** The same writes into a `Vec` and a `BytesMut`, which must match. */ +export function writes(data: rt.ByteSlice, out: rt.ByteVec): void { + const vec: rt.ByteVec = new rt.ByteVec(); + const buf: rt.BytesMut = rt.bytesMutWithCapacity(0); + writeAll$Vec_u8(vec, data); + writeAll$BytesMut(buf, data); + rt.byteVecPush(out, rt.byteSliceEq(rt.byteVecSlice(vec), rt.bytesMutView(buf)) ? 1 : 0); + rt.byteVecPush(out, ((0x7fffffff - vec.length as rt.usize)) === 0x7fffffff - buf.length as rt.usize ? 1 : 0); + rt.byteVecPush(out, buf.length < 0x7fffffff ? 1 : 0); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(vec)); +} + +/** A write by each pair of `data`'s bytes. */ +export function writeAll$BytesMut(buf: rt.BytesMut, data: rt.ByteSlice): void { + let dataData: Uint8Array = data.data; + let dataStart: number = data.start; + let dataLen: number = data.length; + while (dataLen >= 2) { + const op: rt.u8 = dataData[dataStart]; + const n: rt.u8 = dataData[dataStart + 1]; + const restData: Uint8Array = dataData; + const restStart: number = dataStart + 2; + const restLen: number = dataLen - 2; + dataData = restData; + dataStart = restStart; + dataLen = restLen; + const op2: rt.u8 = op; + const n2: rt.u8 = n; + const v: rt.u64 = rt.u64Mul(n2 as rt.u64, { hi: 0x1010101, lo: 0x1010101 } as rt.u64); + const _18: rt.u8 = rt.u8Rem(op2, 15); + if (_18 === 0) { + rt.bytesMutPutWord(buf, n2, 1, false); + } else if (_18 === 1) { + rt.bytesMutPutWord(buf, (n2 << 24) >> 24, 1, false); + } else if (_18 === 2) { + rt.bytesMutPutWord(buf, rt.u64Low(v) & 0xffff, 2, false); + } else if (_18 === 3) { + rt.bytesMutPutWord(buf, (rt.u64Low(v) << 16) >> 16, 2, true); + } else if (_18 === 4) { + rt.bytesMutPutWord(buf, rt.u64Low(v), 4, false); + } else if (_18 === 5) { + rt.bytesMutPutWord(buf, rt.u64Low(v) | 0, 4, true); + } else if (_18 === 6) { + rt.bytesMutPutBytes(buf, rt.u64ToBeBytes(v), true); + } else if (_18 === 7) { + rt.bytesMutPutBytes(buf, rt.i64ToBeBytes(rt.i64Cast(v)), false); + } else if (_18 === 8) { + rt.bytesMutPutBytes(buf, rt.u128ToBeBytes(rt.u128Shl(rt.u128Cast(v), 40)), true); + } else if (_18 === 9) { + const _30: rt.usize = rt.usizeRem(n2 as rt.usize, 10); + rt.bytesMutPutInt(buf, rt.u64ToBeBytes(v), _30, false); + } else if (_18 === 10) { + const _33: rt.i64 = rt.i64Cast(v); + const _34: rt.usize = rt.usizeRem(n2 as rt.usize, 10); + rt.bytesMutPutInt(buf, rt.i64ToBeBytes(_33), _34, true); + } else if (_18 === 11) { + rt.bytesMutExtend(buf, rt.byteSliceFrom(Uint8Array.of(op2, n2))); + } else if (_18 === 12) { + rt.bytesMutPutFill(buf, n2, rt.usizeRem(n2 as rt.usize, 7)); + } else if (_18 === 13) { + rt.bytesMutExtend(buf, rt.byteSliceFrom(Uint8Array.of(112, 117, 116))); + } else { + rt.bytesMutPutBytes(buf, rt.f64ToBeBytes(((n2 as rt.f64)) / 3.0), false); + } + } +} + +/** A write by each pair of `data`'s bytes. */ +export function writeAll$Vec_u8(buf: rt.ByteVec, data: rt.ByteSlice): void { + let dataData: Uint8Array = data.data; + let dataStart: number = data.start; + let dataLen: number = data.length; + while (dataLen >= 2) { + const op: rt.u8 = dataData[dataStart]; + const n: rt.u8 = dataData[dataStart + 1]; + const restData: Uint8Array = dataData; + const restStart: number = dataStart + 2; + const restLen: number = dataLen - 2; + dataData = restData; + dataStart = restStart; + dataLen = restLen; + const op2: rt.u8 = op; + const n2: rt.u8 = n; + const v: rt.u64 = rt.u64Mul(n2 as rt.u64, { hi: 0x1010101, lo: 0x1010101 } as rt.u64); + const _18: rt.u8 = rt.u8Rem(op2, 15); + if (_18 === 0) { + rt.byteVecPutWord(buf, n2, 1, false); + } else if (_18 === 1) { + rt.byteVecPutWord(buf, (n2 << 24) >> 24, 1, false); + } else if (_18 === 2) { + rt.byteVecPutWord(buf, rt.u64Low(v) & 0xffff, 2, false); + } else if (_18 === 3) { + rt.byteVecPutWord(buf, (rt.u64Low(v) << 16) >> 16, 2, true); + } else if (_18 === 4) { + rt.byteVecPutWord(buf, rt.u64Low(v), 4, false); + } else if (_18 === 5) { + rt.byteVecPutWord(buf, rt.u64Low(v) | 0, 4, true); + } else if (_18 === 6) { + rt.byteVecPutBytes(buf, rt.u64ToBeBytes(v), true); + } else if (_18 === 7) { + rt.byteVecPutBytes(buf, rt.i64ToBeBytes(rt.i64Cast(v)), false); + } else if (_18 === 8) { + rt.byteVecPutBytes(buf, rt.u128ToBeBytes(rt.u128Shl(rt.u128Cast(v), 40)), true); + } else if (_18 === 9) { + const _30: rt.usize = rt.usizeRem(n2 as rt.usize, 10); + rt.byteVecPutInt(buf, rt.u64ToBeBytes(v), _30, false); + } else if (_18 === 10) { + const _33: rt.i64 = rt.i64Cast(v); + const _34: rt.usize = rt.usizeRem(n2 as rt.usize, 10); + rt.byteVecPutInt(buf, rt.i64ToBeBytes(_33), _34, true); + } else if (_18 === 11) { + rt.byteVecExtendFromSlice(buf, rt.byteSliceFrom(Uint8Array.of(op2, n2))); + } else if (_18 === 12) { + rt.byteVecPutFill(buf, n2, rt.usizeRem(n2 as rt.usize, 7)); + } else if (_18 === 13) { + rt.byteVecExtendFromSlice(buf, rt.byteSliceFrom(Uint8Array.of(112, 117, 116))); + } else { + rt.byteVecPutBytes(buf, rt.f64ToBeBytes(((n2 as rt.f64)) / 3.0), false); + } + } +} + +/** `Bytes`' own edits, through a `&mut`, and `slice_ref` of a part of it. */ +export function edits(data: rt.ByteSlice, out: rt.ByteVec): void { + let part!: rt.ByteSlice; + if (data.length >= 2) { + let bytes: rt.ByteSlice = rt.bytesCopyFromSlice(new rt.ByteSlice(data.data, data.start + 2, data.length - 2)); + const a: rt.usize = rt.usizeRem(data.data[data.start + 1] as rt.usize, rt.usizeAdd(data.length - 2, 2)); + const _17: rt.u8 = rt.u8Rem(data.data[data.start], 6); + if (_17 === 0) { + part = rt.bytesSplitTo(rt.place(() => bytes, (value6) => bytes = value6), a); + } else if (_17 === 1) { + part = rt.bytesSplitOff(rt.place(() => bytes, (value5) => bytes = value5), a); + } else if (_17 === 2) { + rt.bytesTruncate(rt.place(() => bytes, (value4) => bytes = value4), a); + part = bytes; + } else if (_17 === 3) { + rt.bytesTruncate(rt.place(() => bytes, (value3) => bytes = value3), 0); + part = rt.bytesNew(); + } else if (_17 === 4) { + const sub: rt.ByteSlice = rt.byteSliceRange(bytes, rt.min(a, data.length - 2)); + part = rt.bytesSliceRef(bytes, sub); + } else { + rt.bytesAdvance(rt.place(() => bytes, (value) => bytes = value), a); + const _35: rt.usize = rt.usizeDiv(a, 2); + part = rt.bytesSplitTo(rt.place(() => bytes, (value2) => bytes = value2), _35); + } + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(part, f), (f: rt.Formatter) => rt.bytesDebug(bytes, f)]; + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0], " ", args2[1]]))); + } +} + +//# sourceMappingURL=buf.ts.map diff --git a/ts/fixtures/stock/expected/bytes.TryGetError.ts b/ts/fixtures/stock/expected/bytes.TryGetError.ts new file mode 100644 index 000000000..4b6b5f3b8 --- /dev/null +++ b/ts/fixtures/stock/expected/bytes.TryGetError.ts @@ -0,0 +1,19 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** + * Error type for the `try_get_` methods of [`Buf`]. + * Indicates that there were not enough remaining + * bytes in the buffer while attempting + * to get a value from a [`Buf`] with one + * of the `try_get_` methods. + */ +export interface TryGetError { + /** The number of bytes necessary to get the value */ + requested: rt.usize; + /** The number of bytes available in the buffer */ + available: rt.usize; +} + +//# sourceMappingURL=bytes.TryGetError.ts.map diff --git a/ts/fixtures/stock/expected/bytes.ts b/ts/fixtures/stock/expected/bytes.ts new file mode 100644 index 000000000..c3d0f172b --- /dev/null +++ b/ts/fixtures/stock/expected/bytes.ts @@ -0,0 +1,14 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import type * as TryGetError from "./bytes.TryGetError.ts"; + +export function panicAdvance(errorInfo: TryGetError.TryGetError): never { + const arg = errorInfo.available; + const _8: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(arg, f); + const arg2 = errorInfo.requested; + const args2: rt.Fmt[] = [_8, (f: rt.Formatter) => rt.usizeDisplay(arg2, f)]; + rt.panicFmt(["advance out of bounds: the len is ", args2[0], " but advancing by ", args2[1]]); +} + +//# sourceMappingURL=bytes.ts.map diff --git a/ts/fixtures/stock/expected/bytes/buf/buf_impl.ts b/ts/fixtures/stock/expected/bytes/buf/buf_impl.ts new file mode 100644 index 000000000..89d7c1c69 --- /dev/null +++ b/ts/fixtures/stock/expected/bytes/buf/buf_impl.ts @@ -0,0 +1,113 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../../rt.ts"; + +/** + * Returns true if there are any more bytes to consume + * + * This is equivalent to `self.remaining() != 0`. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"a"[..]; + * + * assert!(buf.has_remaining()); + * + * buf.get_u8(); + * + * assert!(!buf.has_remaining()); + * ``` + */ +export function hasRemaining$Buf_Bytes(self: rt.Place): boolean { + return self.v.length !== 0; +} + +/** + * Returns true if there are any more bytes to consume + * + * This is equivalent to `self.remaining() != 0`. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"a"[..]; + * + * assert!(buf.has_remaining()); + * + * buf.get_u8(); + * + * assert!(!buf.has_remaining()); + * ``` + */ +export function hasRemaining$Buf_BytesMut(self: rt.BytesMut): boolean { + return self.length !== 0; +} + +/** + * Returns the number of bytes between the current position and the end of + * the buffer. + * + * This value is greater than or equal to the length of the slice returned + * by `chunk()`. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"hello world"[..]; + * + * assert_eq!(buf.remaining(), 11); + * + * buf.get_u8(); + * + * assert_eq!(buf.remaining(), 10); + * ``` + * + * # Implementer notes + * + * Implementations of `remaining` should ensure that the return value does + * not change unless a call is made to `advance` or any other function that + * is documented to change the `Buf`'s current position. + */ +export function remaining$Buf_Bytes(self: rt.Place): rt.usize { + return self.v.length; +} + +/** + * Returns the number of bytes between the current position and the end of + * the buffer. + * + * This value is greater than or equal to the length of the slice returned + * by `chunk()`. + * + * # Examples + * + * ``` + * use bytes::Buf; + * + * let mut buf = &b"hello world"[..]; + * + * assert_eq!(buf.remaining(), 11); + * + * buf.get_u8(); + * + * assert_eq!(buf.remaining(), 10); + * ``` + * + * # Implementer notes + * + * Implementations of `remaining` should ensure that the return value does + * not change unless a call is made to `advance` or any other function that + * is documented to change the `Buf`'s current position. + */ +export function remaining$Buf_BytesMut(self: rt.BytesMut): rt.usize { + return self.length; +} + +//# sourceMappingURL=buf_impl.ts.map diff --git a/ts/fixtures/stock/expected/core/option.ts b/ts/fixtures/stock/expected/core/option.ts new file mode 100644 index 000000000..a6049d9a1 --- /dev/null +++ b/ts/fixtures/stock/expected/core/option.ts @@ -0,0 +1,12 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; + +export function unwrapOr$Option_u8(self: rt.u8 | undefined, default_: rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return self; +} + +//# sourceMappingURL=option.ts.map diff --git a/ts/fixtures/stock/expected/core/result.ts b/ts/fixtures/stock/expected/core/result.ts new file mode 100644 index 000000000..eb4785d8b --- /dev/null +++ b/ts/fixtures/stock/expected/core/result.ts @@ -0,0 +1,12 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import type * as TryGetError from "../bytes.TryGetError.ts"; + +export function unwrapOrElse$Result_unit_TryGetError_copy_to_slice_closure0(self: rt.Result, op: (a0: TryGetError.TryGetError) => void): void { + if (!self.ok) { + op(self.error); + } +} + +//# sourceMappingURL=result.ts.map diff --git a/ts/fixtures/stock/expected/harness.ts b/ts/fixtures/stock/expected/harness.ts index d9741717a..2455a9e88 100644 --- a/ts/fixtures/stock/expected/harness.ts +++ b/ts/fixtures/stock/expected/harness.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { bytesMut, reads, writes, edits } from "./buf.ts"; import * as Owner from "./harness.Owner.ts"; /** @@ -8,7 +9,7 @@ import * as Owner from "./harness.Owner.ts"; * moves no other. */ export function cases(): Array<(a0: rt.ByteSlice, a1: rt.ByteVec) => void> { - return [slices, made, events, random]; + return [slices, made, events, random, bytesMut, reads, writes, edits]; } /** Run one case. */ diff --git a/ts/fixtures/stock/src/buf.rs b/ts/fixtures/stock/src/buf.rs new file mode 100644 index 000000000..e1ca4a0f7 --- /dev/null +++ b/ts/fixtures/stock/src/buf.rs @@ -0,0 +1,313 @@ +//! `bytes`' `BytesMut`, `Buf`, and `BufMut`: each case runs ops its input picks, so the +//! differential test reaches their panics and what `split_to` and `freeze` share. + +use bytes::{Buf, BufMut, Bytes, BytesMut}; + +/// A `BytesMut` split, frozen, grown, and written, ending with every piece's bytes: a +/// write to one that reached another would show. +pub fn bytes_mut(data: &[u8], out: &mut Vec) { + let mut ops = Ops(data); + let mut buf = BytesMut::with_capacity(ops.byte() as usize % 24); + let mut pieces: Vec = Vec::new(); + let mut frozen: Vec = Vec::new(); + while let Some(op) = ops.next() { + let n = ops.byte() as usize; + match op % 18 { + 0 => buf.extend_from_slice(ops.take(n % 12)), + 1 => buf.put_u8(n as u8), + 2 => buf.put_u16(n as u16 * 257), + 3 => pieces.push(buf.split_to(n % (buf.len() + 2))), + 4 => { + if let Some(piece) = pieces.pop() { + frozen.push(piece.freeze()); + } + } + 5 => buf.truncate(n % (buf.len() + 2)), + 6 => buf.resize(n % 40, n as u8), + // Past what a buffer holds, by overflowing `usize` or not: each panics. + 7 => buf.reserve(match n % 4 { + 0 => usize::MAX - n, + 1 => isize::MAX as usize - buf.len() + 1, + _ => n, + }), + 8 => { + if let Some(piece) = pieces.pop() { + buf.unsplit(piece); + } + } + 9 => buf.advance(n % (buf.len() + 2)), + 10 => out.extend_from_slice(&read(&mut buf, n).to_be_bytes()), + 11 => buf.clear(), + 12 => pieces.push(buf.split()), + 13 => frozen.push(buf.copy_to_bytes(n % (buf.len() + 2))), + 14 => buf.put_bytes(n as u8, n % 9), + 15 => { + // Through `DerefMut`, into what this handle alone holds. + if !buf.is_empty() { + let at = n % buf.len(); + buf[at] ^= 0xff; + } + if let Some(piece) = pieces.last_mut() { + piece.put_slice(b"xy"); + } + } + 16 => buf.put(Bytes::copy_from_slice(ops.take(n % 5))), + _ => { + let mut source = BytesMut::from(ops.take(n % 6)); + // Its own `Buf`, read into a `BufMut`, then the rest whole. + let first = source.get_u8_checked(); + buf.put_u8(first); + buf.put(source); + } + } + } + let tail = BytesMut::from(&b"tail"[..]); + out.push((buf == tail) as u8); + out.push((buf.clone() == buf[..]) as u8); + out.extend_from_slice(format!("{buf:?} {}\n", buf.len()).as_bytes()); + for piece in &pieces { + out.extend_from_slice(format!("{piece:?}\n").as_bytes()); + } + for bytes in &frozen { + out.extend_from_slice(format!("{bytes:?}\n").as_bytes()); + } + let vec: Vec = buf.into(); + out.extend_from_slice(&vec); +} + +trait Checked { + /// The next byte, or 0 if none remains. + fn get_u8_checked(&mut self) -> u8; +} + +impl Checked for B { + fn get_u8_checked(&mut self) -> u8 { + match self.has_remaining() { + true => self.get_u8(), + false => 0, + } + } +} + +/// A scalar read off the front of a buffer by `n`'s pick, as a `u128`'s bytes. +fn read(buf: &mut B, n: usize) -> u128 { + match n % 14 { + 0 => buf.get_u8().into(), + 1 => buf.get_i8() as u128, + 2 => buf.get_u16().into(), + 3 => buf.get_i16_le() as u128, + 4 => buf.get_u32_le().into(), + 5 => buf.get_i32() as u128, + 6 => buf.get_u64().into(), + 7 => buf.get_i64_le() as u128, + 8 => buf.get_u128_le(), + 9 => buf.get_i128() as u128, + 10 => buf.get_uint(n % 10).into(), + 11 => buf.get_int_le(n % 10) as u128, + 12 => buf.get_f64().to_bits().into(), + _ => { + let mut dst = [0; 3]; + buf.copy_to_slice(&mut dst[..n % 4]); + u32::from_be_bytes([0, dst[0], dst[1], dst[2]]).into() + } + } +} + +/// A buffer of the crate's own, in pieces: `Buf`'s provided methods read across them. +struct Pieces { + /// None empty, so `chunk` is empty only once nothing remains, as `Buf` requires. + parts: Vec>, + /// How far into the first part reads are. + at: usize, +} + +impl Pieces { + /// `input` in two parts, cut at `cut`. + fn new(input: &[u8], cut: usize) -> Self { + let (a, b) = input.split_at(cut); + let mut parts = vec![a.to_vec(), b.to_vec()]; + parts.retain(|part| !part.is_empty()); + Self { parts, at: 0 } + } +} + +impl Buf for Pieces { + fn remaining(&self) -> usize { + self.parts.iter().map(Vec::len).sum::() - self.at + } + + fn chunk(&self) -> &[u8] { + match self.parts.first() { + Some(part) => &part[self.at..], + None => &[], + } + } + + fn advance(&mut self, mut cnt: usize) { + while cnt > 0 { + let left = self.parts[0].len() - self.at; + if cnt < left { + self.at += cnt; + return; + } + cnt -= left; + self.parts.remove(0); + self.at = 0; + } + } + + // Its own, as moq's buffers have: the provided one reads through a `Take<&mut Self>`. + fn copy_to_bytes(&mut self, len: usize) -> Bytes { + let mut out = BytesMut::with_capacity(len); + while out.len() < len { + let take = self.chunk().len().min(len - out.len()); + out.extend_from_slice(&self.chunk()[..take]); + self.advance(take); + } + out.freeze() + } +} + +/// The same reads off a `Bytes`, a `BytesMut`, and a buffer in pieces: each scalar, and +/// what remains. +pub fn reads(data: &[u8], out: &mut Vec) { + let [kind, cut, ops @ ..] = data else { + return; + }; + let (ops, input) = ops.split_at(ops.len() / 2); + let cut = *cut as usize % (input.len() + 1); + let rest = match kind % 3 { + 0 => read_all(&mut Bytes::copy_from_slice(input), ops, read, out), + 1 => read_all(&mut BytesMut::from(input), ops, read, out), + _ => read_all(&mut Pieces::new(input, cut), ops, read_pieces, out), + }; + out.extend_from_slice(&rest); + // Put whole, into a buffer with room and one without, which `bytes` reads differently. + let mut put = BytesMut::with_capacity(*kind as usize % 2); + put.put(Pieces::new(input, cut)); + let mut vec = Vec::new(); + vec.put(Pieces::new(input, cut)); + out.push((put == vec) as u8); + out.extend_from_slice(&put); + let slice: &[u8] = input; + out.push((slice.remaining() == input.len()) as u8); + out.push((slice.chunk() == input) as u8); + out.push(slice.has_remaining() as u8); +} + +/// The reads of `Buf`'s provided methods that translate for a buffer of the crate's own: +/// those whose MIR reads no bytes as another type. +fn read_pieces(buf: &mut Pieces, n: usize) -> u128 { + match n % 2 { + 0 => buf.get_u8().into(), + _ => { + let mut dst = [0; 3]; + buf.copy_to_slice(&mut dst[..n % 4]); + u32::from_be_bytes([0, dst[0], dst[1], dst[2]]).into() + } + } +} + +/// `read`s by each of `ops`, then the rest, as `copy_to_bytes` takes it. +fn read_all(buf: &mut B, ops: &[u8], read: fn(&mut B, usize) -> u128, out: &mut Vec) -> Vec { + for &op in ops { + if op == 0xff { + buf.advance(1); + continue; + } + out.extend_from_slice(&read(buf, op as usize).to_be_bytes()); + out.push(buf.has_remaining() as u8); + } + let n = buf.remaining(); + buf.copy_to_bytes(n).to_vec() +} + +/// The same writes into a `Vec` and a `BytesMut`, which must match. +pub fn writes(data: &[u8], out: &mut Vec) { + let mut vec = Vec::new(); + let mut buf = BytesMut::new(); + write_all(&mut vec, data); + write_all(&mut buf, data); + out.push((vec == buf) as u8); + out.push((vec.remaining_mut() == buf.remaining_mut()) as u8); + out.push(buf.has_remaining_mut() as u8); + out.extend_from_slice(&vec); +} + +/// A write by each pair of `data`'s bytes. +fn write_all(buf: &mut B, data: &[u8]) { + let mut data = data; + while let [op, n, rest @ ..] = data { + data = rest; + let (op, n) = (*op, *n); + let v = u64::from(n) * 0x0101_0101_0101_0101; + match op % 15 { + 0 => buf.put_u8(n), + 1 => buf.put_i8(n as i8), + 2 => buf.put_u16(v as u16), + 3 => buf.put_i16_le(v as i16), + 4 => buf.put_u32(v as u32), + 5 => buf.put_i32_le(v as i32), + 6 => buf.put_u64_le(v), + 7 => buf.put_i64(v as i64), + 8 => buf.put_u128_le(u128::from(v) << 40), + 9 => buf.put_uint(v, n as usize % 10), + 10 => buf.put_int_le(v as i64, n as usize % 10), + 11 => buf.put_slice(&[op, n]), + 12 => buf.put_bytes(n, n as usize % 7), + 13 => buf.put(Bytes::from_static(b"put")), + _ => buf.put_f64(f64::from(n) / 3.0), + } + } +} + +/// `Bytes`' own edits, through a `&mut`, and `slice_ref` of a part of it. +pub fn edits(data: &[u8], out: &mut Vec) { + let [kind, a, rest @ ..] = data else { + return; + }; + let mut bytes = Bytes::copy_from_slice(rest); + let a = *a as usize % (rest.len() + 2); + let part = match kind % 6 { + 0 => bytes.split_to(a), + 1 => bytes.split_off(a), + 2 => { + bytes.truncate(a); + bytes.clone() + } + 3 => { + bytes.clear(); + Bytes::new() + } + 4 => { + let sub = &bytes[a.min(rest.len())..]; + bytes.slice_ref(sub) + } + _ => { + bytes.advance(a); + bytes.copy_to_bytes(a / 2) + } + }; + out.extend_from_slice(format!("{part:?} {bytes:?}").as_bytes()); +} + +/// The bytes of a case's input, taken from the front. +struct Ops<'a>(&'a [u8]); + +impl<'a> Ops<'a> { + fn next(&mut self) -> Option { + let (&first, rest) = self.0.split_first()?; + self.0 = rest; + Some(first) + } + + fn byte(&mut self) -> u8 { + self.next().unwrap_or(0) + } + + fn take(&mut self, n: usize) -> &'a [u8] { + let (taken, rest) = self.0.split_at(n.min(self.0.len())); + self.0 = rest; + taken + } +} diff --git a/ts/fixtures/stock/src/harness.rs b/ts/fixtures/stock/src/harness.rs index 9f5957914..3be072f00 100644 --- a/ts/fixtures/stock/src/harness.rs +++ b/ts/fixtures/stock/src/harness.rs @@ -10,7 +10,16 @@ type Case = fn(&[u8], &mut Vec); /// Each case, which the first byte picks modulo their count, so a case added at the end /// moves no other. fn cases() -> Vec { - vec![slices, made, events, random] + vec![ + slices, + made, + events, + random, + crate::buf::bytes_mut, + crate::buf::reads, + crate::buf::writes, + crate::buf::edits, + ] } /// Run one case. diff --git a/ts/fixtures/stock/src/lib.rs b/ts/fixtures/stock/src/lib.rs index 906dd577c..d06747c6d 100644 --- a/ts/fixtures/stock/src/lib.rs +++ b/ts/fixtures/stock/src/lib.rs @@ -3,6 +3,7 @@ //! //! `harness::run` is the entry point both sides of the differential test run. +mod buf; pub mod harness; #[cfg(target_arch = "wasm32")] #[path = "../../wasm.rs"] diff --git a/ts/moq/model.toml b/ts/moq/model.toml index 88d1e7631..651b041aa 100644 --- a/ts/moq/model.toml +++ b/ts/moq/model.toml @@ -20,8 +20,6 @@ roots = [ ] [bind] -# `unsafe` inside, which translation doesn't map yet. -"bytes::BytesMut" = "bind/bytes-mut.ts" # DEFLATE and the clock, which JS has its own of. "model::flate::Encoder" = "bind/encoder.ts" "model::flate::Decoder" = "bind/decoder.ts" diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index 20d71d1fc..40f7bc919 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -565,7 +565,7 @@ export function byteSliceEq(a: ByteSlice, b: ByteSlice): boolean { } /** Copy `src` into `dst` at `at`; a few bytes copy faster than a view of them is made. */ -function copyBytes(dst: Uint8Array, at: number, src: Uint8Array, start: number, length: number): void { +export function copyBytes(dst: Uint8Array, at: number, src: Uint8Array, start: number, length: number): void { if (length <= 16) { for (let i = 0; i < length; i++) dst[at + i] = src[start + i]; } else { diff --git a/ts/runtime/rt/bytes.ts b/ts/runtime/rt/bytes.ts index b95b7e8a1..1f521eeb0 100644 --- a/ts/runtime/rt/bytes.ts +++ b/ts/runtime/rt/bytes.ts @@ -1,9 +1,28 @@ -// `bytes::Bytes`, for rust2-ts output: immutable bytes that its clones and slices share, -// as a `&[u8]` shares them, so a `Bytes` is an `rt.ByteSlice`. `rt.ts` re-exports all of it. +// `bytes`, for rust2-ts output. A `Bytes` is immutable bytes that its clones and slices +// share, as a `&[u8]` shares them, so it is an `rt.ByteSlice`. A `BytesMut` is a window of +// storage that the handles `split_to` makes and the `Bytes` that `freeze` makes share +// without overlapping. `rt.ts` re-exports all of it. -import { ByteSlice, type FmtResult, type Formatter, fmtWriteStr, panic, type RangeInclusive } from "../rt.ts"; +import { + ByteSlice, + type ByteVec, + byteSliceToByteVec, + bytes, + byteVecExtendFromSlice, + byteVecPush, + copyBytes, + type FmtResult, + type Formatter, + fmtWriteStr, + type Place, + panic, + type RangeInclusive, +} from "../rt.ts"; import type { usize } from "./int.ts"; +/** `isize::MAX` on wasm32, the most bytes an allocation holds. */ +const ISIZE_MAX = 0x7fffffff; + /** `bytes::Bytes`. */ export type Bytes = ByteSlice; @@ -61,3 +80,384 @@ function escape(byte: number): string { if (byte >= 0x20 && byte < 0x7f) return String.fromCharCode(byte); return `\\x${byte.toString(16).padStart(2, "0")}`; } + +/** `Bytes::split_to`: the first `at` bytes, leaving the rest. */ +export function bytesSplitTo(p: Place, at: usize): Bytes { + const b = p.v; + if (at > b.length) panic(`split_to out of bounds: ${at} <= ${b.length}`); + p.v = new ByteSlice(b.data, b.start + at, b.length - at); + return new ByteSlice(b.data, b.start, at); +} + +/** `Bytes::split_off`: the bytes from `at` on, leaving the first `at`. */ +export function bytesSplitOff(p: Place, at: usize): Bytes { + const b = p.v; + if (at > b.length) panic(`split_off out of bounds: ${at} <= ${b.length}`); + p.v = new ByteSlice(b.data, b.start, at); + return new ByteSlice(b.data, b.start + at, b.length - at); +} + +/** `Bytes::truncate`, and `clear` of 0. */ +export function bytesTruncate(p: Place, len: usize): void { + if (len < p.v.length) p.v = new ByteSlice(p.v.data, p.v.start, len); +} + +/** + * `Bytes::slice_ref`: the bytes of `b` that `subset` is, by where they are in memory. Its + * panic names no addresses, which JS has none of. + */ +export function bytesSliceRef(b: Bytes, subset: ByteSlice): Bytes { + if (subset.length === 0) return bytesNew(); + if (subset.data.buffer !== b.data.buffer) panic("subset is out of bounds"); + const at = subset.data.byteOffset + subset.start; + const from = b.data.byteOffset + b.start; + if (at < from) panic("subset pointer is smaller than self pointer"); + if (at + subset.length > from + b.length) panic("subset is out of bounds"); + return new ByteSlice(b.data, b.start + (at - from), subset.length); +} + +// Buf + +/** `bytes`' panic for reading or advancing past what remains. */ +function panicAdvance(requested: number, available: number): never { + panic(`advance out of bounds: the len is ${available} but advancing by ${requested}`); +} + +/** The `Buf` of `Bytes` or `BytesMut` advancing past what remains, which asserts. */ +function panicRemaining(cnt: number, remaining: number): never { + panic(`cannot advance past \`remaining\`: ${cnt} <= ${remaining}`); +} + +/** `nbytes` read into an integer of `size` bytes, which holds at most that many. */ +function checkFits(size: number, nbytes: number): void { + if (nbytes > size) panic(`size too large: the integer type can fit ${size} bytes, but nbytes is ${nbytes}`); +} + +/** `n` bytes from the front of `s`, the other way around if `le`. */ +function readOf(s: ByteSlice, n: number, le: boolean): Uint8Array { + const view = s.data.subarray(s.start, s.start + n); + return le ? view.slice().reverse() : view; +} + +/** The unsigned number of the `n` big-endian bytes of `s` from `i`, `n` at most 4. */ +function wordOf(s: ByteSlice, n: number, le: boolean): number { + let v = 0; + for (let i = 0; i < n; i++) v = (v << 8) | s.data[s.start + (le ? n - 1 - i : i)]; + return n === 4 ? v >>> 0 : v; +} + +/** `::advance`. */ +export function bytesAdvance(p: Place, cnt: usize): void { + const b = p.v; + if (cnt > b.length) panicRemaining(cnt, b.length); + p.v = new ByteSlice(b.data, b.start + cnt, b.length - cnt); +} + +/** `Buf::get_*` of `Bytes`: its first `n` bytes, the other way around if `le`, read past. */ +export function bytesRead(p: Place, n: usize, le: boolean): Uint8Array { + const b = p.v; + if (b.length < n) panicAdvance(n, b.length); + p.v = new ByteSlice(b.data, b.start + n, b.length - n); + return readOf(b, n, le); +} + +/** `Buf::get_*` of `Bytes` of at most 4 bytes, as an unsigned number. */ +export function bytesReadWord(p: Place, n: usize, le: boolean): number { + const b = p.v; + if (b.length < n) panicAdvance(n, b.length); + p.v = new ByteSlice(b.data, b.start + n, b.length - n); + return wordOf(b, n, le); +} + +/** + * `Buf::get_uint` or `get_int` of `Bytes`: `nbytes` as the big-endian bytes of an integer of + * `size` bytes, sign-extended if `signed`. + */ +export function bytesReadInt(p: Place, size: usize, nbytes: usize, signed: boolean, le: boolean): Uint8Array { + checkFits(size, nbytes); + return widen(bytesRead(p, nbytes, le), size, signed); +} + +/** `Buf::copy_to_slice` of `Bytes`. */ +export function bytesCopyToSlice(p: Place, dst: ByteSlice): void { + const b = p.v; + if (b.length < dst.length) panicAdvance(dst.length, b.length); + copyBytes(dst.data, dst.start, b.data, b.start, dst.length); + p.v = new ByteSlice(b.data, b.start + dst.length, b.length - dst.length); +} + +/** Big-endian bytes as the low bytes of `size`, the rest zero, or copies of the sign if `signed`. */ +function widen(read: Uint8Array, size: number, signed: boolean): Uint8Array { + const out = new Uint8Array(size); + if (signed && read.length > 0 && read[0] >= 0x80) out.fill(0xff); + out.set(read, size - read.length); + return out; +} + +// BytesMut + +/** + * `bytes::BytesMut`: `length` bytes of `data` from `start`, with room up to `cap` before + * the bytes another handle or a frozen `Bytes` holds. Its capacity isn't `bytes`', which + * depends on whether the other handles of its storage dropped, so translation refuses + * what reads it. + */ +export class BytesMut { + data: Uint8Array; + start: number; + length: number; + cap: number; + /** Whether `split_to` shared its storage, whose growth panics as `bytes`' shared kind does. */ + shared: boolean; + + constructor(data: Uint8Array, start: number, length: number, cap: number, shared: boolean) { + this.data = data; + this.start = start; + this.length = length; + this.cap = cap; + this.shared = shared; + } +} + +/** `BytesMut::with_capacity`, `new` of 0. */ +export function bytesMutWithCapacity(capacity: usize): BytesMut { + if (capacity > ISIZE_MAX) panic("capacity overflow"); + return new BytesMut(bytes(capacity), 0, 0, capacity, false); +} + +/** `BytesMut::zeroed`. */ +export function bytesMutZeroed(len: usize): BytesMut { + const b = bytesMutWithCapacity(len); + b.length = len; + return b; +} + +/** A `BytesMut` of a copy of `s`: `From<&[u8]>`, `From<&str>`, `From`, and `Clone`. */ +export function bytesMutFrom(s: ByteSlice): BytesMut { + const b = bytesMutWithCapacity(s.length); + copyBytes(b.data, 0, s.data, s.start, s.length); + b.length = s.length; + return b; +} + +/** Its bytes, as `Deref`, `DerefMut`, `AsRef`, `AsMut`, and `Buf::chunk` lend them. */ +export function bytesMutView(b: BytesMut): ByteSlice { + return new ByteSlice(b.data, b.start, b.length); +} + +/** `BytesMut::freeze`: a `Bytes` of its bytes, which nothing writes again. */ +export function bytesMutFreeze(b: BytesMut): Bytes { + return new ByteSlice(b.data, b.start, b.length); +} + +/** `From for Vec`. */ +export function bytesMutToByteVec(b: BytesMut): ByteVec { + return byteSliceToByteVec(bytesMutView(b)); +} + +/** `BytesMut::reserve`: room for `additional` more bytes, panicking as `bytes` does past what a buffer holds. */ +export function bytesMutReserve(b: BytesMut, additional: usize): void { + if (additional <= b.cap - b.length) return; + const needed = b.length + additional; + // A vector's own storage moves its bytes to the front where that alone makes the room. + if (!b.shared && b.start >= b.length && b.cap - b.length + b.start >= additional) { + b.data.copyWithin(0, b.start, b.start + b.length); + b.cap += b.start; + b.start = 0; + return; + } + if (needed > 0xffffffff && b.shared) panic("overflow"); + // A vector grows past its offset, where a shared one starts afresh. + if ((b.shared ? needed : b.start + needed) > ISIZE_MAX) panic("capacity overflow"); + const cap = Math.max(needed, b.cap * 2, 8); + const data = bytes(cap); + copyBytes(data, 0, b.data, b.start, b.length); + b.data = data; + b.start = 0; + b.cap = cap; + b.shared = false; +} + +/** `BytesMut::extend_from_slice`, and `BufMut::put_slice`. */ +export function bytesMutExtend(b: BytesMut, s: ByteSlice): void { + bytesMutReserve(b, s.length); + copyBytes(b.data, b.start + b.length, s.data, s.start, s.length); + b.length += s.length; +} + +/** `BufMut::put_u8` and the other writes of a narrow integer: its low `n` bytes, big-endian unless `le`. */ +export function bytesMutPutWord(b: BytesMut, v: number, n: number, le: boolean): void { + bytesMutReserve(b, n); + const at = b.start + b.length; + for (let i = 0; i < n; i++) b.data[at + (le ? i : n - 1 - i)] = v >>> (8 * i); + b.length += n; +} + +/** `BufMut::put_*` of the big-endian bytes of a wide integer or float, reversed if `le`. */ +export function bytesMutPutBytes(b: BytesMut, be: Uint8Array, le: boolean): void { + bytesMutReserve(b, be.length); + const at = b.start + b.length; + for (let i = 0; i < be.length; i++) b.data[at + i] = be[le ? be.length - 1 - i : i]; + b.length += be.length; +} + +/** `BufMut::put_uint` or `put_int`: the low `nbytes` of the big-endian bytes, which `bytes` checks against `size` the other way around. */ +export function bytesMutPutInt(b: BytesMut, be: Uint8Array, nbytes: usize, le: boolean): void { + if (nbytes > be.length) panic(`size too large: the integer type can fit ${nbytes} bytes, but nbytes is ${be.length}`); + bytesMutPutBytes(b, be.subarray(be.length - nbytes), le); +} + +/** `BufMut::put_bytes`: `cnt` copies of `val`. */ +export function bytesMutPutFill(b: BytesMut, val: number, cnt: usize): void { + bytesMutReserve(b, cnt); + b.data.fill(val, b.start + b.length, b.start + b.length + cnt); + b.length += cnt; +} + +/** `BytesMut::truncate`, and `clear` of 0. */ +export function bytesMutTruncate(b: BytesMut, len: usize): void { + if (len <= b.length) b.length = len; +} + +/** `BytesMut::resize`. */ +export function bytesMutResize(b: BytesMut, len: usize, value: number): void { + if (len <= b.length) { + b.length = len; + return; + } + bytesMutPutFill(b, value, len - b.length); +} + +/** `BytesMut::split_to`: the first `at` bytes, sharing the storage, leaving the rest. */ +export function bytesMutSplitTo(b: BytesMut, at: usize): BytesMut { + if (at > b.length) panic(`split_to out of bounds: ${at} <= ${b.length}`); + const head = new BytesMut(b.data, b.start, at, at, true); + b.start += at; + b.length -= at; + b.cap -= at; + b.shared = true; + return head; +} + +/** `BytesMut::unsplit`: `other`'s bytes after these, in place where it follows them in their storage. */ +export function bytesMutUnsplit(b: BytesMut, other: BytesMut): void { + if (b.length === 0) { + b.data = other.data; + b.start = other.start; + b.length = other.length; + b.cap = other.cap; + b.shared = other.shared; + return; + } + if (other.cap === 0) return; + if (b.shared && other.shared && b.data === other.data && b.start + b.length === other.start) { + b.length += other.length; + b.cap += other.cap; + return; + } + bytesMutExtend(b, bytesMutView(other)); +} + +/** `::advance`. */ +export function bytesMutAdvance(b: BytesMut, cnt: usize): void { + if (cnt > b.length) panicRemaining(cnt, b.length); + b.start += cnt; + b.length -= cnt; + b.cap -= cnt; +} + +/** `Buf::get_*` of `BytesMut`: its first `n` bytes, the other way around if `le`, read past. */ +export function bytesMutRead(b: BytesMut, n: usize, le: boolean): Uint8Array { + if (b.length < n) panicAdvance(n, b.length); + const read = readOf(bytesMutView(b), n, le); + bytesMutAdvance(b, n); + return read; +} + +/** `Buf::get_*` of `BytesMut` of at most 4 bytes, as an unsigned number. */ +export function bytesMutReadWord(b: BytesMut, n: usize, le: boolean): number { + if (b.length < n) panicAdvance(n, b.length); + const v = wordOf(bytesMutView(b), n, le); + bytesMutAdvance(b, n); + return v; +} + +/** `Buf::get_uint` or `get_int` of `BytesMut`, as `bytesReadInt`. */ +export function bytesMutReadInt(b: BytesMut, size: usize, nbytes: usize, signed: boolean, le: boolean): Uint8Array { + checkFits(size, nbytes); + return widen(bytesMutRead(b, nbytes, le), size, signed); +} + +/** `Buf::copy_to_slice` of `BytesMut`. */ +export function bytesMutCopyToSlice(b: BytesMut, dst: ByteSlice): void { + if (b.length < dst.length) panicAdvance(dst.length, b.length); + copyBytes(dst.data, dst.start, b.data, b.start, dst.length); + bytesMutAdvance(b, dst.length); +} + +/** + * `BufMut::put` into a `BytesMut` of a `Buf` the crate implements, through its methods. + * Into no room, `bytes` takes `copy_to_bytes` of all of it; into some, each chunk in turn. + */ +export function bytesMutPutBuf( + b: BytesMut, + src: B, + hasRemaining: (src: B) => boolean, + remaining: (src: B) => usize, + chunk: (src: B) => ByteSlice, + advance: (src: B, cnt: usize) => void, + copyToBytes: (src: B, len: usize) => Bytes, +): void { + if (!hasRemaining(src)) return; + if (b.cap === 0) { + bytesMutExtend(b, copyToBytes(src, remaining(src))); + return; + } + bytesMutReserve(b, remaining(src)); + while (hasRemaining(src)) { + const s = chunk(src); + bytesMutExtend(b, s); + advance(src, s.length as usize); + } +} + +// BufMut of Vec + +/** `BufMut::put` into a `Vec` of a `Buf` the crate implements, each chunk in turn. */ +export function byteVecPutBuf( + v: ByteVec, + src: B, + hasRemaining: (src: B) => boolean, + remaining: (src: B) => usize, + chunk: (src: B) => ByteSlice, + advance: (src: B, cnt: usize) => void, +): void { + if (v.length + remaining(src) > ISIZE_MAX) panic("capacity overflow"); + while (hasRemaining(src)) { + const s = chunk(src); + byteVecExtendFromSlice(v, s); + advance(src, s.length as usize); + } +} + +/** `BufMut::put_u8` and the other writes of a narrow integer to a `Vec`, as `bytesMutPutWord`. */ +export function byteVecPutWord(v: ByteVec, value: number, n: number, le: boolean): void { + for (let i = 0; i < n; i++) byteVecPush(v, value >>> (8 * (le ? i : n - 1 - i))); +} + +/** `BufMut::put_*` of big-endian bytes to a `Vec`, reversed if `le`. */ +export function byteVecPutBytes(v: ByteVec, be: Uint8Array, le: boolean): void { + for (let i = 0; i < be.length; i++) byteVecPush(v, be[le ? be.length - 1 - i : i]); +} + +/** `BufMut::put_uint` or `put_int` to a `Vec`, as `bytesMutPutInt`. */ +export function byteVecPutInt(v: ByteVec, be: Uint8Array, nbytes: usize, le: boolean): void { + if (nbytes > be.length) panic(`size too large: the integer type can fit ${nbytes} bytes, but nbytes is ${be.length}`); + byteVecPutBytes(v, be.subarray(be.length - nbytes), le); +} + +/** `BufMut::put_bytes` to a `Vec`: its `resize`, which panics past what a vector holds. */ +export function byteVecPutFill(v: ByteVec, val: number, cnt: usize): void { + if (v.length + cnt > ISIZE_MAX) panic("capacity overflow"); + for (let i = 0; i < cnt; i++) byteVecPush(v, val); +} diff --git a/ts/src/census.rs b/ts/src/census.rs index a2fbc2a0b..b615d0a69 100644 --- a/ts/src/census.rs +++ b/ts/src/census.rs @@ -141,6 +141,7 @@ const VERBATIM: &[&str] = &[ ".await", "?", "Binary", + "BufMut::put", "Bytes::from_owner", "Copy", "Debug", diff --git a/ts/src/lower/fmt.rs b/ts/src/lower/fmt.rs index 40c26bbb8..fe50951fa 100644 --- a/ts/src/lower/fmt.rs +++ b/ts/src/lower/fmt.rs @@ -299,6 +299,7 @@ pub fn std_impl<'tcx>( (Std::Utf8Error, Trait::Display) => rt("utf8ErrorDisplay", vec![value, f]), (Std::Duration, Trait::Debug) => Expr::rt("durationDebug", vec![value, f]), (Std::Bytes, Trait::Debug) => Expr::rt("bytesDebug", vec![value, f]), + (Std::BytesMut, Trait::Debug) => Expr::rt("bytesDebug", vec![Expr::rt("bytesMutView", vec![value]), f]), _ => return None, }, _ => return None, diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 63508fc76..75ec6a1f2 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -125,6 +125,8 @@ pub enum Std { Duration, /// `bytes::Bytes`: an `rt.ByteSlice`, as `&[u8]` is. Bytes, + /// `bytes::BytesMut`: `rt.BytesMut`, a window of storage it shares with what it splits off. + BytesMut, /// `rand::rngs::ThreadRng`: `rt.ThreadRng`, which holds no state. ThreadRng, } diff --git a/ts/src/lower/mir/decided.rs b/ts/src/lower/mir/decided.rs index 139f6ceda..36f4a5855 100644 --- a/ts/src/lower/mir/decided.rs +++ b/ts/src/lower/mir/decided.rs @@ -25,7 +25,7 @@ use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use crate::lower::Crates; /// Fold each switch in `body` that an enclosing switch decided. -pub fn fold<'tcx>(tcx: TyCtxt<'tcx>, crates: &Crates, body: &mut mir::Body<'tcx>) { +pub fn fold<'tcx>(tcx: TyCtxt<'tcx>, crates: &Crates<'tcx>, body: &mut mir::Body<'tcx>) { let flow = Flow::new(tcx, crates, body); let entry = flow.solve(body); let mut folded = false; @@ -161,7 +161,7 @@ impl<'tcx> Narrowing<'tcx> { } /// Where `body`'s tests and payload reads must see a place's whole type. -pub fn narrowing<'tcx>(tcx: TyCtxt<'tcx>, crates: &Crates, body: &mir::Body<'tcx>) -> Narrowing<'tcx> { +pub fn narrowing<'tcx>(tcx: TyCtxt<'tcx>, crates: &Crates<'tcx>, body: &mir::Body<'tcx>) -> Narrowing<'tcx> { let mut flow = Flow::new(tcx, crates, body); // A widened test narrows nothing, which can leave a later test to widen too. loop { @@ -186,7 +186,7 @@ type Decided = (usize, Vec<(u128, BasicBlock)>, BasicBlock); /// What a body's places are, for the dataflow. struct Flow<'c, 'tcx> { tcx: TyCtxt<'tcx>, - crates: &'c Crates, + crates: &'c Crates<'tcx>, /// Each reference local whose one write is an assignment, as the place it borrows or /// the place behind the reference it copies. borrows: IndexVec>>, @@ -202,7 +202,7 @@ struct Flow<'c, 'tcx> { } impl<'c, 'tcx> Flow<'c, 'tcx> { - fn new(tcx: TyCtxt<'tcx>, crates: &'c Crates, body: &mir::Body<'tcx>) -> Self { + fn new(tcx: TyCtxt<'tcx>, crates: &'c Crates<'tcx>, body: &mir::Body<'tcx>) -> Self { let n = body.local_decls.len(); let mut writes = Writes(IndexVec::from_elem_n(0, n)); writes.visit_body(body); @@ -718,7 +718,7 @@ fn union(a: &[u128], b: &[u128]) -> Vec { /// Whether a value of `ty` can change what it points at: it is or holds a `&mut` or a /// `*mut`, or hides what it holds. -fn lends<'tcx>(tcx: TyCtxt<'tcx>, crates: &Crates, ty: Ty<'tcx>) -> bool { +fn lends<'tcx>(tcx: TyCtxt<'tcx>, crates: &Crates<'tcx>, ty: Ty<'tcx>) -> bool { let mut seen = FxHashSet::default(); let mut stack = vec![ty]; while let Some(ty) = stack.pop() { diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index a95bb50fe..b835d259e 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -175,7 +175,7 @@ pub struct Translator<'a, 'tcx> { pub tcx: TyCtxt<'tcx>, config: &'a Config, /// The crates whose bodies translate. - pub crates: Crates, + pub crates: Crates<'tcx>, pub program: Program, instances: rustc_data_structures::fx::FxHashMap, SymId>, queue: VecDeque<(Instance<'tcx>, SymId)>, @@ -224,28 +224,30 @@ pub struct Translator<'a, 'tcx> { } /// The crates that translate as one program: the package, and every crate it depends on -/// but std's and those [`stock`] maps. What the roots reach of them translates; any -/// function of the others is its mapping, a binding, or refused. -pub struct Crates(rustc_data_structures::fx::FxHashSet); - -impl Crates { - fn new(tcx: TyCtxt<'_>) -> Self { - Self( - tcx.crates(()) - .iter() - .copied() - .filter(|&krate| { - !tcx.crate_dep_kind(krate).macros_only() - && !of_std(tcx, krate) - && !stock::is_stock_crate(tcx, krate) - }) - .collect(), - ) +/// but std's and those [`stock`] maps whole. What the roots reach of them translates, but +/// for what [`stock`] maps in place of it; any function of the others is its mapping, a +/// binding, or refused. +pub struct Crates<'tcx> { + tcx: TyCtxt<'tcx>, + crates: rustc_data_structures::fx::FxHashSet, +} + +impl<'tcx> Crates<'tcx> { + fn new(tcx: TyCtxt<'tcx>) -> Self { + let crates = tcx + .crates(()) + .iter() + .copied() + .filter(|&krate| { + !tcx.crate_dep_kind(krate).macros_only() && !of_std(tcx, krate) && !stock::is_opaque_crate(tcx, krate) + }) + .collect(); + Self { tcx, crates } } - /// Whether `def_id`'s crate translates. + /// Whether `def_id` translates: it is of a crate that does, and no mapping stands in for it. pub fn translates(&self, def_id: DefId) -> bool { - def_id.is_local() || self.0.contains(&def_id.krate) + def_id.is_local() || (self.crates.contains(&def_id.krate) && !stock::mapped(self.tcx, def_id)) } } @@ -887,7 +889,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { match instance.def { InstanceKind::Item(did) => { self.bound_module(instance).is_none() - && (self.crates.translates(did) || library::from_mir(self, instance)) + && ((self.crates.translates(did) && !stock::maps(self.tcx, instance)) + || library::from_mir(self, instance)) } _ => false, } @@ -1135,6 +1138,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { | library::Std::VecDeque | library::Std::Entry | library::Std::Hasher + | library::Std::BytesMut | library::Std::ThreadRng, ) => Some(ObjectKind::Class), // A place, unless a pointer to what it holds is that object. @@ -1467,6 +1471,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { library::Std::Hasher => Type::Rt("Hasher", vec![]), library::Std::Duration => Type::Rt("Duration", vec![]), library::Std::Bytes => Type::Rt("ByteSlice", vec![]), + library::Std::BytesMut => Type::Rt("BytesMut", vec![]), library::Std::ThreadRng => Type::Rt("ThreadRng", vec![]), library::Std::ControlFlow => { if let Some(msg) = self.erasure_conflict(Ty::new_adt(tcx, adt, args)) { diff --git a/ts/src/lower/pointer.rs b/ts/src/lower/pointer.rs index cea49e48b..ed651a5e6 100644 --- a/ts/src/lower/pointer.rs +++ b/ts/src/lower/pointer.rs @@ -195,10 +195,12 @@ pub fn keeps(tcx: ty::TyCtxt<'_>, def_id: rustc_hir::def_id::DefId) -> bool { ) } -/// Whether std's `def_id` is one this module maps that takes the `rt.Place` a `&mut self` -/// is, rather than what it points at: a `MaybeUninit`'s, which it points into. +/// Whether std's `def_id` is one a mapping takes the `rt.Place` a `&mut` is for, rather +/// than what it points at: a `MaybeUninit`'s, which it points into, and a well-known +/// crate's, such as a `Bytes` that `Buf::advance` moves past its front. pub fn takes_place(tcx: ty::TyCtxt<'_>, def_id: rustc_hir::def_id::DefId) -> bool { matches!(super::library::key(tcx, def_id), Some((owner, _)) if owner == "MaybeUninit") + || super::stock::is_stock(tcx, def_id) } /// A call of std's raw pointer, `NonNull`, `MaybeUninit`, or `Box` functions that make or diff --git a/ts/src/lower/stock.rs b/ts/src/lower/stock.rs index 9bce159b3..39bb25f1f 100644 --- a/ts/src/lower/stock.rs +++ b/ts/src/lower/stock.rs @@ -1,15 +1,16 @@ //! Well-known crates that translation maps itself, as it maps std, so a consumer binds -//! none of them: `bytes::Bytes`, which is the `rt.ByteSlice` a `&[u8]` is, and `rand`'s -//! thread-local generator, which draws from the platform's cryptographic source. -//! `tracing`'s events are left out where they are written, by -//! [`super::Translator::ignored_site`]. +//! none of them: `bytes`' `Bytes`, which is the `rt.ByteSlice` a `&[u8]` is, and +//! `BytesMut`, which is `rt.BytesMut`, and `rand`'s thread-local generator, which draws +//! from the platform's cryptographic source. The rest of `bytes`, such as `Buf`'s provided +//! methods of the crate's own buffers, translates from its MIR. `tracing`'s events are +//! left out where they are written, by [`super::Translator::ignored_site`]. use rustc_hir::def::DefKind; use rustc_hir::def_id::{CrateNum, DefId}; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeVisitableExt}; use super::body::Body; -use super::library::{Call, Std, key, string, targ}; +use super::library::{self, Call, Std, key, string, targ}; use super::num::Int; use crate::ts::{Expr, Stmt}; @@ -20,6 +21,7 @@ pub fn of(tcx: TyCtxt<'_>, did: DefId) -> Option { } match (tcx.crate_name(did.krate).as_str(), tcx.opt_item_name(did)?.as_str()) { ("bytes", "Bytes") => Some(Std::Bytes), + ("bytes", "BytesMut") => Some(Std::BytesMut), ("rand", "ThreadRng") => Some(Std::ThreadRng), _ => None, } @@ -31,11 +33,176 @@ pub fn is_stock(tcx: TyCtxt<'_>, did: DefId) -> bool { !did.is_local() && is_stock_crate(tcx, did.krate) } -/// Whether `krate`, a dependency, is one of these crates, which maps rather than translates. +/// Whether `krate`, a dependency, is one of these crates, whose functions map, or translate +/// only where [`maps`] says they don't. pub fn is_stock_crate(tcx: TyCtxt<'_>, krate: CrateNum) -> bool { matches!(tcx.crate_name(krate).as_str(), "bytes" | "rand") } +/// Whether `krate` is one of these crates of which nothing translates: `rand`, whose +/// generators would have to be its own. +pub fn is_opaque_crate(tcx: TyCtxt<'_>, krate: CrateNum) -> bool { + tcx.crate_name(krate).as_str() == "rand" +} + +/// Whether `did`, an item of `bytes`, has a mapping in place of its MIR: `Bytes`, +/// `BytesMut`, and their functions and impls, and the crate's impls of std's byte slices +/// and vectors. The mapping of a function stands in for it or refuses it. The impls that +/// forward through a reference or a `Box`, and the crate's other types and functions, +/// translate. +pub fn mapped(tcx: TyCtxt<'_>, did: DefId) -> bool { + if tcx.crate_name(did.krate).as_str() != "bytes" { + return false; + } + match tcx + .opt_parent(did) + .filter(|&imp| matches!(tcx.def_kind(imp), DefKind::Impl { .. })) + { + Some(imp) => mapped_self(tcx, tcx.type_of(imp).instantiate_identity().skip_norm_wip()), + None => of(tcx, did).is_some(), + } +} + +/// Whether `instance`, a provided method of `Buf` or `BufMut`, maps for its `Self`, which +/// [`mapped`] can't tell from the method alone: one the mapping names, of a buffer whose +/// impl maps. The others lower from their MIR, as for the crate's own buffers. +pub fn maps<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool { + let did = instance.def_id(); + tcx.crate_name(did.krate).as_str() == "bytes" + && tcx.trait_of_assoc(did).is_some() + && mapped_self(tcx, instance.args.type_at(0)) + && (BUF.contains(&tcx.item_name(did).as_str()) || BUF_MUT.contains(&tcx.item_name(did).as_str())) +} + +/// `Buf`'s methods that the mapping names for its buffers. +const BUF: &[&str] = &[ + "remaining", + "chunk", + "advance", + "has_remaining", + "copy_to_slice", + "copy_to_bytes", + "get_u8", + "get_i8", + "get_u16", + "get_u16_le", + "get_u16_ne", + "get_i16", + "get_i16_le", + "get_i16_ne", + "get_u32", + "get_u32_le", + "get_u32_ne", + "get_i32", + "get_i32_le", + "get_i32_ne", + "get_u64", + "get_u64_le", + "get_u64_ne", + "get_i64", + "get_i64_le", + "get_i64_ne", + "get_u128", + "get_u128_le", + "get_u128_ne", + "get_i128", + "get_i128_le", + "get_i128_ne", + "get_f64", + "get_f64_le", + "get_f64_ne", + "get_uint", + "get_uint_le", + "get_uint_ne", + "get_int", + "get_int_le", + "get_int_ne", +]; + +/// `BufMut`'s methods that the mapping names for its buffers. +const BUF_MUT: &[&str] = &[ + "remaining_mut", + "has_remaining_mut", + "put", + "put_slice", + "put_bytes", + "put_u8", + "put_i8", + "put_u16", + "put_u16_le", + "put_u16_ne", + "put_i16", + "put_i16_le", + "put_i16_ne", + "put_u32", + "put_u32_le", + "put_u32_ne", + "put_i32", + "put_i32_le", + "put_i32_ne", + "put_u64", + "put_u64_le", + "put_u64_ne", + "put_i64", + "put_i64_le", + "put_i64_ne", + "put_u128", + "put_u128_le", + "put_u128_ne", + "put_i128", + "put_i128_le", + "put_i128_ne", + "put_f64", + "put_f64_le", + "put_f64_ne", + "put_uint", + "put_uint_le", + "put_uint_ne", + "put_int", + "put_int_le", + "put_int_ne", +]; + +/// A buffer that the mapping of `Buf` or `BufMut` reads or writes. +#[derive(Clone, Copy, PartialEq)] +enum Buffer { + /// A `Bytes`, whose `&mut` is an `rt.Place`. + Bytes, + BytesMut, + /// A `&[u8]`, which `Buf` reads through `&self` only: a `&mut` to it is refused. + Slice, + /// A `Vec`, which `BufMut` writes. + Vec, +} + +impl Buffer { + fn of<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option { + match ty.kind() { + ty::Adt(adt, args) => match library::Std::of(tcx, adt.did())? { + Std::Bytes => Some(Self::Bytes), + Std::BytesMut => Some(Self::BytesMut), + Std::Vec if is_u8(args.type_at(0)) => Some(Self::Vec), + _ => None, + }, + ty::Ref(_, inner, ty::Mutability::Not) if matches!(inner.kind(), ty::Slice(e) if is_u8(*e)) => { + Some(Self::Slice) + } + _ => None, + } + } +} + +/// Whether `ty`, the `Self` of a function of `bytes`, has a representation of its own or +/// is std's, so a mapping stands in for its impls: not a type parameter, through which an +/// impl forwards, nor the crate's own buffer or another crate's, which translate. +fn mapped_self<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { + match ty.kind() { + ty::Adt(adt, _) => library::Std::of(tcx, adt.did()).is_some() && !ty.has_param(), + ty::Ref(_, inner, _) => matches!(inner.kind(), ty::Slice(e) if is_u8(*e)), + _ => false, + } +} + /// A call of one of these crates' functions, or of a std trait's on one of their types: /// its mapping, `None` if it has none, or its arguments back if it is no such call. pub fn call<'tcx>( @@ -51,58 +218,126 @@ pub fn call<'tcx>( let self_std = call.args.types().next().and_then(|t| b.t.std_of(t.peel_refs())); if is_stock(tcx, call.def_id) { return Ok(match tcx.crate_name(call.def_id.krate).as_str() { - "bytes" => bytes(b, call, &name, args, out), + "bytes" => bytes(b, call, &owner, &name, args, out), _ => rand(b, call, &owner, &name, args, out), }); } - match (owner.as_str(), name.as_str(), self_std) { + let mut args = args.into_iter(); + let mut arg = || args.next().expect("an argument"); + Ok(match (owner.as_str(), name.as_str(), self_std) { // A clone of either shares what it holds, and a `Bytes` is the slice it derefs to. ("Clone", "clone", Some(Std::Bytes | Std::ThreadRng)) | ("Deref", "deref", Some(Std::Bytes)) | ("AsRef", "as_ref", Some(Std::Bytes)) - | ("Borrow", "borrow", Some(Std::Bytes)) => Ok(args.into_iter().next()), - ("Default", "default", Some(Std::Bytes)) => Ok(Some(Expr::rt("bytesNew", vec![]))), - ("Default", "default", Some(Std::ThreadRng)) => Ok(Some(Expr::rt("randRng", vec![]))), - ("PartialEq", "eq", Some(Std::Bytes)) => { - let other = targ(call.args, 1).peel_refs(); - let bytes = b.t.std_of(other) == Some(Std::Bytes) - || matches!(other.kind(), ty::Slice(e) if matches!(e.kind(), ty::Uint(ty::UintTy::U8))); - Ok(bytes.then(|| Expr::rt("byteSliceEq", args))) + | ("Borrow", "borrow", Some(Std::Bytes)) => Some(arg()), + // A `BytesMut` lends a slice of its storage, and its clone copies it. + ("Deref", "deref", Some(Std::BytesMut)) + | ("DerefMut", "deref_mut", Some(Std::BytesMut)) + | ("AsRef", "as_ref", Some(Std::BytesMut)) + | ("AsMut", "as_mut", Some(Std::BytesMut)) + | ("Borrow", "borrow", Some(Std::BytesMut)) + | ("BorrowMut", "borrow_mut", Some(Std::BytesMut)) => Some(view(arg())), + ("Clone", "clone", Some(Std::BytesMut)) => Some(Expr::rt("bytesMutFrom", vec![view(arg())])), + ("Default", "default", Some(Std::Bytes)) => Some(Expr::rt("bytesNew", vec![])), + ("Default", "default", Some(Std::BytesMut)) => Some(Expr::rt("bytesMutWithCapacity", vec![Expr::lit("0")])), + ("Default", "default", Some(Std::ThreadRng)) => Some(Expr::rt("randRng", vec![])), + ("PartialEq", "eq", _) => { + let (l, r) = (targ(call.args, 0).peel_refs(), targ(call.args, 1).peel_refs()); + let stock = |t: Ty<'tcx>| matches!(b.t.std_of(t), Some(Std::Bytes | Std::BytesMut)); + if !stock(l) && !stock(r) { + return Err(args.collect()); + } + let (a, c) = (arg(), arg()); + match (as_slice(b, l, a), as_slice(b, r, c)) { + (Some(a), Some(c)) => Some(Expr::rt("byteSliceEq", vec![a, c])), + _ => None, + } } - ("From", "from", _) => from(b, call, args), - _ => Err(args), - } + ("From", "from", _) => return from(b, call, args.collect()), + _ => return Err(args.collect()), + }) } -/// `From::from` into or out of a `Bytes`. +/// The bytes of `value`, a `ty`, as an `rt.ByteSlice`, if it is a run of bytes. +fn as_slice<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>, value: Expr) -> Option { + Some(match ty.kind() { + ty::Slice(e) if is_u8(*e) => value, + ty::Array(e, _) if is_u8(*e) => Expr::rt("byteSliceFrom", vec![value]), + _ if string(b.t.tcx, ty) => Expr::rt("stringAsBytes", vec![value]), + _ => match b.t.std_of(ty)? { + Std::Bytes => value, + Std::BytesMut => view(value), + Std::Vec if targ_is_u8(ty) => Expr::rt("byteVecSlice", vec![value]), + _ => return None, + }, + }) +} + +/// The bytes of a `BytesMut`. +fn view(value: Expr) -> Expr { + Expr::rt("bytesMutView", vec![value]) +} + +/// `From::from` into or out of a `Bytes` or a `BytesMut`. fn from<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec) -> Result, Vec> { let tcx = b.t.tcx; let (to, from) = (targ(call.args, 0), targ(call.args, 1)); let byte_vec = |t: Ty<'tcx>| b.t.std_of(t) == Some(Std::Vec) && targ_is_u8(t); + let mut args = args.into_iter(); let f = match (b.t.std_of(to), b.t.std_of(from)) { + (Some(Std::Bytes), Some(Std::BytesMut)) => "bytesMutFreeze", (Some(Std::Bytes), _) if byte_vec(from) => "byteVecSlice", (Some(Std::Bytes), _) if string(tcx, from.peel_refs()) => "stringAsBytes", - (Some(Std::Bytes), _) if is_bytes_ref(from) => return Ok(args.into_iter().next()), + (Some(Std::Bytes), _) if is_bytes_ref(from) => return Ok(args.next()), (Some(Std::Bytes), _) => return Ok(None), + (Some(Std::BytesMut), _) => { + let bytes = match as_slice(b, from.peel_refs(), args.next().expect("an operand")) { + Some(bytes) if from.is_ref() || b.t.std_of(from) == Some(Std::Bytes) => bytes, + _ => return Ok(None), + }; + return Ok(Some(Expr::rt("bytesMutFrom", vec![bytes]))); + } (_, Some(Std::Bytes)) if byte_vec(to) => "byteSliceToByteVec", - (_, Some(Std::Bytes)) => return Ok(None), - _ => return Err(args), + (_, Some(Std::BytesMut)) if byte_vec(to) => "bytesMutToByteVec", + (_, Some(Std::Bytes | Std::BytesMut)) => return Ok(None), + _ => return Err(args.collect()), }; - Ok(Some(Expr::rt(f, args))) + Ok(Some(Expr::rt(f, args.collect()))) } -/// A function of `bytes`: `Bytes`'s own. +/// A function of `bytes`: `Bytes`'s or `BytesMut`'s own, or a method of `Buf` or `BufMut` +/// on a buffer the mapping reads or writes. fn bytes<'tcx>( b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, + owner: &str, name: &str, args: Vec, out: &mut Vec, ) -> Option { let tcx = b.t.tcx; - if super::library::inherent_std(tcx, call.def_id) != Some(Std::Bytes) { - return None; + match super::library::inherent_std(tcx, call.def_id) { + Some(Std::Bytes) => return bytes_own(b, call, name, args, out), + Some(Std::BytesMut) => return bytes_mut(b, call, name, args, out), + _ => {} + } + let buffer = Buffer::of(tcx, targ(call.args, 0))?; + match owner { + "Buf" => buf(b, call, buffer, name, args), + "BufMut" => buf_mut(b, call, buffer, name, args), + _ => None, } +} + +/// A function of `Bytes`: a `&mut self` one takes its `rt.Place`. +fn bytes_own<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + call: &Call<'tcx>, + name: &str, + args: Vec, + out: &mut Vec, +) -> Option { + let tcx = b.t.tcx; let mut args = args.into_iter(); Some(match name { "new" => Expr::rt("bytesNew", vec![]), @@ -115,6 +350,11 @@ fn bytes<'tcx>( "slice" if b.t.std_of(targ(call.args, 0)) == Some(Std::RangeInclusive) => { Expr::rt("bytesSliceInclusive", vec![args.next()?, args.next()?]) } + "slice_ref" => Expr::rt("bytesSliceRef", vec![args.next()?, args.next()?]), + "split_to" => Expr::rt("bytesSplitTo", vec![args.next()?, args.next()?]), + "split_off" => Expr::rt("bytesSplitOff", vec![args.next()?, args.next()?]), + "truncate" => Expr::rt("bytesTruncate", vec![args.next()?, args.next()?]), + "clear" => Expr::rt("bytesTruncate", vec![args.next()?, Expr::lit("0")]), // The owner is read once, as `bytes` reads it, and would drop with the last `Bytes` // that shares it, which no value here tracks. "from_owner" => { @@ -139,6 +379,224 @@ fn bytes<'tcx>( }) } +/// A function of `BytesMut`. What reads its capacity is refused: `bytes`' depends on +/// whether the other handles of its storage dropped, such as a `Bytes` it froze, which +/// none here counts. +fn bytes_mut( + b: &mut Body<'_, '_, '_>, + call: &Call<'_>, + name: &str, + args: Vec, + out: &mut Vec, +) -> Option { + if matches!( + name, + "capacity" | "split_off" | "try_reclaim" | "try_unsplit" | "spare_capacity_mut" + ) { + let msg = format!( + "`BytesMut::{name}`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported" + ); + return Some(b.err(call.span, msg)); + } + let mut args = args.into_iter(); + let mut arg = || args.next(); + let f = match name { + "new" => return Some(Expr::rt("bytesMutWithCapacity", vec![Expr::lit("0")])), + "with_capacity" => "bytesMutWithCapacity", + "zeroed" => "bytesMutZeroed", + "len" => return Some(arg()?.member("length")), + "is_empty" => return Some(arg()?.member("length").binary("===", Expr::lit("0"))), + "freeze" => "bytesMutFreeze", + "split_to" => "bytesMutSplitTo", + "split" => { + let this = b.spill(arg()?, "buf", out); + return Some(Expr::rt("bytesMutSplitTo", vec![this.clone(), this.member("length")])); + } + "truncate" => "bytesMutTruncate", + "clear" => return Some(Expr::rt("bytesMutTruncate", vec![arg()?, Expr::lit("0")])), + "resize" => "bytesMutResize", + "reserve" => "bytesMutReserve", + "extend_from_slice" => "bytesMutExtend", + "unsplit" => "bytesMutUnsplit", + _ => return None, + }; + Some(Expr::rt(f, args.collect())) +} + +/// A method of `Buf` on a buffer the mapping reads. +fn buf<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + call: &Call<'tcx>, + buffer: Buffer, + name: &str, + args: Vec, +) -> Option { + let mut args = args.into_iter(); + let this = args.next()?; + // What reads past the front: a `Bytes`'s place, or a `BytesMut`. A `&[u8]`'s would be a + // `&mut` to a reference, which is not supported yet. + let prefix = match buffer { + Buffer::Bytes => Some("bytes"), + Buffer::BytesMut => Some("bytesMut"), + Buffer::Slice | Buffer::Vec => None, + }; + let rt = |f: &str, args: Vec| Some(Expr::rt(format!("{}{f}", prefix?), args)); + Some(match name { + "remaining" => this.member("length"), + "has_remaining" => this.member("length").binary("!==", Expr::lit("0")), + "chunk" if buffer == Buffer::BytesMut => view(this), + "chunk" => this, + "advance" => rt("Advance", vec![this, args.next()?])?, + "copy_to_slice" => rt("CopyToSlice", vec![this, args.next()?])?, + "copy_to_bytes" if buffer == Buffer::BytesMut => Expr::rt( + "bytesMutFreeze", + vec![Expr::rt("bytesMutSplitTo", vec![this, args.next()?])], + ), + "copy_to_bytes" => rt("SplitTo", vec![this, args.next()?])?, + _ => { + let (ty, le) = scalar(name.strip_prefix("get_")?); + let out = signature(b.t.tcx, call).output(); + let le = Expr::lit(le.to_string()); + match ty { + "uint" | "int" => { + let int = Int::of(out)?; + let (size, signed) = (Expr::lit("8"), Expr::lit(int.signed.to_string())); + let read = rt("ReadInt", vec![this, size, args.next()?, signed, le])?; + int.method("fromBeBytes", vec![read]) + } + "f64" => Expr::rt("f64FromBeBytes", vec![rt("Read", vec![this, Expr::lit("8"), le])?]), + _ => { + let int = Int::of(out)?; + let n = Expr::lit((int.bits / 8).to_string()); + if int.big() { + int.method("fromBeBytes", vec![rt("Read", vec![this, n, le])?]) + } else { + let word = rt("ReadWord", vec![this, n, le])?; + let word = if int.signed { int.wrap(word) } else { word }; + Expr::As(Box::new(word), int.ty()) + } + } + } + } + }) +} + +/// A method of `BufMut` on a buffer the mapping writes. +fn buf_mut<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + call: &Call<'tcx>, + buffer: Buffer, + name: &str, + args: Vec, +) -> Option { + let mut args = args.into_iter(); + let this = args.next()?; + let prefix = match buffer { + Buffer::BytesMut => "bytesMut", + Buffer::Vec => "byteVec", + Buffer::Bytes | Buffer::Slice => return None, + }; + let rt = |f: &str, args: Vec| Expr::rt(format!("{prefix}{f}"), args); + // A vector's or a `BytesMut`'s length is at most `isize::MAX`. + let isize_max = Expr::lit("0x7fffffff"); + Some(match name { + "remaining_mut" => Expr::As( + Box::new(isize_max.binary("-", this.member("length"))), + Int::of(b.t.tcx.types.usize)?.ty(), + ), + "has_remaining_mut" => this.member("length").binary("<", isize_max), + "put_slice" if buffer == Buffer::BytesMut => Expr::rt("bytesMutExtend", vec![this, args.next()?]), + "put_slice" => Expr::rt("byteVecExtendFromSlice", vec![this, args.next()?]), + "put" => put(b, call, buffer, this, args.next()?)?, + "put_bytes" => rt("PutFill", vec![this, args.next()?, args.next()?]), + _ => { + let (ty, le) = scalar(name.strip_prefix("put_")?); + let input = *signature(b.t.tcx, call).inputs().get(1)?; + let value = args.next()?; + let le = Expr::lit(le.to_string()); + match ty { + "uint" | "int" => { + let be = Int::of(input)?.method("toBeBytes", vec![value]); + rt("PutInt", vec![this, be, args.next()?, le]) + } + "f64" => rt("PutBytes", vec![this, Expr::rt("f64ToBeBytes", vec![value]), le]), + _ => { + let int = Int::of(input)?; + match int.big() { + true => rt("PutBytes", vec![this, int.method("toBeBytes", vec![value]), le]), + false => rt("PutWord", vec![this, value, Expr::lit((int.bits / 8).to_string()), le]), + } + } + } + } + }) +} + +/// `BufMut::put` of a `Buf` into a buffer the mapping writes: all of it, read whole from +/// a buffer the mapping reads, and otherwise through its own methods, as `bytes` reads it. +fn put<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, buffer: Buffer, this: Expr, src: Expr) -> Option { + let tcx = b.t.tcx; + let ty = targ(call.args, 1); + let bytes = match Buffer::of(tcx, ty) { + Some(Buffer::BytesMut) => Some(view(src.clone())), + Some(Buffer::Bytes | Buffer::Slice) => Some(src.clone()), + _ => None, + }; + if let Some(bytes) = bytes { + return Some(match buffer { + Buffer::BytesMut => Expr::rt("bytesMutExtend", vec![this, bytes]), + _ => Expr::rt("byteVecExtendFromSlice", vec![this, bytes]), + }); + } + // `put` drops it between calls of its methods, which only an object JS can call them on + // can stand for. + if b.t.drops(ty) || b.t.needs_place(ty) { + let msg = format!("`BufMut::put` of `{ty}`, which is not supported"); + return Some(b.err(call.span, msg)); + } + let buf = tcx + .traits(call.def_id.krate) + .iter() + .copied() + .find(|&tr| tcx.item_name(tr).as_str() == "Buf")?; + let mut method = |name: &str| { + let f = tcx + .associated_items(buf) + .in_definition_order() + .find(|i| i.is_fn() && i.name().as_str() == name)? + .def_id; + Some(b.fn_value(f, tcx.mk_args(&[ty.into()]), call.span)) + }; + let (has, remaining, chunk, advance) = ( + method("has_remaining")?, + method("remaining")?, + method("chunk")?, + method("advance")?, + ); + Some(match buffer { + Buffer::BytesMut => { + let copy = method("copy_to_bytes")?; + Expr::rt("bytesMutPutBuf", vec![this, src, has, remaining, chunk, advance, copy]) + } + _ => Expr::rt("byteVecPutBuf", vec![this, src, has, remaining, chunk, advance]), + }) +} + +/// A `get_` or `put_` method's scalar, and whether its bytes are little-endian, as +/// wasm32's native order is. +fn scalar(name: &str) -> (&str, bool) { + match name.strip_suffix("_le").or_else(|| name.strip_suffix("_ne")) { + Some(ty) => (ty, true), + None => (name, false), + } +} + +/// The signature of the function `call` names, with its arguments. +fn signature<'tcx>(tcx: TyCtxt<'tcx>, call: &Call<'tcx>) -> ty::FnSig<'tcx> { + let sig = tcx.fn_sig(call.def_id).instantiate(tcx, call.args).skip_norm_wip(); + tcx.instantiate_bound_regions_with_erased(sig) +} + /// A function of `rand`: `rng`, or a method of its `Rng` or `RngExt` on a `ThreadRng`. fn rand<'tcx>( b: &mut Body<'_, '_, 'tcx>, @@ -197,6 +655,10 @@ fn trait_fn(tcx: TyCtxt<'_>, item: rustc_span::Symbol) -> Option { .map(|i| i.def_id) } +fn is_u8(ty: Ty<'_>) -> bool { + matches!(ty.kind(), ty::Uint(ty::UintTy::U8)) +} + fn targ_is_u8(ty: Ty<'_>) -> bool { matches!(ty.kind(), ty::Adt(_, args) if args.types().next().is_some_and(|t| matches!(t.kind(), ty::Uint(ty::UintTy::U8)))) } From fa4e695ef4dc9e78153184371007f0697a1f62b2 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 07:50:30 -0700 Subject: [PATCH 3/9] chore(quest): plan a BytesMut's exact capacity Co-Authored-By: Claude Opus 5.5 --- quest/m3/README.md | 1 + quest/m3/ts-bytes-capacity.md | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 quest/m3/ts-bytes-capacity.md diff --git a/quest/m3/README.md b/quest/m3/README.md index de9b8bd2c..86ccbdeba 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -18,6 +18,7 @@ generic std gap is planned here even when moq never calls it. - [Unsafe code the translator can model](/quest/m3/ts-unsafe.md) - a dependency using only `unsafe` the translator can model translates from source - [f32](/quest/m3/ts-f32.md) - `f32` and `Duration`'s `f32` methods translate as `f64` does - [A mutable reference to a reference](/quest/m3/ts-mut-ref.md) - `&mut &[u8]` and `&mut &mut T` translate, so `Buf` of a `&[u8]` and `bytes`' forwarding impls do +- [A `BytesMut`'s capacity](/quest/m3/ts-bytes-capacity.md) - `BytesMut::capacity` and what reads it translate with `bytes`' values - [Trait objects](/quest/m3/ts-dyn.md) - `dyn Error`, `dyn Iterator`, and `dyn Buf` translate, so a consumer neither rewrites nor binds them - [Waiting: type-check in process with tsrs](/quest/m3/ts-tsrs.md) - rust2-ts checks bindings through tsrs instead of `tsc` once it is a stable library - [An inclusive range folded through an adaptor](/quest/m3/ts-range-fold.md) - a `RangeInclusive` folded through `map`, `filter`, or `rev` ends in core's state, and `by_ref` of one type-checks diff --git a/quest/m3/ts-bytes-capacity.md b/quest/m3/ts-bytes-capacity.md new file mode 100644 index 000000000..8ef908885 --- /dev/null +++ b/quest/m3/ts-bytes-capacity.md @@ -0,0 +1,21 @@ +# [M] A `BytesMut`'s capacity + +## Goal + +[rust2-ts](/ts/README.md) translates `BytesMut::capacity`, `split_off`, `try_reclaim`, +`try_unsplit`, and `spare_capacity_mut` with `bytes`' values, proven by differential tests +against native Rust. + +## Plan + +Found by [#222](https://github.com/kixelated/rust2/pull/222) on 2026-10-29: `bytes` +reclaims a `BytesMut`'s storage in `reserve` once no other handle of it is alive, so its +capacity depends on whether the `Bytes` it froze and the handles it split off dropped. +`rt.ByteSlice`, which a `Bytes` is, is a value JS copies and counts no drops, so #222 +refuses these. moq calls none of them. + +- Count the live handles of a storage, as [shared ownership](/quest/m2/ts-shared.md) counts + an `Arc`'s, which makes a `Bytes` a value that drops. +- Measure the count's cost on the codec's [TS benchmark](/ts/README.md#bench). + +Public API: the translator's output. From d7c216a08e5102d0c5db47312a17934ae754d1b2 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 07:50:38 -0700 Subject: [PATCH 4/9] chore(quest): title the BytesMut capacity quest as quest check requires Co-Authored-By: Claude Opus 5.5 --- quest/m3/README.md | 2 +- quest/m3/ts-bytes-capacity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/quest/m3/README.md b/quest/m3/README.md index 86ccbdeba..e7b4232d7 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -18,7 +18,7 @@ generic std gap is planned here even when moq never calls it. - [Unsafe code the translator can model](/quest/m3/ts-unsafe.md) - a dependency using only `unsafe` the translator can model translates from source - [f32](/quest/m3/ts-f32.md) - `f32` and `Duration`'s `f32` methods translate as `f64` does - [A mutable reference to a reference](/quest/m3/ts-mut-ref.md) - `&mut &[u8]` and `&mut &mut T` translate, so `Buf` of a `&[u8]` and `bytes`' forwarding impls do -- [A `BytesMut`'s capacity](/quest/m3/ts-bytes-capacity.md) - `BytesMut::capacity` and what reads it translate with `bytes`' values +- [The capacity of a BytesMut](/quest/m3/ts-bytes-capacity.md) - `BytesMut::capacity` and what reads it translate with `bytes`' values - [Trait objects](/quest/m3/ts-dyn.md) - `dyn Error`, `dyn Iterator`, and `dyn Buf` translate, so a consumer neither rewrites nor binds them - [Waiting: type-check in process with tsrs](/quest/m3/ts-tsrs.md) - rust2-ts checks bindings through tsrs instead of `tsc` once it is a stable library - [An inclusive range folded through an adaptor](/quest/m3/ts-range-fold.md) - a `RangeInclusive` folded through `map`, `filter`, or `rev` ends in core's state, and `by_ref` of one type-checks diff --git a/quest/m3/ts-bytes-capacity.md b/quest/m3/ts-bytes-capacity.md index 8ef908885..8d64f2752 100644 --- a/quest/m3/ts-bytes-capacity.md +++ b/quest/m3/ts-bytes-capacity.md @@ -1,4 +1,4 @@ -# [M] A `BytesMut`'s capacity +# [M] The capacity of a BytesMut ## Goal From 0107b7758128017438c3250058143b966abd6897 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:24:17 -0700 Subject: [PATCH 5/9] fix(ts): refuse BufMut::put of a crate's own Buf into a BytesMut bytes calls the source's copy_to_bytes or its chunk and advance by whether the BytesMut's capacity is zero, which depends on whether other handles of its storage dropped. rt.BytesMut can't tell, so the calls a crate's own Buf sees could differ. Put into a Vec stays mapped. Co-Authored-By: Claude Opus 5.5 --- ts/README.md | 4 +- ts/fixtures/reject/census.md | 197 ++++++++++++++++-------------- ts/fixtures/reject/expected.txt | 61 ++++----- ts/fixtures/reject/src/lib.rs | 27 ++++ ts/fixtures/reject/ts.toml | 1 + ts/fixtures/stock/expected/buf.ts | 10 +- ts/fixtures/stock/src/buf.rs | 7 +- ts/runtime/rt/bytes.ts | 26 ---- ts/src/census.rs | 1 + ts/src/lower/stock.rs | 22 ++-- 10 files changed, 185 insertions(+), 171 deletions(-) diff --git a/ts/README.md b/ts/README.md index cb13e1f6e..12962d2bc 100644 --- a/ts/README.md +++ b/ts/README.md @@ -323,7 +323,9 @@ of them: - `Buf` and `BufMut` of a `Bytes`, a `BytesMut`, a `&[u8]`, and a `Vec` map: the required methods, `has_remaining`, `copy_to_slice`, `copy_to_bytes`, each `get_` and `put_` of an integer or `f64`, `put_slice`, `put_bytes`, and `put`, whose panics are - `bytes`'. `put` of the crate's own `Buf` reads it through its methods as `bytes` does. + `bytes`'. `put` of the crate's own `Buf` into a `Vec` reads it through its methods + as `bytes` does, and into a `BytesMut` is refused, as `bytes` picks those methods by its + capacity. The rest of `bytes`, such as the provided methods of the crate's own `Buf` and the impls forwarding through a `&mut` or a `Box`, translates from its MIR, refused where that is. - `rand::rng()` is an `rt.ThreadRng`, whose `random` of an integer or `bool` and diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 5ec0debd3..397a6e972 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 96 -- Function instances: 105 +- Refusals: 97 +- Function instances: 110 - Generic functions no instance reached, lowered over their type parameters: 7 ## By construct @@ -17,57 +17,58 @@ | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | fixtures/reject/src/lib.rs:16:15 | | 2 | `_` of `_`, whose `None` is `rt.None`, which is not supported yet | fixtures/reject/src/lib.rs:41:42 | | 2 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | fixtures/reject/src/lib.rs:247:16 | -| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | fixtures/reject/src/lib.rs:488:23 | -| 2 | a coercion to `_`, which is not supported yet | fixtures/reject/src/lib.rs:479:40 | +| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | fixtures/reject/src/lib.rs:515:23 | +| 2 | a coercion to `_`, which is not supported yet | fixtures/reject/src/lib.rs:506:40 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:159:1 | | 2 | constructing `_` from another crate | fixtures/reject/src/lib.rs:145:23 | | 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:139:2 | | 2 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | fixtures/reject/src/lib.rs:369:13 | +| 1 | `BufMut::put` of `_` into a `BytesMut`, which picks the methods it calls by a capacity that depends on whether the other handles of its storage dropped, which is not supported | fixtures/reject/src/lib.rs:440:2 | | 1 | `Bytes::from_owner` of `_`, which would drop with the last clone of what it makes, which is not supported | fixtures/reject/src/lib.rs:425:2 | | 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:68:2 | | 1 | `_` is not supported yet | fixtures/reject/src/lib.rs:393:18 | | 1 | `_` is not supported: its `Pending` and `Ready` would both be `rt.OuterPending` | fixtures/reject/src/lib.rs:105:20 | | 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `None` would be `rt.None` as `_` | fixtures/reject/src/lib.rs:31:2 | -| 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` | fixtures/reject/src/lib.rs:526:2 | +| 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` | fixtures/reject/src/lib.rs:553:2 | | 1 | `_` of `_` by `_`, which is not supported yet | fixtures/reject/src/lib.rs:286:6 | | 1 | `_` of `_`, which drops `_`, which is not supported yet | fixtures/reject/src/lib.rs:53:13 | -| 1 | `_` of `_`, which is not supported yet | fixtures/reject/src/lib.rs:569:4 | +| 1 | `_` of `_`, which is not supported yet | fixtures/reject/src/lib.rs:596:4 | | 1 | `_` through a held type's own, which is not supported yet | fixtures/reject/src/lib.rs:318:2 | -| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | fixtures/reject/src/lib.rs:545:12 | +| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | fixtures/reject/src/lib.rs:572:12 | | 1 | `_`, a trait object of another crate's trait, which is not supported yet | fixtures/reject/src/lib.rs:11:16 | | 1 | `_`, which is not supported yet | fixtures/reject/src/lib.rs:294:9 | | 1 | `_`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported | fixtures/reject/src/lib.rs:434:6 | -| 1 | `f64::mul_add`, which rounds once, where JS would round twice | fixtures/reject/src/lib.rs:458:4 | +| 1 | `f64::mul_add`, which rounds once, where JS would round twice | fixtures/reject/src/lib.rs:485:4 | | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | fixtures/reject/src/lib.rs:221:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | fixtures/reject/src/lib.rs:172:51 | | 1 | a cast from `_` to `_` | fixtures/reject/src/lib.rs:96:2 | -| 1 | a cast from a pointer to `_` to one to `_`, which reads the bytes of one type as another | fixtures/reject/src/lib.rs:586:27 | +| 1 | a cast from a pointer to `_` to one to `_`, which reads the bytes of one type as another | fixtures/reject/src/lib.rs:613:27 | | 1 | a coercion to `_` | fixtures/reject/src/lib.rs:341:2 | | 1 | a constant of type `_` | fixtures/reject/src/lib.rs:80:2 | -| 1 | a dangling pointer to `_`, a value of no bytes made of more than structs and tuples | fixtures/reject/src/lib.rs:671:11 | +| 1 | a dangling pointer to `_`, a value of no bytes made of more than structs and tuples | fixtures/reject/src/lib.rs:698:11 | | 1 | a future of `_`, which can be `rt.Pending`, as the future's own `Pending` is | fixtures/reject/src/lib.rs:110:34 | | 1 | a mutable borrow of a subslice of `_`, which JS would copy, having no views | fixtures/reject/src/lib.rs:226:13 | | 1 | a mutable reference into a `Result`'s payload, passed on or kept | fixtures/reject/src/lib.rs:413:12 | -| 1 | a pointer's address, which JS has no counterpart of | fixtures/reject/src/lib.rs:591:17 | +| 1 | a pointer's address, which JS has no counterpart of | fixtures/reject/src/lib.rs:618:17 | | 1 | a printable type must implement `Display` or `Debug` | fixtures/reject/src/lib.rs:92:1 | -| 1 | a raw pointer to `_` behind a reference, which is the object and not where it is kept | fixtures/reject/src/lib.rs:608:10 | -| 1 | a raw pointer to `_` in `_`, which the crate may put another object in place of | fixtures/reject/src/lib.rs:639:10 | -| 1 | a raw pointer to `_` in a variable assigned again while it may point there | fixtures/reject/src/lib.rs:647:10 | -| 1 | a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet | fixtures/reject/src/lib.rs:655:10 | +| 1 | a raw pointer to `_` behind a reference, which is the object and not where it is kept | fixtures/reject/src/lib.rs:635:10 | +| 1 | a raw pointer to `_` in `_`, which the crate may put another object in place of | fixtures/reject/src/lib.rs:666:10 | +| 1 | a raw pointer to `_` in a variable assigned again while it may point there | fixtures/reject/src/lib.rs:674:10 | +| 1 | a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet | fixtures/reject/src/lib.rs:682:10 | | 1 | a scalar constant of type `_` | fixtures/reject/src/lib.rs:8:2 | -| 1 | a trait object of `_`, which is not supported yet | fixtures/reject/src/lib.rs:505:26 | +| 1 | a trait object of `_`, which is not supported yet | fixtures/reject/src/lib.rs:532:26 | | 1 | a zero-sized constant of type `_` | fixtures/reject/src/lib.rs:62:2 | -| 1 | an upcast from `_` to `_`, which is not supported yet | fixtures/reject/src/lib.rs:563:32 | +| 1 | an upcast from `_` to `_`, which is not supported yet | fixtures/reject/src/lib.rs:590:32 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:8:2 | | 1 | collecting `_`, whose `None` is `rt.None`, which is not supported yet | fixtures/reject/src/lib.rs:36:43 | | 1 | comparing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:268:52 | -| 1 | comparing pointers to `()`, which has no bytes and so no address of its own | fixtures/reject/src/lib.rs:662:2 | -| 1 | comparing pointers to `_`, each a place JS makes of its own | fixtures/reject/src/lib.rs:627:2 | +| 1 | comparing pointers to `()`, which has no bytes and so no address of its own | fixtures/reject/src/lib.rs:689:2 | +| 1 | comparing pointers to `_`, each a place JS makes of its own | fixtures/reject/src/lib.rs:654:2 | | 1 | constructing `_` | fixtures/reject/src/lib.rs:400:53 | | 1 | hashing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:268:52 | | 1 | hashing `_` through `_`'s own `Hash::hash_slice`, which is not supported yet | fixtures/reject/src/lib.rs:360:16 | | 1 | passing `_`, which drops, to `_`, which is not supported yet | fixtures/reject/src/lib.rs:377:4 | -| 1 | union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart | fixtures/reject/src/lib.rs:613:1 | +| 1 | union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart | fixtures/reject/src/lib.rs:640:1 | ## By API @@ -83,25 +84,26 @@ The type or module each refused type or path belongs to. | 4 | `std::vec::Vec` | fixtures/reject/src/lib.rs:268:52 | | 4 | `u32` | fixtures/reject/src/lib.rs:226:13 | | 4 | `u8` | fixtures/reject/src/lib.rs:80:2 | -| 3 | `(u32, u32)` | fixtures/reject/src/lib.rs:639:10 | +| 3 | `(u32, u32)` | fixtures/reject/src/lib.rs:666:10 | | 3 | `{closure}` | fixtures/reject/src/lib.rs:369:13 | | 2 | `Meters` | fixtures/reject/src/lib.rs:85:2 | | 2 | `Poll` | fixtures/reject/src/lib.rs:105:20 | -| 2 | `Scaled` | fixtures/reject/src/lib.rs:488:23 | -| 2 | `dyn Scaled` | fixtures/reject/src/lib.rs:488:23 | -| 2 | `dyn std::any::Any` | fixtures/reject/src/lib.rs:563:32 | -| 2 | `std::any::TypeId` | fixtures/reject/src/lib.rs:569:2 | +| 2 | `Scaled` | fixtures/reject/src/lib.rs:515:23 | +| 2 | `dyn Scaled` | fixtures/reject/src/lib.rs:515:23 | +| 2 | `dyn std::any::Any` | fixtures/reject/src/lib.rs:590:32 | +| 2 | `std::any::TypeId` | fixtures/reject/src/lib.rs:596:2 | | 2 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:53:13 | | 2 | `std::iter::Iterator` | fixtures/reject/src/lib.rs:247:16 | | 2 | `std::iter::Map` | fixtures/reject/src/lib.rs:145:23 | | 2 | `std::ops::Range` | fixtures/reject/src/lib.rs:180:8 | | 2 | `std::pin::Pin` | fixtures/reject/src/lib.rs:116:2 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:21:4 | -| 2 | `std::std` | fixtures/reject/src/lib.rs:598:11 | -| 2 | `std::vec::IntoIter` | fixtures/reject/src/lib.rs:453:17 | +| 2 | `std::std` | fixtures/reject/src/lib.rs:625:11 | +| 2 | `std::vec::IntoIter` | fixtures/reject/src/lib.rs:480:17 | | 1 | `Batched` | fixtures/reject/src/lib.rs:360:16 | -| 1 | `Bits` | fixtures/reject/src/lib.rs:613:1 | +| 1 | `Bits` | fixtures/reject/src/lib.rs:640:1 | | 1 | `BytesMut` | fixtures/reject/src/lib.rs:434:6 | +| 1 | `Counted` | fixtures/reject/src/lib.rs:440:2 | | 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:159:1 | | 1 | `Entry` | fixtures/reject/src/lib.rs:369:13 | | 1 | `FusedIterator` | fixtures/reject/src/lib.rs:213:1 | @@ -110,29 +112,29 @@ The type or module each refused type or path belongs to. | 1 | `Hasher` | fixtures/reject/src/lib.rs:294:9 | | 1 | `Maybe` | fixtures/reject/src/lib.rs:31:2 | | 1 | `Noisy` | fixtures/reject/src/lib.rs:53:13 | -| 1 | `Only` | fixtures/reject/src/lib.rs:671:11 | -| 1 | `Span2` | fixtures/reject/src/lib.rs:639:10 | +| 1 | `Only` | fixtures/reject/src/lib.rs:698:11 | +| 1 | `Span2` | fixtures/reject/src/lib.rs:666:10 | | 1 | `T \| undefined` | fixtures/reject/src/lib.rs:31:2 | -| 1 | `Tail` | fixtures/reject/src/lib.rs:515:30 | -| 1 | `Waiting` | fixtures/reject/src/lib.rs:526:2 | +| 1 | `Tail` | fixtures/reject/src/lib.rs:542:30 | +| 1 | `Waiting` | fixtures/reject/src/lib.rs:553:2 | | 1 | `[u16; 1]` | fixtures/reject/src/lib.rs:240:22 | -| 1 | `[u8; 4]` | fixtures/reject/src/lib.rs:505:26 | -| 1 | `dyn Keyed` | fixtures/reject/src/lib.rs:563:32 | +| 1 | `[u8; 4]` | fixtures/reject/src/lib.rs:532:26 | +| 1 | `dyn Keyed` | fixtures/reject/src/lib.rs:590:32 | | 1 | `dyn std::iter::Iterator` | fixtures/reject/src/lib.rs:11:16 | -| 1 | `f64` | fixtures/reject/src/lib.rs:463:2 | +| 1 | `f64` | fixtures/reject/src/lib.rs:490:2 | | 1 | `into_keys` | fixtures/reject/src/lib.rs:53:13 | -| 1 | `poll` | fixtures/reject/src/lib.rs:526:2 | -| 1 | `rt.Poll` | fixtures/reject/src/lib.rs:526:2 | -| 1 | `std::any::Any` | fixtures/reject/src/lib.rs:569:4 | +| 1 | `poll` | fixtures/reject/src/lib.rs:553:2 | +| 1 | `rt.Poll` | fixtures/reject/src/lib.rs:553:2 | +| 1 | `std::any::Any` | fixtures/reject/src/lib.rs:596:4 | | 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:172:51 | | 1 | `std::iter::Rev` | fixtures/reject/src/lib.rs:166:14 | | 1 | `std::option::Option` | fixtures/reject/src/lib.rs:420:2 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:126:11 | -| 1 | `std::std::Layout` | fixtures/reject/src/lib.rs:596:15 | +| 1 | `std::std::Layout` | fixtures/reject/src/lib.rs:623:15 | | 1 | `std::string::String` | fixtures/reject/src/lib.rs:74:10 | | 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:121:2 | -| 1 | `std::sync::Mutex` | fixtures/reject/src/lib.rs:545:12 | -| 1 | `std::sync::Weak` | fixtures/reject/src/lib.rs:479:40 | +| 1 | `std::sync::Mutex` | fixtures/reject/src/lib.rs:572:12 | +| 1 | `std::sync::Weak` | fixtures/reject/src/lib.rs:506:40 | | 1 | `std::task::Poll` | fixtures/reject/src/lib.rs:110:34 | | 1 | `str` | fixtures/reject/src/lib.rs:377:4 | | 1 | `u64` | fixtures/reject/src/lib.rs:96:2 | @@ -146,54 +148,55 @@ The type or module each refused type or path belongs to. | 4 | a variant of `_`, which is not supported: either is the same JS string | `std::borrow::Cow` | fixtures/reject/src/lib.rs:382:2 | | 3 | unsupported type `_` | `f32` | fixtures/reject/src/lib.rs:7:14 | | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | `Option` | fixtures/reject/src/lib.rs:16:15 | -| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | `dyn Scaled`, `Scaled` | fixtures/reject/src/lib.rs:488:23 | +| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | `dyn Scaled`, `Scaled` | fixtures/reject/src/lib.rs:515:23 | | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:116:2 | | 2 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:85:2 | -| 2 | unsupported call to `_` | `::sum` | fixtures/reject/src/lib.rs:453:17 | +| 2 | unsupported call to `_` | `::sum` | fixtures/reject/src/lib.rs:480:17 | +| 1 | `BufMut::put` of `_` into a `BytesMut`, which picks the methods it calls by a capacity that depends on whether the other handles of its storage dropped, which is not supported | `Counted` | fixtures/reject/src/lib.rs:440:2 | | 1 | `Bytes::from_owner` of `_`, which would drop with the last clone of what it makes, which is not supported | `std::sync::Arc` | fixtures/reject/src/lib.rs:425:2 | | 1 | `_` is not supported yet | `std::borrow::Cow` | fixtures/reject/src/lib.rs:393:18 | | 1 | `_` is not supported: its `Pending` and `Ready` would both be `rt.OuterPending` | `Poll` | fixtures/reject/src/lib.rs:105:20 | | 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `None` would be `rt.None` as `_` | `Maybe`, `value`, `Option`, `T \| undefined`, `Option` | fixtures/reject/src/lib.rs:31:2 | -| 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` | `Waiting`, `poll`, `Poll`, `rt.Poll`, `Poll` | fixtures/reject/src/lib.rs:526:2 | +| 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` | `Waiting`, `poll`, `Poll`, `rt.Poll`, `Poll` | fixtures/reject/src/lib.rs:553:2 | | 1 | `_` of `_` by `_`, which is not supported yet | `HashMap::contains_key`, `std::collections::HashMap`, `u8` | fixtures/reject/src/lib.rs:286:6 | | 1 | `_` of `_`, which drops `_`, which is not supported yet | `into_keys`, `std::collections::HashMap`, `Noisy` | fixtures/reject/src/lib.rs:53:13 | -| 1 | `_` of `_`, which is not supported yet | `std::any::Any::type_id`, `dyn std::any::Any` | fixtures/reject/src/lib.rs:569:4 | +| 1 | `_` of `_`, which is not supported yet | `std::any::Any::type_id`, `dyn std::any::Any` | fixtures/reject/src/lib.rs:596:4 | | 1 | `_` of `_`, whose `None` is `rt.None`, which is not supported yet | `HashSet::get`, `Option` | fixtures/reject/src/lib.rs:263:6 | | 1 | `_` of `_`, whose `None` is `rt.None`, which is not supported yet | `Iterator::find`, `Option` | fixtures/reject/src/lib.rs:41:42 | | 1 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | `std::iter::Iterator::count` | fixtures/reject/src/lib.rs:247:38 | | 1 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | `std::iter::Iterator::filter` | fixtures/reject/src/lib.rs:247:16 | | 1 | `_` through a held type's own, which is not supported yet | `::ne` | fixtures/reject/src/lib.rs:318:2 | -| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::sync::Mutex::get_mut` | fixtures/reject/src/lib.rs:545:12 | +| 1 | `_` with a mutable reference to a value JS copies, which its mapping would copy | `std::sync::Mutex::get_mut` | fixtures/reject/src/lib.rs:572:12 | | 1 | `_`, a trait object of another crate's trait, which is not supported yet | `dyn std::iter::Iterator` | fixtures/reject/src/lib.rs:11:16 | | 1 | `_`, which is not supported yet | `Hasher::write` | fixtures/reject/src/lib.rs:294:9 | | 1 | `_`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported | `BytesMut::capacity` | fixtures/reject/src/lib.rs:434:6 | | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | `std::iter::Map`, `std::ops::Range` | fixtures/reject/src/lib.rs:221:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | `std::iter::Chain` | fixtures/reject/src/lib.rs:172:51 | | 1 | a cast from `_` to `_` | `u64`, `f32` | fixtures/reject/src/lib.rs:96:2 | -| 1 | a cast from a pointer to `_` to one to `_`, which reads the bytes of one type as another | `u32`, `u8` | fixtures/reject/src/lib.rs:586:27 | +| 1 | a cast from a pointer to `_` to one to `_`, which reads the bytes of one type as another | `u32`, `u8` | fixtures/reject/src/lib.rs:613:27 | | 1 | a coercion to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:341:2 | -| 1 | a coercion to `_`, which is not supported yet | `&Tail` | fixtures/reject/src/lib.rs:515:30 | -| 1 | a coercion to `_`, which is not supported yet | `std::sync::Weak` | fixtures/reject/src/lib.rs:479:40 | +| 1 | a coercion to `_`, which is not supported yet | `&Tail` | fixtures/reject/src/lib.rs:542:30 | +| 1 | a coercion to `_`, which is not supported yet | `std::sync::Weak` | fixtures/reject/src/lib.rs:506:40 | | 1 | a constant of type `_` | `&u8` | fixtures/reject/src/lib.rs:80:2 | -| 1 | a dangling pointer to `_`, a value of no bytes made of more than structs and tuples | `Only` | fixtures/reject/src/lib.rs:671:11 | +| 1 | a dangling pointer to `_`, a value of no bytes made of more than structs and tuples | `Only` | fixtures/reject/src/lib.rs:698:11 | | 1 | a future of `_`, which can be `rt.Pending`, as the future's own `Pending` is | `std::task::Poll` | fixtures/reject/src/lib.rs:110:34 | | 1 | a mutable borrow of a subslice of `_`, which JS would copy, having no views | `u32` | fixtures/reject/src/lib.rs:226:13 | -| 1 | a raw pointer to `_` behind a reference, which is the object and not where it is kept | `std::vec::Vec` | fixtures/reject/src/lib.rs:608:10 | -| 1 | a raw pointer to `_` in `_`, which the crate may put another object in place of | `(u32, u32)`, `Span2` | fixtures/reject/src/lib.rs:639:10 | -| 1 | a raw pointer to `_` in a variable assigned again while it may point there | `(u32, u32)` | fixtures/reject/src/lib.rs:647:10 | -| 1 | a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet | `(u32, u32)` | fixtures/reject/src/lib.rs:655:10 | +| 1 | a raw pointer to `_` behind a reference, which is the object and not where it is kept | `std::vec::Vec` | fixtures/reject/src/lib.rs:635:10 | +| 1 | a raw pointer to `_` in `_`, which the crate may put another object in place of | `(u32, u32)`, `Span2` | fixtures/reject/src/lib.rs:666:10 | +| 1 | a raw pointer to `_` in a variable assigned again while it may point there | `(u32, u32)` | fixtures/reject/src/lib.rs:674:10 | +| 1 | a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet | `(u32, u32)` | fixtures/reject/src/lib.rs:682:10 | | 1 | a scalar constant of type `_` | `f32` | fixtures/reject/src/lib.rs:8:2 | -| 1 | a trait object of `_`, which is not supported yet | `[u8; 4]` | fixtures/reject/src/lib.rs:505:26 | +| 1 | a trait object of `_`, which is not supported yet | `[u8; 4]` | fixtures/reject/src/lib.rs:532:26 | | 1 | a zero-sized constant of type `_` | `{async closure}` | fixtures/reject/src/lib.rs:62:2 | | 1 | an assignment through a reference to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:101:2 | | 1 | an assignment through a reference to `_` | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:121:2 | | 1 | an iterator of the crate implementing `_`, which is not supported yet | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:159:1 | | 1 | an iterator of the crate implementing `_`, which is not supported yet | `FusedIterator` | fixtures/reject/src/lib.rs:213:1 | -| 1 | an upcast from `_` to `_`, which is not supported yet | `dyn Keyed`, `dyn std::any::Any` | fixtures/reject/src/lib.rs:563:32 | +| 1 | an upcast from `_` to `_`, which is not supported yet | `dyn Keyed`, `dyn std::any::Any` | fixtures/reject/src/lib.rs:590:32 | | 1 | arithmetic on `_` | `f32` | fixtures/reject/src/lib.rs:8:2 | | 1 | collecting `_`, whose `None` is `rt.None`, which is not supported yet | `Option` | fixtures/reject/src/lib.rs:36:43 | | 1 | comparing `_` as a key, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:268:52 | -| 1 | comparing pointers to `_`, each a place JS makes of its own | `u32` | fixtures/reject/src/lib.rs:627:2 | +| 1 | comparing pointers to `_`, each a place JS makes of its own | `u32` | fixtures/reject/src/lib.rs:654:2 | | 1 | constructing `_` | `std::borrow::Cow` | fixtures/reject/src/lib.rs:400:53 | | 1 | constructing `_` from another crate | `std::iter::Map` | fixtures/reject/src/lib.rs:145:23 | | 1 | constructing `_` from another crate | `std::iter::Rev` | fixtures/reject/src/lib.rs:166:14 | @@ -205,21 +208,21 @@ The type or module each refused type or path belongs to. | 1 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | `{closure}`, `Iterator::for_each` | fixtures/reject/src/lib.rs:370:16 | | 1 | passing `_`, which drops, to `_`, which is not supported yet | `{closure}`, `str::contains` | fixtures/reject/src/lib.rs:377:4 | | 1 | replacing the value behind a reference to `_` | `[u16; 1]` | fixtures/reject/src/lib.rs:240:22 | -| 1 | union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart | `Bits`, `u32` | fixtures/reject/src/lib.rs:613:1 | -| 1 | unsupported call to `_` | `::fmt` | fixtures/reject/src/lib.rs:463:2 | -| 1 | unsupported call to `_` | `::eq` | fixtures/reject/src/lib.rs:569:2 | +| 1 | union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart | `Bits`, `u32` | fixtures/reject/src/lib.rs:640:1 | +| 1 | unsupported call to `_` | `::fmt` | fixtures/reject/src/lib.rs:490:2 | +| 1 | unsupported call to `_` | `::eq` | fixtures/reject/src/lib.rs:596:2 | | 1 | unsupported call to `_` | `::deref` | fixtures/reject/src/lib.rs:394:2 | | 1 | unsupported call to `_` | `::eq` | fixtures/reject/src/lib.rs:420:2 | | 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:126:11 | | 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:74:10 | | 1 | unsupported call to `_` | `::hash` | fixtures/reject/src/lib.rs:351:10 | -| 1 | unsupported call to `_` | `std::any::TypeId::of` | fixtures/reject/src/lib.rs:569:17 | +| 1 | unsupported call to `_` | `std::any::TypeId::of` | fixtures/reject/src/lib.rs:596:17 | | 1 | unsupported call to `_` | `std::ops::Range::contains` | fixtures/reject/src/lib.rs:180:8 | | 1 | unsupported call to `_` | `std::slice::copy_within` | fixtures/reject/src/lib.rs:336:4 | | 1 | unsupported call to `_` | `std::slice::rotate_left` | fixtures/reject/src/lib.rs:21:4 | -| 1 | unsupported call to `_` | `std::std::Layout::new` | fixtures/reject/src/lib.rs:596:15 | -| 1 | unsupported call to `_` | `std::std::alloc` | fixtures/reject/src/lib.rs:598:11 | -| 1 | unsupported call to `_` | `std::std::dealloc` | fixtures/reject/src/lib.rs:601:3 | +| 1 | unsupported call to `_` | `std::std::Layout::new` | fixtures/reject/src/lib.rs:623:15 | +| 1 | unsupported call to `_` | `std::std::alloc` | fixtures/reject/src/lib.rs:625:11 | +| 1 | unsupported call to `_` | `std::std::dealloc` | fixtures/reject/src/lib.rs:628:3 | ## Spans @@ -233,14 +236,14 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:351:10: unsupported call to `::hash::` - fixtures/reject/src/lib.rs:394:2: unsupported call to ` as std::ops::Deref>::deref` - fixtures/reject/src/lib.rs:420:2: unsupported call to ` as std::cmp::PartialEq>::eq` -- fixtures/reject/src/lib.rs:453:17: unsupported call to ` as std::iter::Iterator>::sum::` -- fixtures/reject/src/lib.rs:453:38: unsupported call to ` as std::iter::Iterator>::sum::` -- fixtures/reject/src/lib.rs:463:2: unsupported call to `::fmt` -- fixtures/reject/src/lib.rs:569:2: unsupported call to `::eq` -- fixtures/reject/src/lib.rs:569:17: unsupported call to `std::any::TypeId::of::` -- fixtures/reject/src/lib.rs:596:15: unsupported call to `std::alloc::Layout::new::` -- fixtures/reject/src/lib.rs:598:11: unsupported call to `std::alloc::alloc` -- fixtures/reject/src/lib.rs:601:3: unsupported call to `std::alloc::dealloc` +- fixtures/reject/src/lib.rs:480:17: unsupported call to ` as std::iter::Iterator>::sum::` +- fixtures/reject/src/lib.rs:480:38: unsupported call to ` as std::iter::Iterator>::sum::` +- fixtures/reject/src/lib.rs:490:2: unsupported call to `::fmt` +- fixtures/reject/src/lib.rs:596:2: unsupported call to `::eq` +- fixtures/reject/src/lib.rs:596:17: unsupported call to `std::any::TypeId::of::` +- fixtures/reject/src/lib.rs:623:15: unsupported call to `std::alloc::Layout::new::` +- fixtures/reject/src/lib.rs:625:11: unsupported call to `std::alloc::alloc` +- fixtures/reject/src/lib.rs:628:3: unsupported call to `std::alloc::dealloc` @@ -265,8 +268,8 @@ The type or module each refused type or path belongs to.
a copy of a closure that changes what it captured (3) - fixtures/reject/src/lib.rs:257:14: a copy of a closure that changes what it captured -- fixtures/reject/src/lib.rs:538:14: a copy of a closure that changes what it captured -- fixtures/reject/src/lib.rs:539:14: a copy of a closure that changes what it captured +- fixtures/reject/src/lib.rs:565:14: a copy of a closure that changes what it captured +- fixtures/reject/src/lib.rs:566:14: a copy of a closure that changes what it captured
@@ -309,15 +312,15 @@ The type or module each refused type or path belongs to.
`_`, a trait object of the generic trait `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:488:23: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet -- fixtures/reject/src/lib.rs:489:4: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet +- fixtures/reject/src/lib.rs:515:23: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet +- fixtures/reject/src/lib.rs:516:4: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet
a coercion to `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:479:40: a coercion to `std::sync::Weak`, which is not supported yet -- fixtures/reject/src/lib.rs:515:30: a coercion to `&Tail`, which is not supported yet +- fixtures/reject/src/lib.rs:506:40: a coercion to `std::sync::Weak`, which is not supported yet +- fixtures/reject/src/lib.rs:542:30: a coercion to `&Tail`, which is not supported yet
@@ -349,6 +352,12 @@ The type or module each refused type or path belongs to. +
`BufMut::put` of `_` into a `BytesMut`, which picks the methods it calls by a capacity that depends on whether the other handles of its storage dropped, which is not supported (1) + +- fixtures/reject/src/lib.rs:440:2: `BufMut::put` of `Counted` into a `BytesMut`, which picks the methods it calls by a capacity that depends on whether the other handles of its storage dropped, which is not supported + +
+
`Bytes::from_owner` of `_`, which would drop with the last clone of what it makes, which is not supported (1) - fixtures/reject/src/lib.rs:425:2: `Bytes::from_owner` of `std::sync::Arc<[u8]>`, which would drop with the last clone of what it makes, which is not supported @@ -381,7 +390,7 @@ The type or module each refused type or path belongs to.
`_` is not supported: its field `_` is `_`, typed `_`, whose `Pending` would be `rt.OuterPending` as `_` (1) -- fixtures/reject/src/lib.rs:526:2: `Waiting>` is not supported: its field `poll` is `Poll`, typed `rt.Poll`, whose `Pending` would be `rt.OuterPending` as `Poll>` +- fixtures/reject/src/lib.rs:553:2: `Waiting>` is not supported: its field `poll` is `Poll`, typed `rt.Poll`, whose `Pending` would be `rt.OuterPending` as `Poll>`
@@ -399,7 +408,7 @@ The type or module each refused type or path belongs to.
`_` of `_`, which is not supported yet (1) -- fixtures/reject/src/lib.rs:569:4: `std::any::Any::type_id` of `dyn std::any::Any`, which is not supported yet +- fixtures/reject/src/lib.rs:596:4: `std::any::Any::type_id` of `dyn std::any::Any`, which is not supported yet
@@ -411,7 +420,7 @@ The type or module each refused type or path belongs to.
`_` with a mutable reference to a value JS copies, which its mapping would copy (1) -- fixtures/reject/src/lib.rs:545:12: `std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy +- fixtures/reject/src/lib.rs:572:12: `std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy
@@ -435,7 +444,7 @@ The type or module each refused type or path belongs to.
`f64::mul_add`, which rounds once, where JS would round twice (1) -- fixtures/reject/src/lib.rs:458:4: `f64::mul_add`, which rounds once, where JS would round twice +- fixtures/reject/src/lib.rs:485:4: `f64::mul_add`, which rounds once, where JS would round twice
@@ -459,7 +468,7 @@ The type or module each refused type or path belongs to.
a cast from a pointer to `_` to one to `_`, which reads the bytes of one type as another (1) -- fixtures/reject/src/lib.rs:586:27: a cast from a pointer to `u32` to one to `u8`, which reads the bytes of one type as another +- fixtures/reject/src/lib.rs:613:27: a cast from a pointer to `u32` to one to `u8`, which reads the bytes of one type as another
@@ -477,7 +486,7 @@ The type or module each refused type or path belongs to.
a dangling pointer to `_`, a value of no bytes made of more than structs and tuples (1) -- fixtures/reject/src/lib.rs:671:11: a dangling pointer to `Only`, a value of no bytes made of more than structs and tuples +- fixtures/reject/src/lib.rs:698:11: a dangling pointer to `Only`, a value of no bytes made of more than structs and tuples
@@ -501,7 +510,7 @@ The type or module each refused type or path belongs to.
a pointer's address, which JS has no counterpart of (1) -- fixtures/reject/src/lib.rs:591:17: a pointer's address, which JS has no counterpart of +- fixtures/reject/src/lib.rs:618:17: a pointer's address, which JS has no counterpart of
@@ -513,25 +522,25 @@ The type or module each refused type or path belongs to.
a raw pointer to `_` behind a reference, which is the object and not where it is kept (1) -- fixtures/reject/src/lib.rs:608:10: a raw pointer to `std::vec::Vec` behind a reference, which is the object and not where it is kept +- fixtures/reject/src/lib.rs:635:10: a raw pointer to `std::vec::Vec` behind a reference, which is the object and not where it is kept
a raw pointer to `_` in `_`, which the crate may put another object in place of (1) -- fixtures/reject/src/lib.rs:639:10: a raw pointer to `(u32, u32)` in `Span2`, which the crate may put another object in place of +- fixtures/reject/src/lib.rs:666:10: a raw pointer to `(u32, u32)` in `Span2`, which the crate may put another object in place of
a raw pointer to `_` in a variable assigned again while it may point there (1) -- fixtures/reject/src/lib.rs:647:10: a raw pointer to `(u32, u32)` in a variable assigned again while it may point there +- fixtures/reject/src/lib.rs:674:10: a raw pointer to `(u32, u32)` in a variable assigned again while it may point there
a raw pointer to `_` in an element, a payload, or a union field, which is not supported yet (1) -- fixtures/reject/src/lib.rs:655:10: a raw pointer to `(u32, u32)` in an element, a payload, or a union field, which is not supported yet +- fixtures/reject/src/lib.rs:682:10: a raw pointer to `(u32, u32)` in an element, a payload, or a union field, which is not supported yet
@@ -543,7 +552,7 @@ The type or module each refused type or path belongs to.
a trait object of `_`, which is not supported yet (1) -- fixtures/reject/src/lib.rs:505:26: a trait object of `[u8; 4]`, which is not supported yet +- fixtures/reject/src/lib.rs:532:26: a trait object of `[u8; 4]`, which is not supported yet
@@ -555,7 +564,7 @@ The type or module each refused type or path belongs to.
an upcast from `_` to `_`, which is not supported yet (1) -- fixtures/reject/src/lib.rs:563:32: an upcast from `dyn Keyed` to `dyn std::any::Any`, which is not supported yet +- fixtures/reject/src/lib.rs:590:32: an upcast from `dyn Keyed` to `dyn std::any::Any`, which is not supported yet
@@ -579,13 +588,13 @@ The type or module each refused type or path belongs to.
comparing pointers to `()`, which has no bytes and so no address of its own (1) -- fixtures/reject/src/lib.rs:662:2: comparing pointers to `()`, which has no bytes and so no address of its own +- fixtures/reject/src/lib.rs:689:2: comparing pointers to `()`, which has no bytes and so no address of its own
comparing pointers to `_`, each a place JS makes of its own (1) -- fixtures/reject/src/lib.rs:627:2: comparing pointers to `u32`, each a place JS makes of its own +- fixtures/reject/src/lib.rs:654:2: comparing pointers to `u32`, each a place JS makes of its own
@@ -615,6 +624,6 @@ The type or module each refused type or path belongs to.
union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart (1) -- fixtures/reject/src/lib.rs:613:1: union `Bits`, whose fields overlap in `u32` and `f64`, which JS keeps apart +- fixtures/reject/src/lib.rs:640:1: union `Bits`, whose fields overlap in `u32` and `f64`, which JS keeps apart
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index bc8254702..cbc26b2ea 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -54,40 +54,41 @@ hashing `std::vec::Vec` through `Batched`'s own `Hash::hash_slice`, whi passing `{closure@fixtures/reject/src/lib.rs:369:28: 369:35}`, a closure that owns a value that drops, to `Entry::or_insert_with`, which is not supported yet at fixtures/reject/src/lib.rs:369:13 passing `{closure@fixtures/reject/src/lib.rs:370:25: 370:33}`, a closure that owns a value that drops, to `Iterator::for_each`, which is not supported yet at fixtures/reject/src/lib.rs:370:16 passing `{closure@fixtures/reject/src/lib.rs:377:13: 377:27}`, which drops, to `str::contains`, which is not supported yet at fixtures/reject/src/lib.rs:377:4 -unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:453:17 -unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:453:38 +unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:480:17 +unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:480:38 a mutable reference into a `Result`'s payload, passed on or kept at fixtures/reject/src/lib.rs:413:12 unsupported call to ` as std::cmp::PartialEq>::eq` at fixtures/reject/src/lib.rs:420:2 `Bytes::from_owner` of `std::sync::Arc<[u8]>`, which would drop with the last clone of what it makes, which is not supported at fixtures/reject/src/lib.rs:425:2 `BytesMut::capacity`, which reads a capacity that depends on whether the other handles of its storage dropped, which is not supported at fixtures/reject/src/lib.rs:434:6 -`f64::mul_add`, which rounds once, where JS would round twice at fixtures/reject/src/lib.rs:458:4 -unsupported call to `::fmt` at fixtures/reject/src/lib.rs:463:11 -a coercion to `std::sync::Weak`, which is not supported yet at fixtures/reject/src/lib.rs:479:40 -`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:488:23 -`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:489:4 -a trait object of `[u8; 4]`, which is not supported yet at fixtures/reject/src/lib.rs:505:26 -a coercion to `&Tail`, which is not supported yet at fixtures/reject/src/lib.rs:515:30 -`std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:545:12 -`Waiting>` is not supported: its field `poll` is `Poll`, typed `rt.Poll`, whose `Pending` would be `rt.OuterPending` as `Poll>` at fixtures/reject/src/lib.rs:526:2 -a copy of a closure that changes what it captured at fixtures/reject/src/lib.rs:538:14 -a copy of a closure that changes what it captured at fixtures/reject/src/lib.rs:539:14 -an upcast from `dyn Keyed` to `dyn std::any::Any`, which is not supported yet at fixtures/reject/src/lib.rs:563:32 -`std::any::Any::type_id` of `dyn std::any::Any`, which is not supported yet at fixtures/reject/src/lib.rs:569:4 -unsupported call to `std::any::TypeId::of::` at fixtures/reject/src/lib.rs:569:17 -unsupported call to `::eq` at fixtures/reject/src/lib.rs:569:2 -a cast from a pointer to `u32` to one to `u8`, which reads the bytes of one type as another at fixtures/reject/src/lib.rs:586:27 -a pointer's address, which JS has no counterpart of at fixtures/reject/src/lib.rs:591:17 -unsupported call to `std::alloc::Layout::new::` at fixtures/reject/src/lib.rs:596:15 -unsupported call to `std::alloc::alloc` at fixtures/reject/src/lib.rs:598:11 -unsupported call to `std::alloc::dealloc` at fixtures/reject/src/lib.rs:601:3 -a raw pointer to `std::vec::Vec` behind a reference, which is the object and not where it is kept at fixtures/reject/src/lib.rs:608:10 -union `Bits`, whose fields overlap in `u32` and `f64`, which JS keeps apart at fixtures/reject/src/lib.rs:619:10 -comparing pointers to `u32`, each a place JS makes of its own at fixtures/reject/src/lib.rs:627:2 -a raw pointer to `(u32, u32)` in `Span2`, which the crate may put another object in place of at fixtures/reject/src/lib.rs:639:10 -a raw pointer to `(u32, u32)` in a variable assigned again while it may point there at fixtures/reject/src/lib.rs:647:10 -a raw pointer to `(u32, u32)` in an element, a payload, or a union field, which is not supported yet at fixtures/reject/src/lib.rs:655:10 -comparing pointers to `()`, which has no bytes and so no address of its own at fixtures/reject/src/lib.rs:662:2 -a dangling pointer to `Only`, a value of no bytes made of more than structs and tuples at fixtures/reject/src/lib.rs:671:11 +`BufMut::put` of `Counted` into a `BytesMut`, which picks the methods it calls by a capacity that depends on whether the other handles of its storage dropped, which is not supported at fixtures/reject/src/lib.rs:440:2 +`f64::mul_add`, which rounds once, where JS would round twice at fixtures/reject/src/lib.rs:485:4 +unsupported call to `::fmt` at fixtures/reject/src/lib.rs:490:11 +a coercion to `std::sync::Weak`, which is not supported yet at fixtures/reject/src/lib.rs:506:40 +`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:515:23 +`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:516:4 +a trait object of `[u8; 4]`, which is not supported yet at fixtures/reject/src/lib.rs:532:26 +a coercion to `&Tail`, which is not supported yet at fixtures/reject/src/lib.rs:542:30 +`std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy at fixtures/reject/src/lib.rs:572:12 +`Waiting>` is not supported: its field `poll` is `Poll`, typed `rt.Poll`, whose `Pending` would be `rt.OuterPending` as `Poll>` at fixtures/reject/src/lib.rs:553:2 +a copy of a closure that changes what it captured at fixtures/reject/src/lib.rs:565:14 +a copy of a closure that changes what it captured at fixtures/reject/src/lib.rs:566:14 +an upcast from `dyn Keyed` to `dyn std::any::Any`, which is not supported yet at fixtures/reject/src/lib.rs:590:32 +`std::any::Any::type_id` of `dyn std::any::Any`, which is not supported yet at fixtures/reject/src/lib.rs:596:4 +unsupported call to `std::any::TypeId::of::` at fixtures/reject/src/lib.rs:596:17 +unsupported call to `::eq` at fixtures/reject/src/lib.rs:596:2 +a cast from a pointer to `u32` to one to `u8`, which reads the bytes of one type as another at fixtures/reject/src/lib.rs:613:27 +a pointer's address, which JS has no counterpart of at fixtures/reject/src/lib.rs:618:17 +unsupported call to `std::alloc::Layout::new::` at fixtures/reject/src/lib.rs:623:15 +unsupported call to `std::alloc::alloc` at fixtures/reject/src/lib.rs:625:11 +unsupported call to `std::alloc::dealloc` at fixtures/reject/src/lib.rs:628:3 +a raw pointer to `std::vec::Vec` behind a reference, which is the object and not where it is kept at fixtures/reject/src/lib.rs:635:10 +union `Bits`, whose fields overlap in `u32` and `f64`, which JS keeps apart at fixtures/reject/src/lib.rs:646:10 +comparing pointers to `u32`, each a place JS makes of its own at fixtures/reject/src/lib.rs:654:2 +a raw pointer to `(u32, u32)` in `Span2`, which the crate may put another object in place of at fixtures/reject/src/lib.rs:666:10 +a raw pointer to `(u32, u32)` in a variable assigned again while it may point there at fixtures/reject/src/lib.rs:674:10 +a raw pointer to `(u32, u32)` in an element, a payload, or a union field, which is not supported yet at fixtures/reject/src/lib.rs:682:10 +comparing pointers to `()`, which has no bytes and so no address of its own at fixtures/reject/src/lib.rs:689:2 +a dangling pointer to `Only`, a value of no bytes made of more than structs and tuples at fixtures/reject/src/lib.rs:698:11 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:139:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:159:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:193:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index e2cbe180b..909a01d4e 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -434,6 +434,33 @@ pub fn bytes_mut_capacity(n: usize) -> usize { buf.capacity() } +/// `bytes` reads a `Buf` of the crate's own into a `BytesMut` by its `copy_to_bytes` only +/// at zero capacity. +pub fn bytes_mut_put(buf: &mut bytes::BytesMut, src: Counted) { + bytes::BufMut::put(buf, src); +} + +/// A `Buf` whose `copy_to_bytes` differs from its `chunk` and `advance`. +pub struct Counted(pub bytes::Bytes); + +impl bytes::Buf for Counted { + fn remaining(&self) -> usize { + self.0.remaining() + } + + fn chunk(&self) -> &[u8] { + self.0.chunk() + } + + fn advance(&mut self, cnt: usize) { + self.0.advance(cnt); + } + + fn copy_to_bytes(&mut self, len: usize) -> bytes::Bytes { + bytes::Bytes::from(vec![0; len]) + } +} + pub struct Part(pub u64); impl std::iter::Sum for std::time::Duration { diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index e8921bf65..b55342865 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -53,6 +53,7 @@ roots = [ "places_equal", "owned_bytes", "bytes_mut_capacity", + "bytes_mut_put", "fma", "float_printed", "weak_object", diff --git a/ts/fixtures/stock/expected/buf.ts b/ts/fixtures/stock/expected/buf.ts index 522fa55d8..776c8949f 100644 --- a/ts/fixtures/stock/expected/buf.ts +++ b/ts/fixtures/stock/expected/buf.ts @@ -241,14 +241,10 @@ export function reads(data: rt.ByteSlice, out: rt.ByteVec): void { rest = readAll$Pieces(Pieces.new(input, cut), new rt.ByteSlice(data.data, data.start + 2, mid), readPieces, out); } rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rest)); - const put: rt.BytesMut = rt.bytesMutWithCapacity(rt.usizeRem(data.data[data.start] as rt.usize, 2)); - const _42: Pieces.Pieces = Pieces.new(input, cut); - rt.bytesMutPutBuf(put, _42, Pieces.hasRemaining$Buf, Pieces.remaining$Buf, Pieces.chunk$Buf, Pieces.advance$Buf, Pieces.copyToBytes$Buf); const vec: rt.ByteVec = new rt.ByteVec(); - const _46: Pieces.Pieces = Pieces.new(input, cut); - rt.byteVecPutBuf(vec, _46, Pieces.hasRemaining$Buf, Pieces.remaining$Buf, Pieces.chunk$Buf, Pieces.advance$Buf); - rt.byteVecPush(out, rt.byteSliceEq(rt.bytesMutView(put), rt.byteVecSlice(vec)) ? 1 : 0); - rt.byteVecExtendFromSlice(out, rt.bytesMutView(put)); + const _38: Pieces.Pieces = Pieces.new(input, cut); + rt.byteVecPutBuf(vec, _38, Pieces.hasRemaining$Buf, Pieces.remaining$Buf, Pieces.chunk$Buf, Pieces.advance$Buf); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(vec)); const slice: rt.ByteSlice = input; rt.byteVecPush(out, slice.length === input.length ? 1 : 0); rt.byteVecPush(out, rt.byteSliceEq(slice, input) ? 1 : 0); diff --git a/ts/fixtures/stock/src/buf.rs b/ts/fixtures/stock/src/buf.rs index e1ca4a0f7..c2bd1e7d2 100644 --- a/ts/fixtures/stock/src/buf.rs +++ b/ts/fixtures/stock/src/buf.rs @@ -182,13 +182,10 @@ pub fn reads(data: &[u8], out: &mut Vec) { _ => read_all(&mut Pieces::new(input, cut), ops, read_pieces, out), }; out.extend_from_slice(&rest); - // Put whole, into a buffer with room and one without, which `bytes` reads differently. - let mut put = BytesMut::with_capacity(*kind as usize % 2); - put.put(Pieces::new(input, cut)); + // Put whole, chunk by chunk. let mut vec = Vec::new(); vec.put(Pieces::new(input, cut)); - out.push((put == vec) as u8); - out.extend_from_slice(&put); + out.extend_from_slice(&vec); let slice: &[u8] = input; out.push((slice.remaining() == input.len()) as u8); out.push((slice.chunk() == input) as u8); diff --git a/ts/runtime/rt/bytes.ts b/ts/runtime/rt/bytes.ts index 1f521eeb0..276963d88 100644 --- a/ts/runtime/rt/bytes.ts +++ b/ts/runtime/rt/bytes.ts @@ -395,32 +395,6 @@ export function bytesMutCopyToSlice(b: BytesMut, dst: ByteSlice): void { bytesMutAdvance(b, dst.length); } -/** - * `BufMut::put` into a `BytesMut` of a `Buf` the crate implements, through its methods. - * Into no room, `bytes` takes `copy_to_bytes` of all of it; into some, each chunk in turn. - */ -export function bytesMutPutBuf( - b: BytesMut, - src: B, - hasRemaining: (src: B) => boolean, - remaining: (src: B) => usize, - chunk: (src: B) => ByteSlice, - advance: (src: B, cnt: usize) => void, - copyToBytes: (src: B, len: usize) => Bytes, -): void { - if (!hasRemaining(src)) return; - if (b.cap === 0) { - bytesMutExtend(b, copyToBytes(src, remaining(src))); - return; - } - bytesMutReserve(b, remaining(src)); - while (hasRemaining(src)) { - const s = chunk(src); - bytesMutExtend(b, s); - advance(src, s.length as usize); - } -} - // BufMut of Vec /** `BufMut::put` into a `Vec` of a `Buf` the crate implements, each chunk in turn. */ diff --git a/ts/src/census.rs b/ts/src/census.rs index b615d0a69..ca5a30f76 100644 --- a/ts/src/census.rs +++ b/ts/src/census.rs @@ -143,6 +143,7 @@ const VERBATIM: &[&str] = &[ "Binary", "BufMut::put", "Bytes::from_owner", + "BytesMut", "Copy", "Debug", "DebugList::entries", diff --git a/ts/src/lower/stock.rs b/ts/src/lower/stock.rs index 39bb25f1f..241c52fea 100644 --- a/ts/src/lower/stock.rs +++ b/ts/src/lower/stock.rs @@ -533,7 +533,8 @@ fn buf_mut<'tcx>( } /// `BufMut::put` of a `Buf` into a buffer the mapping writes: all of it, read whole from -/// a buffer the mapping reads, and otherwise through its own methods, as `bytes` reads it. +/// a buffer the mapping reads, and otherwise through its own methods, as `bytes` reads it +/// into a `Vec`. fn put<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, buffer: Buffer, this: Expr, src: Expr) -> Option { let tcx = b.t.tcx; let ty = targ(call.args, 1); @@ -554,6 +555,14 @@ fn put<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, buffer: Buffer, this let msg = format!("`BufMut::put` of `{ty}`, which is not supported"); return Some(b.err(call.span, msg)); } + // Into a `BytesMut`, `bytes` calls its `copy_to_bytes` or its `chunk` and `advance` by + // whether the capacity is zero. + if buffer == Buffer::BytesMut { + let msg = format!( + "`BufMut::put` of `{ty}` into a `BytesMut`, which picks the methods it calls by a capacity that depends on whether the other handles of its storage dropped, which is not supported" + ); + return Some(b.err(call.span, msg)); + } let buf = tcx .traits(call.def_id.krate) .iter() @@ -573,13 +582,10 @@ fn put<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, buffer: Buffer, this method("chunk")?, method("advance")?, ); - Some(match buffer { - Buffer::BytesMut => { - let copy = method("copy_to_bytes")?; - Expr::rt("bytesMutPutBuf", vec![this, src, has, remaining, chunk, advance, copy]) - } - _ => Expr::rt("byteVecPutBuf", vec![this, src, has, remaining, chunk, advance]), - }) + Some(Expr::rt( + "byteVecPutBuf", + vec![this, src, has, remaining, chunk, advance], + )) } /// A `get_` or `put_` method's scalar, and whether its bytes are little-endian, as From aa328080751381d5b93f8127127556219330e3cd Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:49:48 -0700 Subject: [PATCH 6/9] fix(ts): throw on Bytes::slice_ref of bytes from other storage Rust may share storage that the translation copies, such as a &'static str's bytes, which as_bytes encodes anew, so a subset from another buffer may be one Rust accepts. Throw a rust2-ts error there instead of panicking as if Rust would. Co-Authored-By: Claude Opus 5.5 --- ts/README.md | 4 +++- ts/runtime/rt/bytes.ts | 8 ++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/ts/README.md b/ts/README.md index f54d31f7a..03aceb2e2 100644 --- a/ts/README.md +++ b/ts/README.md @@ -308,7 +308,9 @@ of them: `Clone`, `Deref`, `AsRef`, `PartialEq` with bytes, `Default`, `Debug`, and `From` between it and `Vec`, `String`, `&'static [u8]`, and `&'static str` map to `rt/bytes.ts`, panicking as `bytes` does, and so do `split_to`, `split_off`, - `truncate`, `clear`, and `slice_ref`, whose panic names no addresses. `Bytes::from_owner` + `truncate`, `clear`, and `slice_ref`, whose panic names no addresses. `slice_ref` of + bytes from other storage throws, since Rust may share what JS copied, as a `&'static + str`'s bytes that `as_bytes` encodes anew. `Bytes::from_owner` reads its owner's bytes once, as `bytes` does, and is refused for an owner that drops, which would drop with the last clone of what it makes. - `bytes::BytesMut` is an `rt.BytesMut`: a window of storage that the handles `split_to` diff --git a/ts/runtime/rt/bytes.ts b/ts/runtime/rt/bytes.ts index 276963d88..6fa2937d8 100644 --- a/ts/runtime/rt/bytes.ts +++ b/ts/runtime/rt/bytes.ts @@ -104,11 +104,15 @@ export function bytesTruncate(p: Place, len: usize): void { /** * `Bytes::slice_ref`: the bytes of `b` that `subset` is, by where they are in memory. Its - * panic names no addresses, which JS has none of. + * panic names no addresses, which JS has none of. Bytes of other storage throw instead: + * Rust may share what JS copied, such as a `&'static str`'s bytes, which `as_bytes` + * encodes anew each time. */ export function bytesSliceRef(b: Bytes, subset: ByteSlice): Bytes { if (subset.length === 0) return bytesNew(); - if (subset.data.buffer !== b.data.buffer) panic("subset is out of bounds"); + if (subset.data.buffer !== b.data.buffer) { + throw new Error("rust2-ts: `Bytes::slice_ref` of bytes from other storage, which Rust may share where JS copied"); + } const at = subset.data.byteOffset + subset.start; const from = b.data.byteOffset + b.start; if (at < from) panic("subset pointer is smaller than self pointer"); From 32c45e0b4d6f814e0f0ec2b76672b57e7d779b92 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:12:06 -0700 Subject: [PATCH 7/9] fix(ts): track when a BytesMut's storage kind depends on drops bytes keeps shared storage shared when it grows with no other handle alive, and makes it a vector when one is, so after shared storage grows, after From, and after a vector's put of a Bytes or BytesMut, its kind is unknown here. A reserve past usize::MAX, whose panic message is "overflow" for shared storage and "capacity overflow" for a vector, throws a rust2-ts error there instead of guessing. The stock fixture reserves past usize::MAX only into handles sure of their kind. Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/stock/expected/buf.ts | 71 ++++++++++++++++--------------- ts/fixtures/stock/src/buf.rs | 20 ++++++--- ts/runtime/rt/bytes.ts | 40 ++++++++++++++--- ts/src/lower/stock.rs | 18 +++++--- 4 files changed, 96 insertions(+), 53 deletions(-) diff --git a/ts/fixtures/stock/expected/buf.ts b/ts/fixtures/stock/expected/buf.ts index 776c8949f..fd38aa794 100644 --- a/ts/fixtures/stock/expected/buf.ts +++ b/ts/fixtures/stock/expected/buf.ts @@ -10,7 +10,6 @@ import { hasRemaining$Buf_Bytes, hasRemaining$Buf_BytesMut, remaining$Buf_Bytes, * write to one that reached another would show. */ export function bytesMut(data: rt.ByteSlice, out: rt.ByteVec): void { - let _61!: rt.usize; const ops: Ops.Ops = { _0: data }; const buf: rt.BytesMut = rt.bytesMutWithCapacity(rt.usizeRem(Ops.byte(ops) as rt.usize, 24)); const pieces: rt.BytesMut[] = []; @@ -42,19 +41,23 @@ export function bytesMut(data: rt.ByteSlice, out: rt.ByteVec): void { } else if (_20 === 6) { rt.bytesMutResize(buf, rt.usizeRem(n, 40), n & 0xff); } else if (_20 === 7) { - const _62: rt.usize = rt.usizeRem(n, 4); - if (_62 === 0) { - _61 = rt.usizeSub(4294967295, n); - } else if (_62 === 1) { - _61 = rt.usizeAdd(rt.usizeSub(2147483647, buf.length), 1); + const _60: rt.usize = rt.usizeRem(n, 4); + if (_60 === 0) { + const fresh: rt.BytesMut = rt.bytesMutFrom(Ops.take(ops, rt.usizeRem(n, 6))); + if (rt.usizeRem(n, 8) === 0) { + const _72: rt.BytesMut = rt.bytesMutSplitTo(fresh, 0); + pieces.push(_72); + } + rt.bytesMutReserve(fresh, rt.usizeSub(4294967295, n)); + } else if (_60 === 1) { + rt.bytesMutReserve(buf, rt.usizeAdd(rt.usizeSub(2147483647, buf.length), 1)); } else { - _61 = n; + rt.bytesMutReserve(buf, n); } - rt.bytesMutReserve(buf, _61); } else if (_20 === 8) { - const _71: rt.BytesMut | undefined = pieces.pop(); - if (_71 !== undefined) { - rt.bytesMutUnsplit(buf, _71); + const _87: rt.BytesMut | undefined = pieces.pop(); + if (_87 !== undefined) { + rt.bytesMutUnsplit(buf, _87); } } else if (_20 === 9) { rt.bytesMutAdvance(buf, rt.usizeRem(n, rt.usizeAdd(buf.length, 2))); @@ -64,32 +67,32 @@ export function bytesMut(data: rt.ByteSlice, out: rt.ByteVec): void { rt.bytesMutTruncate(buf, 0); } else if (_20 === 12) { const buf2 = buf; - const _91: rt.BytesMut = rt.bytesMutSplitTo(buf2, buf2.length); - pieces.push(_91); + const _107: rt.BytesMut = rt.bytesMutSplitTo(buf2, buf2.length); + pieces.push(_107); } else if (_20 === 13) { - const _94: rt.ByteSlice = rt.bytesMutFreeze(rt.bytesMutSplitTo(buf, rt.usizeRem(n, rt.usizeAdd(buf.length, 2)))); - frozen.push(_94); + const _110: rt.ByteSlice = rt.bytesMutFreeze(rt.bytesMutSplitTo(buf, rt.usizeRem(n, rt.usizeAdd(buf.length, 2)))); + frozen.push(_110); } else if (_20 === 14) { rt.bytesMutPutFill(buf, n & 0xff, rt.usizeRem(n, 9)); } else if (_20 === 15) { if (!((buf.length === 0))) { const at: rt.usize = rt.usizeRem(n, buf.length); - const _112: rt.ByteSlice = rt.bytesMutView(buf); - rt.idx(_112, at); - _112.data[_112.start + at] = _112.data[_112.start + at] ^ 255; + const _128: rt.ByteSlice = rt.bytesMutView(buf); + rt.idx(_128, at); + _128.data[_128.start + at] = _128.data[_128.start + at] ^ 255; } - const _117: rt.BytesMut | undefined = rt.sliceLast(pieces); - if (_117 !== undefined) { - rt.bytesMutExtend(_117, rt.byteSliceFrom(Uint8Array.of(120, 121))); + const _133: rt.BytesMut | undefined = rt.sliceLast(pieces); + if (_133 !== undefined) { + rt.bytesMutExtend(_133, rt.byteSliceFrom(Uint8Array.of(120, 121))); } } else if (_20 === 16) { - const _126: rt.ByteSlice = rt.bytesCopyFromSlice(Ops.take(ops, rt.usizeRem(n, 5))); - rt.bytesMutExtend(buf, _126); + const _142: rt.ByteSlice = rt.bytesCopyFromSlice(Ops.take(ops, rt.usizeRem(n, 5))); + rt.bytesMutPutStorage(buf, _142); } else { const source: rt.BytesMut = rt.bytesMutFrom(Ops.take(ops, rt.usizeRem(n, 6))); const first: rt.u8 = getU8Checked$Checked_BytesMut(source); rt.bytesMutPutWord(buf, first, 1, false); - rt.bytesMutExtend(buf, rt.bytesMutView(source)); + rt.bytesMutPutStorage(buf, rt.bytesMutView(source)); } } else { break; @@ -97,18 +100,18 @@ export function bytesMut(data: rt.ByteSlice, out: rt.ByteVec): void { } const tail: rt.BytesMut = rt.bytesMutFrom(rt.byteSliceRange(rt.byteSliceFrom(Uint8Array.of(116, 97, 105, 108)), 0)); rt.byteVecPush(out, rt.byteSliceEq(rt.bytesMutView(buf), rt.bytesMutView(tail)) ? 1 : 0); - const _155: rt.BytesMut = rt.bytesMutFrom(rt.bytesMutView(buf)); - const _157: rt.ByteSlice = rt.byteSliceRange(rt.bytesMutView(buf), 0); - rt.byteVecPush(out, rt.byteSliceEq(rt.bytesMutView(_155), _157) ? 1 : 0); - const _168: rt.usize = buf.length; - const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(rt.bytesMutView(buf), f), (f: rt.Formatter) => rt.usizeDisplay(_168, f)]; + const _171: rt.BytesMut = rt.bytesMutFrom(rt.bytesMutView(buf)); + const _173: rt.ByteSlice = rt.byteSliceRange(rt.bytesMutView(buf), 0); + rt.byteVecPush(out, rt.byteSliceEq(rt.bytesMutView(_171), _173) ? 1 : 0); + const _184: rt.usize = buf.length; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(rt.bytesMutView(buf), f), (f: rt.Formatter) => rt.usizeDisplay(_184, f)]; rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0], " ", args2[1], "\n"]))); - for (const _179 of pieces) { - const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(rt.bytesMutView(_179), f)]; + for (const _195 of pieces) { + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(rt.bytesMutView(_195), f)]; rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args4[0], "\n"]))); } - for (const _198 of frozen) { - const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(_198, f)]; + for (const _214 of frozen) { + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(_214, f)]; rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args6[0], "\n"]))); } rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rt.bytesMutToByteVec(buf))); @@ -368,7 +371,7 @@ export function writeAll$BytesMut(buf: rt.BytesMut, data: rt.ByteSlice): void { } else if (_18 === 12) { rt.bytesMutPutFill(buf, n2, rt.usizeRem(n2 as rt.usize, 7)); } else if (_18 === 13) { - rt.bytesMutExtend(buf, rt.byteSliceFrom(Uint8Array.of(112, 117, 116))); + rt.bytesMutPutStorage(buf, rt.byteSliceFrom(Uint8Array.of(112, 117, 116))); } else { rt.bytesMutPutBytes(buf, rt.f64ToBeBytes(((n2 as rt.f64)) / 3.0), false); } diff --git a/ts/fixtures/stock/src/buf.rs b/ts/fixtures/stock/src/buf.rs index c2bd1e7d2..f8478c3fb 100644 --- a/ts/fixtures/stock/src/buf.rs +++ b/ts/fixtures/stock/src/buf.rs @@ -24,12 +24,20 @@ pub fn bytes_mut(data: &[u8], out: &mut Vec) { } 5 => buf.truncate(n % (buf.len() + 2)), 6 => buf.resize(n % 40, n as u8), - // Past what a buffer holds, by overflowing `usize` or not: each panics. - 7 => buf.reserve(match n % 4 { - 0 => usize::MAX - n, - 1 => isize::MAX as usize - buf.len() + 1, - _ => n, - }), + // Past what a buffer holds, by overflowing `usize` or not: each panics. Past + // `usize::MAX`, by the kind of storage, so into a handle sure of its kind: a new + // one, a vector, or one split, shared. + 7 => match n % 4 { + 0 => { + let mut fresh = BytesMut::from(ops.take(n % 6)); + if n % 8 == 0 { + pieces.push(fresh.split_to(0)); + } + fresh.reserve(usize::MAX - n); + } + 1 => buf.reserve(isize::MAX as usize - buf.len() + 1), + _ => buf.reserve(n), + }, 8 => { if let Some(piece) = pieces.pop() { buf.unsplit(piece); diff --git a/ts/runtime/rt/bytes.ts b/ts/runtime/rt/bytes.ts index 6fa2937d8..c20ee7f59 100644 --- a/ts/runtime/rt/bytes.ts +++ b/ts/runtime/rt/bytes.ts @@ -211,10 +211,14 @@ export class BytesMut { start: number; length: number; cap: number; - /** Whether `split_to` shared its storage, whose growth panics as `bytes`' shared kind does. */ - shared: boolean; - - constructor(data: Uint8Array, start: number, length: number, cap: number, shared: boolean) { + /** + * Whether its storage is `bytes`' shared kind, which `split_to` makes and whose growth + * panics apart from a vector's. `undefined` where `bytes`' kind depends on whether other + * handles of its storage dropped, as once shared storage grows. + */ + shared: boolean | undefined; + + constructor(data: Uint8Array, start: number, length: number, cap: number, shared: boolean | undefined) { this.data = data; this.start = start; this.length = length; @@ -244,6 +248,13 @@ export function bytesMutFrom(s: ByteSlice): BytesMut { return b; } +/** `BytesMut::from` a `Bytes`, whose storage it takes where no other handle holds it. */ +export function bytesMutFromBytes(s: Bytes): BytesMut { + const b = bytesMutFrom(s); + b.shared = undefined; + return b; +} + /** Its bytes, as `Deref`, `DerefMut`, `AsRef`, `AsMut`, and `Buf::chunk` lend them. */ export function bytesMutView(b: BytesMut): ByteSlice { return new ByteSlice(b.data, b.start, b.length); @@ -270,7 +281,12 @@ export function bytesMutReserve(b: BytesMut, additional: usize): void { b.start = 0; return; } - if (needed > 0xffffffff && b.shared) panic("overflow"); + if (needed > 0xffffffff) { + if (b.shared === undefined) { + throw new Error("rust2-ts: `BytesMut::reserve` past `usize::MAX`, whose panic depends on whether other handles of its storage dropped"); + } + if (b.shared) panic("overflow"); + } // A vector grows past its offset, where a shared one starts afresh. if ((b.shared ? needed : b.start + needed) > ISIZE_MAX) panic("capacity overflow"); const cap = Math.max(needed, b.cap * 2, 8); @@ -279,7 +295,19 @@ export function bytesMutReserve(b: BytesMut, additional: usize): void { b.data = data; b.start = 0; b.cap = cap; - b.shared = false; + // Shared storage stays shared if no other handle held it, and becomes a vector if one did. + if (b.shared) b.shared = undefined; +} + +/** + * `BufMut::put` of a `Bytes` or a `BytesMut`. At zero capacity `bytes` takes its storage, + * of a kind that depends on its handles, and a vector's capacity is only approximate here. + */ +export function bytesMutPutStorage(b: BytesMut, s: Bytes): void { + if (s.length === 0) return; + const vector = b.shared === false; + bytesMutExtend(b, s); + if (vector) b.shared = undefined; } /** `BytesMut::extend_from_slice`, and `BufMut::put_slice`. */ diff --git a/ts/src/lower/stock.rs b/ts/src/lower/stock.rs index 241c52fea..b64c547e2 100644 --- a/ts/src/lower/stock.rs +++ b/ts/src/lower/stock.rs @@ -292,10 +292,11 @@ fn from<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec) -> (Some(Std::Bytes), _) => return Ok(None), (Some(Std::BytesMut), _) => { let bytes = match as_slice(b, from.peel_refs(), args.next().expect("an operand")) { - Some(bytes) if from.is_ref() || b.t.std_of(from) == Some(Std::Bytes) => bytes, + Some(bytes) if from.is_ref() => Expr::rt("bytesMutFrom", vec![bytes]), + Some(bytes) if b.t.std_of(from) == Some(Std::Bytes) => Expr::rt("bytesMutFromBytes", vec![bytes]), _ => return Ok(None), }; - return Ok(Some(Expr::rt("bytesMutFrom", vec![bytes]))); + return Ok(Some(bytes)); } (_, Some(Std::Bytes)) if byte_vec(to) => "byteSliceToByteVec", (_, Some(Std::BytesMut)) if byte_vec(to) => "bytesMutToByteVec", @@ -538,16 +539,19 @@ fn buf_mut<'tcx>( fn put<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, buffer: Buffer, this: Expr, src: Expr) -> Option { let tcx = b.t.tcx; let ty = targ(call.args, 1); - let bytes = match Buffer::of(tcx, ty) { + let source = Buffer::of(tcx, ty); + let bytes = match source { Some(Buffer::BytesMut) => Some(view(src.clone())), Some(Buffer::Bytes | Buffer::Slice) => Some(src.clone()), _ => None, }; if let Some(bytes) = bytes { - return Some(match buffer { - Buffer::BytesMut => Expr::rt("bytesMutExtend", vec![this, bytes]), - _ => Expr::rt("byteVecExtendFromSlice", vec![this, bytes]), - }); + let f = match (buffer, source) { + (Buffer::BytesMut, Some(Buffer::Slice)) => "bytesMutExtend", + (Buffer::BytesMut, _) => "bytesMutPutStorage", + _ => "byteVecExtendFromSlice", + }; + return Some(Expr::rt(f, vec![this, bytes])); } // `put` drops it between calls of its methods, which only an object JS can call them on // can stand for. From 5faf0c6fe095c9f7ac08cb01dbcf2a27c14f56c8 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:46:10 -0700 Subject: [PATCH 8/9] fix(ts): grow a BytesMut vector as Vec does and limit shared storage's reserve A handle never split nor taken from a Bytes is bytes' vector kind, whose offset and capacity rt.BytesMut now keeps exactly, so it grows and panics as Vec does. Once storage was shared or taken, bytes' capacity depends on which handles dropped, so reserve throws a rust2-ts error past 512 MiB, counting what the handle read past; below that, bytes' storage stays under 1 GiB and grows without panicking whichever handles dropped. The stock fixture's caller names inputs at the limit's edges, and a runtime test checks the throw. Drops the bench quest, which #160 fixes. Co-Authored-By: Claude Opus 5.5 --- quest/m2/README.md | 1 - quest/m2/ts-bench-forms.md | 21 ----- quest/m3/ts-bytes-capacity.md | 8 +- ts/README.md | 12 ++- ts/fixtures/stock/caller.ts | 11 +++ ts/fixtures/stock/expected/buf.ts | 105 +++++++++++++++-------- ts/fixtures/stock/expected/core/bool.ts | 12 +++ ts/fixtures/stock/expected/harness.ts | 4 +- ts/fixtures/stock/src/buf.rs | 49 +++++++---- ts/fixtures/stock/src/harness.rs | 1 + ts/runtime/rt/bytes.ts | 107 +++++++++++++++--------- ts/tests/fixtures.rs | 4 +- ts/tests/reserve.ts | 43 ++++++++++ ts/tests/runtime.rs | 14 ++++ 14 files changed, 274 insertions(+), 118 deletions(-) delete mode 100644 quest/m2/ts-bench-forms.md create mode 100644 ts/fixtures/stock/caller.ts create mode 100644 ts/fixtures/stock/expected/core/bool.ts create mode 100644 ts/tests/reserve.ts diff --git a/quest/m2/README.md b/quest/m2/README.md index 2486bb2c9..c32ab1dd8 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -31,7 +31,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export/README - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values - [Held values that name a reassigned variable](/quest/m2/ts-aliases.md) - a held place or folded value reads what Rust read, in and across loop iterations - [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 -- [The bench's varint forms at moq's pin](/quest/m2/ts-bench-forms.md) - `just ts bench` runs to its report, its hand-written route decoding each varint form - [Translate against the prebuilt std](/quest/m2/ts-std-build.md) - measure whether `-Zbuild-std` is still needed now that panics abort, and drop it if not - [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-bench-forms.md b/quest/m2/ts-bench-forms.md deleted file mode 100644 index 0a50c2865..000000000 --- a/quest/m2/ts-bench-forms.md +++ /dev/null @@ -1,21 +0,0 @@ -# [S] The bench's varint forms at moq's pin - -## Goal - -`just ts bench` runs to its report at the moq pin, its hand-written route decoding each -varint form as the codec fixture encodes it. - -## Plan - -Found by [#222](https://github.com/kixelated/rust2/pull/222) on 2026-10-29: #196's pin -dropped `Ietf.DRAFT_16` and `DRAFT_17` from moq's `js/net`, so `bench/moq.ts`'s `FORMS` -passes `undefined` as both versions. moq's `isLeadingOnes` takes any version but lite's -first six as leading ones, so the hand-written decode of `varint/quic/2B` and wider reads -QUIC wire as leading ones and fails the output check. Bun runs `bench/` untyped, so -nothing caught it. - -- Pick each form's version from those moq still has: `Lite.DRAFT_06` for QUIC, and - `Lite.DRAFT_07` or `Ietf.DRAFT_18` for leading ones. #222 measured with `Lite.DRAFT_06`. -- Type-check `bench/` in `just check`, so a pin bump that drops a version fails there. - -Public API: none. diff --git a/quest/m3/ts-bytes-capacity.md b/quest/m3/ts-bytes-capacity.md index 8d64f2752..1ad61442c 100644 --- a/quest/m3/ts-bytes-capacity.md +++ b/quest/m3/ts-bytes-capacity.md @@ -3,7 +3,8 @@ ## Goal [rust2-ts](/ts/README.md) translates `BytesMut::capacity`, `split_off`, `try_reclaim`, -`try_unsplit`, and `spare_capacity_mut` with `bytes`' values, proven by differential tests +`try_unsplit`, and `spare_capacity_mut` with `bytes`' values, and `rt.BytesMut` drops its +512 MiB limit on `reserve` for storage that was shared, proven by differential tests against native Rust. ## Plan @@ -12,7 +13,10 @@ Found by [#222](https://github.com/kixelated/rust2/pull/222) on 2026-10-29: `byt reclaims a `BytesMut`'s storage in `reserve` once no other handle of it is alive, so its capacity depends on whether the `Bytes` it froze and the handles it split off dropped. `rt.ByteSlice`, which a `Bytes` is, is a value JS copies and counts no drops, so #222 -refuses these. moq calls none of them. +refuses these. moq calls none of them. For the same reason, once its storage was shared +or taken from a `Bytes`, `reserve` throws a `rust2-ts:` error past 512 MiB, counting what +the handle read past, where `bytes`' panic, or its growing instead, depends on which +handles dropped. Exact capacity removes that limit. - Count the live handles of a storage, as [shared ownership](/quest/m2/ts-shared.md) counts an `Arc`'s, which makes a `Bytes` a value that drops. diff --git a/ts/README.md b/ts/README.md index 090f0bc38..a9866bf3a 100644 --- a/ts/README.md +++ b/ts/README.md @@ -320,9 +320,12 @@ of them: `truncate`, `clear`, `resize`, `reserve`, `extend_from_slice`, `unsplit`, `Clone`, `Deref`, `DerefMut`, `AsRef`, `AsMut`, `PartialEq` with bytes, `Default`, `Debug`, and `From` between it and `Bytes`, `Vec`, `&[u8]`, and `&str` map, panicking as `bytes` - does. Its capacity is refused, and so are `split_off`, `try_reclaim`, `try_unsplit`, - and `spare_capacity_mut`, which read it: `bytes`' depends on whether the other handles - of its storage dropped, such as a `Bytes` it froze, which nothing here counts. + does. A handle never split nor taken from a `Bytes` is a vector that grows and panics + as `Vec` does, counting the bytes it read past. Once its storage was shared, `bytes`' + capacity depends on whether the other handles of it dropped, such as a `Bytes` it froze, + which nothing here counts: its `reserve` throws past 512 MiB, counting what it read + past, where `bytes`' panic depends on that, and its capacity is refused, as are + `split_off`, `try_reclaim`, `try_unsplit`, and `spare_capacity_mut`, which read it. - `Buf` and `BufMut` of a `Bytes`, a `BytesMut`, a `&[u8]`, and a `Vec` map: the required methods, `has_remaining`, `copy_to_slice`, `copy_to_bytes`, each `get_` and `put_` of an integer or `f64`, `put_slice`, `put_bytes`, and `put`, whose panics are @@ -625,7 +628,8 @@ built natively for wasm32 and run beside its translation on the same inputs by that each random value is in its range, every value of a small range drawn. It splits, freezes, grows, and writes a `BytesMut` by ops its input picks, ending with every piece's bytes, and reads and writes through `Buf` and `BufMut` generically, a buffer of - its own included. + its own included. `caller.ts` names the inputs that reserve at the edges of + `BytesMut`'s 512 MiB limit. - `bind` binds `buf::Blob`, a renamed dependency's type with `unsafe` inside, and a function and a type of its own that read through raw pointers, the type dropping an `Arc` where Rust drops it, to the TS in `bind/`. Its differential test runs them against native Rust. `wrong.toml` binds TS that doesn't match diff --git a/ts/fixtures/stock/caller.ts b/ts/fixtures/stock/caller.ts new file mode 100644 index 000000000..96748e5ad --- /dev/null +++ b/ts/fixtures/stock/caller.ts @@ -0,0 +1,11 @@ +// The harness, with inputs it names for `differential.ts`: `buf::reserves`' edges of +// `rt.BytesMut`'s limit, which only these reach, as each allocates 512 MiB. + +import { cases as all, run } from "./harness.ts"; + +export { run }; + +const reserves = all().length - 1; + +/** Each edge but shared storage past the limit, which throws, read past by none and by some. */ +export const cases: Uint8Array[] = [0, 1, 2].flatMap((kind) => [0, 3].map((read) => Uint8Array.of(reserves, ...new TextEncoder().encode("edge"), kind, read))); diff --git a/ts/fixtures/stock/expected/buf.ts b/ts/fixtures/stock/expected/buf.ts index fd38aa794..0a25eb402 100644 --- a/ts/fixtures/stock/expected/buf.ts +++ b/ts/fixtures/stock/expected/buf.ts @@ -4,12 +4,14 @@ import * as rt from "./rt.ts"; import * as Ops from "./buf.Ops.ts"; import * as Pieces from "./buf.Pieces.ts"; import { hasRemaining$Buf_Bytes, hasRemaining$Buf_BytesMut, remaining$Buf_Bytes, remaining$Buf_BytesMut } from "./bytes/buf/buf_impl.ts"; +import { then$bool_BytesMut_reserves_closure0 } from "./core/bool.ts"; /** * A `BytesMut` split, frozen, grown, and written, ending with every piece's bytes: a * write to one that reached another would show. */ export function bytesMut(data: rt.ByteSlice, out: rt.ByteVec): void { + let _80!: rt.usize; const ops: Ops.Ops = { _0: data }; const buf: rt.BytesMut = rt.bytesMutWithCapacity(rt.usizeRem(Ops.byte(ops) as rt.usize, 24)); const pieces: rt.BytesMut[] = []; @@ -41,23 +43,27 @@ export function bytesMut(data: rt.ByteSlice, out: rt.ByteVec): void { } else if (_20 === 6) { rt.bytesMutResize(buf, rt.usizeRem(n, 40), n & 0xff); } else if (_20 === 7) { - const _60: rt.usize = rt.usizeRem(n, 4); - if (_60 === 0) { + if (!(rt.usizeRem(n, 2) === 0)) { + rt.bytesMutReserve(buf, n); + } else { const fresh: rt.BytesMut = rt.bytesMutFrom(Ops.take(ops, rt.usizeRem(n, 6))); - if (rt.usizeRem(n, 8) === 0) { - const _72: rt.BytesMut = rt.bytesMutSplitTo(fresh, 0); - pieces.push(_72); + const read: rt.usize = rt.usizeRem(n, rt.usizeAdd(fresh.length, 1)); + rt.bytesMutAdvance(fresh, read); + const len: rt.usize = fresh.length; + const _81: rt.usize = rt.usizeRem(n, 3); + if (_81 === 0) { + _80 = rt.usizeSub(4294967295, n); + } else if (_81 === 1) { + _80 = rt.usizeAdd(rt.usizeSub(2147483647, len), 1); + } else { + _80 = rt.usizeSub(rt.usizeSub(rt.usizeAdd(2147483647, 1), read), len); } - rt.bytesMutReserve(fresh, rt.usizeSub(4294967295, n)); - } else if (_60 === 1) { - rt.bytesMutReserve(buf, rt.usizeAdd(rt.usizeSub(2147483647, buf.length), 1)); - } else { - rt.bytesMutReserve(buf, n); + rt.bytesMutReserve(fresh, _80); } } else if (_20 === 8) { - const _87: rt.BytesMut | undefined = pieces.pop(); - if (_87 !== undefined) { - rt.bytesMutUnsplit(buf, _87); + const _95: rt.BytesMut | undefined = pieces.pop(); + if (_95 !== undefined) { + rt.bytesMutUnsplit(buf, _95); } } else if (_20 === 9) { rt.bytesMutAdvance(buf, rt.usizeRem(n, rt.usizeAdd(buf.length, 2))); @@ -67,27 +73,27 @@ export function bytesMut(data: rt.ByteSlice, out: rt.ByteVec): void { rt.bytesMutTruncate(buf, 0); } else if (_20 === 12) { const buf2 = buf; - const _107: rt.BytesMut = rt.bytesMutSplitTo(buf2, buf2.length); - pieces.push(_107); + const _115: rt.BytesMut = rt.bytesMutSplitTo(buf2, buf2.length); + pieces.push(_115); } else if (_20 === 13) { - const _110: rt.ByteSlice = rt.bytesMutFreeze(rt.bytesMutSplitTo(buf, rt.usizeRem(n, rt.usizeAdd(buf.length, 2)))); - frozen.push(_110); + const _118: rt.ByteSlice = rt.bytesMutFreeze(rt.bytesMutSplitTo(buf, rt.usizeRem(n, rt.usizeAdd(buf.length, 2)))); + frozen.push(_118); } else if (_20 === 14) { rt.bytesMutPutFill(buf, n & 0xff, rt.usizeRem(n, 9)); } else if (_20 === 15) { if (!((buf.length === 0))) { const at: rt.usize = rt.usizeRem(n, buf.length); - const _128: rt.ByteSlice = rt.bytesMutView(buf); - rt.idx(_128, at); - _128.data[_128.start + at] = _128.data[_128.start + at] ^ 255; + const _136: rt.ByteSlice = rt.bytesMutView(buf); + rt.idx(_136, at); + _136.data[_136.start + at] = _136.data[_136.start + at] ^ 255; } - const _133: rt.BytesMut | undefined = rt.sliceLast(pieces); - if (_133 !== undefined) { - rt.bytesMutExtend(_133, rt.byteSliceFrom(Uint8Array.of(120, 121))); + const _141: rt.BytesMut | undefined = rt.sliceLast(pieces); + if (_141 !== undefined) { + rt.bytesMutExtend(_141, rt.byteSliceFrom(Uint8Array.of(120, 121))); } } else if (_20 === 16) { - const _142: rt.ByteSlice = rt.bytesCopyFromSlice(Ops.take(ops, rt.usizeRem(n, 5))); - rt.bytesMutPutStorage(buf, _142); + const _150: rt.ByteSlice = rt.bytesCopyFromSlice(Ops.take(ops, rt.usizeRem(n, 5))); + rt.bytesMutPutStorage(buf, _150); } else { const source: rt.BytesMut = rt.bytesMutFrom(Ops.take(ops, rt.usizeRem(n, 6))); const first: rt.u8 = getU8Checked$Checked_BytesMut(source); @@ -100,18 +106,18 @@ export function bytesMut(data: rt.ByteSlice, out: rt.ByteVec): void { } const tail: rt.BytesMut = rt.bytesMutFrom(rt.byteSliceRange(rt.byteSliceFrom(Uint8Array.of(116, 97, 105, 108)), 0)); rt.byteVecPush(out, rt.byteSliceEq(rt.bytesMutView(buf), rt.bytesMutView(tail)) ? 1 : 0); - const _171: rt.BytesMut = rt.bytesMutFrom(rt.bytesMutView(buf)); - const _173: rt.ByteSlice = rt.byteSliceRange(rt.bytesMutView(buf), 0); - rt.byteVecPush(out, rt.byteSliceEq(rt.bytesMutView(_171), _173) ? 1 : 0); - const _184: rt.usize = buf.length; - const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(rt.bytesMutView(buf), f), (f: rt.Formatter) => rt.usizeDisplay(_184, f)]; + const _179: rt.BytesMut = rt.bytesMutFrom(rt.bytesMutView(buf)); + const _181: rt.ByteSlice = rt.byteSliceRange(rt.bytesMutView(buf), 0); + rt.byteVecPush(out, rt.byteSliceEq(rt.bytesMutView(_179), _181) ? 1 : 0); + const _192: rt.usize = buf.length; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(rt.bytesMutView(buf), f), (f: rt.Formatter) => rt.usizeDisplay(_192, f)]; rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0], " ", args2[1], "\n"]))); - for (const _195 of pieces) { - const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(rt.bytesMutView(_195), f)]; + for (const _203 of pieces) { + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(rt.bytesMutView(_203), f)]; rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args4[0], "\n"]))); } - for (const _214 of frozen) { - const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(_214, f)]; + for (const _222 of frozen) { + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(_222, f)]; rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args6[0], "\n"]))); } rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rt.bytesMutToByteVec(buf))); @@ -221,6 +227,37 @@ export function read$BytesMut(buf: rt.BytesMut, n: rt.usize): rt.u128 { return ((dst[0] << 16) | (dst[1] << 8) | dst[2]) as rt.u128; } +/** + * `reserve` at the edges of `rt.BytesMut`'s limit for storage that was shared, 512 MiB + * counting what it read past: a vector of its own grows as `Vec` does on either side of + * it, and shared storage grows up to it. Only the inputs `caller.ts` names reach these, + * as each allocates that much. + */ +export function reserves(data: rt.ByteSlice, out: rt.ByteVec): void { + if (data.length === 6) { + if (data.data[data.start] === 101) { + if (data.data[data.start + 1] === 100) { + if (data.data[data.start + 2] === 103) { + if (data.data[data.start + 3] === 101) { + const kind: rt.u8 = data.data[data.start + 4]; + const read: rt.u8 = data.data[data.start + 5]; + const buf: rt.BytesMut = rt.bytesMutFrom(rt.byteSliceRange(rt.byteSliceFrom(Uint8Array.of(101, 100, 103, 101, 115)), 0)); + const read2: rt.usize = rt.usizeRem(read as rt.usize, 5); + rt.bytesMutAdvance(buf, read2); + const head: rt.BytesMut | undefined = then$bool_BytesMut_reserves_closure0(rt.u8Rem(kind, 2) === 1, (): rt.BytesMut => { + return rt.bytesMutSplitTo(buf, 0); + }); + rt.bytesMutReserve(buf, rt.usizeSub(rt.usizeSub(rt.usizeAdd(536870912, rt.u8Rem(rt.u8Div(kind, 2), 2) as rt.usize), read2), buf.length)); + rt.bytesMutExtend(buf, rt.byteSliceFrom(Uint8Array.of(33))); + rt.byteVecExtendFromSlice(out, rt.bytesMutView(buf)); + rt.byteVecPush(out, head !== undefined ? 1 : 0); + } + } + } + } + } +} + /** * The same reads off a `Bytes`, a `BytesMut`, and a buffer in pieces: each scalar, and * what remains. diff --git a/ts/fixtures/stock/expected/core/bool.ts b/ts/fixtures/stock/expected/core/bool.ts new file mode 100644 index 000000000..8e8d6fce4 --- /dev/null +++ b/ts/fixtures/stock/expected/core/bool.ts @@ -0,0 +1,12 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; + +export function then$bool_BytesMut_reserves_closure0(self: boolean, f: () => rt.BytesMut): rt.BytesMut | undefined { + if (!self) { + return undefined; + } + return f(); +} + +//# sourceMappingURL=bool.ts.map diff --git a/ts/fixtures/stock/expected/harness.ts b/ts/fixtures/stock/expected/harness.ts index 2455a9e88..c1d739567 100644 --- a/ts/fixtures/stock/expected/harness.ts +++ b/ts/fixtures/stock/expected/harness.ts @@ -1,7 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { bytesMut, reads, writes, edits } from "./buf.ts"; +import { bytesMut, reserves, reads, writes, edits } from "./buf.ts"; import * as Owner from "./harness.Owner.ts"; /** @@ -9,7 +9,7 @@ import * as Owner from "./harness.Owner.ts"; * moves no other. */ export function cases(): Array<(a0: rt.ByteSlice, a1: rt.ByteVec) => void> { - return [slices, made, events, random, bytesMut, reads, writes, edits]; + return [slices, made, events, random, bytesMut, reads, writes, edits, reserves]; } /** Run one case. */ diff --git a/ts/fixtures/stock/src/buf.rs b/ts/fixtures/stock/src/buf.rs index f8478c3fb..085b91632 100644 --- a/ts/fixtures/stock/src/buf.rs +++ b/ts/fixtures/stock/src/buf.rs @@ -24,20 +24,21 @@ pub fn bytes_mut(data: &[u8], out: &mut Vec) { } 5 => buf.truncate(n % (buf.len() + 2)), 6 => buf.resize(n % 40, n as u8), - // Past what a buffer holds, by overflowing `usize` or not: each panics. Past - // `usize::MAX`, by the kind of storage, so into a handle sure of its kind: a new - // one, a vector, or one split, shared. - 7 => match n % 4 { - 0 => { - let mut fresh = BytesMut::from(ops.take(n % 6)); - if n % 8 == 0 { - pieces.push(fresh.split_to(0)); - } - fresh.reserve(usize::MAX - n); - } - 1 => buf.reserve(isize::MAX as usize - buf.len() + 1), - _ => buf.reserve(n), - }, + // Past what a vector holds, by overflowing `usize` or not, counting what it read + // past: each panics as `Vec` does. Storage that was shared throws there instead, + // so these reserve into a vector of their own. + 7 if n % 2 == 0 => { + let mut fresh = BytesMut::from(ops.take(n % 6)); + let read = n % (fresh.len() + 1); + fresh.advance(read); + let len = fresh.len(); + fresh.reserve(match n % 3 { + 0 => usize::MAX - n, + 1 => isize::MAX as usize - len + 1, + _ => isize::MAX as usize + 1 - read - len, + }); + } + 7 => buf.reserve(n), 8 => { if let Some(piece) = pieces.pop() { buf.unsplit(piece); @@ -121,6 +122,26 @@ fn read(buf: &mut B, n: usize) -> u128 { } } +/// `reserve` at the edges of `rt.BytesMut`'s limit for storage that was shared, 512 MiB +/// counting what it read past: a vector of its own grows as `Vec` does on either side of +/// it, and shared storage grows up to it. Only the inputs `caller.ts` names reach these, +/// as each allocates that much. +pub fn reserves(data: &[u8], out: &mut Vec) { + const LIMIT: usize = 1 << 29; + let &[b'e', b'd', b'g', b'e', kind, read] = data else { + return; + }; + let mut buf = BytesMut::from(&b"edges"[..]); + let read = usize::from(read) % 5; + buf.advance(read); + let head = (kind % 2 == 1).then(|| buf.split_to(0)); + let past = usize::from(kind / 2 % 2); + buf.reserve(LIMIT + past - read - buf.len()); + buf.put_slice(b"!"); + out.extend_from_slice(&buf); + out.push(head.is_some() as u8); +} + /// A buffer of the crate's own, in pieces: `Buf`'s provided methods read across them. struct Pieces { /// None empty, so `chunk` is empty only once nothing remains, as `Buf` requires. diff --git a/ts/fixtures/stock/src/harness.rs b/ts/fixtures/stock/src/harness.rs index 3be072f00..61c241f83 100644 --- a/ts/fixtures/stock/src/harness.rs +++ b/ts/fixtures/stock/src/harness.rs @@ -19,6 +19,7 @@ fn cases() -> Vec { crate::buf::reads, crate::buf::writes, crate::buf::edits, + crate::buf::reserves, ] } diff --git a/ts/runtime/rt/bytes.ts b/ts/runtime/rt/bytes.ts index c20ee7f59..4bf5cef85 100644 --- a/ts/runtime/rt/bytes.ts +++ b/ts/runtime/rt/bytes.ts @@ -23,6 +23,16 @@ import type { usize } from "./int.ts"; /** `isize::MAX` on wasm32, the most bytes an allocation holds. */ const ISIZE_MAX = 0x7fffffff; +/** + * The most bytes, counting those read past, that a `BytesMut` whose storage was shared or + * taken reaches before `reserve` throws. Below it, `bytes`' storage stays under 1 GiB, so + * growing it panics nowhere, whichever handles dropped. + */ +const BYTES_MUT_UNSURE_LIMIT = 0x20000000; + +/** The furthest a `bytes` vector reads past its front before it becomes shared storage, on wasm32. */ +const MAX_VEC_POS = 0x7ffffff; + /** `bytes::Bytes`. */ export type Bytes = ByteSlice; @@ -202,35 +212,35 @@ function widen(read: Uint8Array, size: number, signed: boolean): Uint8Array { /** * `bytes::BytesMut`: `length` bytes of `data` from `start`, with room up to `cap` before - * the bytes another handle or a frozen `Bytes` holds. Its capacity isn't `bytes`', which - * depends on whether the other handles of its storage dropped, so translation refuses - * what reads it. + * the bytes another handle or a frozen `Bytes` holds. Once its storage was shared or + * taken from a `Bytes`, its capacity isn't `bytes`', which depends on whether other + * handles of that storage dropped, so translation refuses what reads it. */ export class BytesMut { data: Uint8Array; + /** How far into `data` it starts, which is at least as far as `bytes`' handle reads past. */ start: number; length: number; cap: number; /** - * Whether its storage is `bytes`' shared kind, which `split_to` makes and whose growth - * panics apart from a vector's. `undefined` where `bytes`' kind depends on whether other - * handles of its storage dropped, as once shared storage grows. + * Whether it is a vector that was never shared nor taken, whose `start` and `cap` are + * `bytes`' own, so it grows and panics as `Vec` does. */ - shared: boolean | undefined; + exact: boolean; - constructor(data: Uint8Array, start: number, length: number, cap: number, shared: boolean | undefined) { + constructor(data: Uint8Array, start: number, length: number, cap: number, exact: boolean) { this.data = data; this.start = start; this.length = length; this.cap = cap; - this.shared = shared; + this.exact = exact; } } /** `BytesMut::with_capacity`, `new` of 0. */ export function bytesMutWithCapacity(capacity: usize): BytesMut { if (capacity > ISIZE_MAX) panic("capacity overflow"); - return new BytesMut(bytes(capacity), 0, 0, capacity, false); + return new BytesMut(bytes(capacity), 0, 0, capacity, true); } /** `BytesMut::zeroed`. */ @@ -240,7 +250,7 @@ export function bytesMutZeroed(len: usize): BytesMut { return b; } -/** A `BytesMut` of a copy of `s`: `From<&[u8]>`, `From<&str>`, `From`, and `Clone`. */ +/** A `BytesMut` of a copy of `s`: `From<&[u8]>`, `From<&str>`, and `Clone`. */ export function bytesMutFrom(s: ByteSlice): BytesMut { const b = bytesMutWithCapacity(s.length); copyBytes(b.data, 0, s.data, s.start, s.length); @@ -248,10 +258,13 @@ export function bytesMutFrom(s: ByteSlice): BytesMut { return b; } -/** `BytesMut::from` a `Bytes`, whose storage it takes where no other handle holds it. */ +/** + * `BytesMut::from` a `Bytes`, whose storage `bytes` takes where no other handle holds it, + * reading past as much of it as the `Bytes` did. + */ export function bytesMutFromBytes(s: Bytes): BytesMut { - const b = bytesMutFrom(s); - b.shared = undefined; + const b = new BytesMut(bytes(s.start + s.length), s.start, s.length, s.length, false); + copyBytes(b.data, s.start, s.data, s.start, s.length); return b; } @@ -270,44 +283,59 @@ export function bytesMutToByteVec(b: BytesMut): ByteVec { return byteSliceToByteVec(bytesMutView(b)); } -/** `BytesMut::reserve`: room for `additional` more bytes, panicking as `bytes` does past what a buffer holds. */ +/** + * `BytesMut::reserve`: room for `additional` more bytes. A vector grows and panics as `Vec` + * does, counting the bytes it read past. Storage that was shared or taken throws past + * `BYTES_MUT_UNSURE_LIMIT`, where `bytes`' panic depends on which handles dropped. + */ export function bytesMutReserve(b: BytesMut, additional: usize): void { + if (!b.exact && b.start + b.length + additional > BYTES_MUT_UNSURE_LIMIT) { + throw new Error( + `rust2-ts: \`BytesMut::reserve\` past ${BYTES_MUT_UNSURE_LIMIT} bytes of storage that was shared, whose panic depends on whether other handles of it dropped`, + ); + } if (additional <= b.cap - b.length) return; const needed = b.length + additional; - // A vector's own storage moves its bytes to the front where that alone makes the room. - if (!b.shared && b.start >= b.length && b.cap - b.length + b.start >= additional) { + if (!b.exact) { + // Never before `start`, which stays as far as `bytes`' handle reads past or further. + const cap = Math.max(needed, b.cap * 2, 8); + const data = bytes(b.start + cap); + copyBytes(data, b.start, b.data, b.start, b.length); + b.data = data; + b.cap = cap; + return; + } + // Its bytes move to the front where that alone makes the room. + if (b.start >= b.length && b.cap - b.length + b.start >= additional) { b.data.copyWithin(0, b.start, b.start + b.length); b.cap += b.start; b.start = 0; return; } - if (needed > 0xffffffff) { - if (b.shared === undefined) { - throw new Error("rust2-ts: `BytesMut::reserve` past `usize::MAX`, whose panic depends on whether other handles of its storage dropped"); - } - if (b.shared) panic("overflow"); - } - // A vector grows past its offset, where a shared one starts afresh. - if ((b.shared ? needed : b.start + needed) > ISIZE_MAX) panic("capacity overflow"); - const cap = Math.max(needed, b.cap * 2, 8); - const data = bytes(cap); - copyBytes(data, 0, b.data, b.start, b.length); + // `Vec::reserve` of the vector from the front of the storage. + const required = b.start + needed; + const total = Math.max((b.start + b.cap) * 2, required, 8); + if (required > ISIZE_MAX || total > ISIZE_MAX) panic("capacity overflow"); + const data = bytes(total); + copyBytes(data, b.start, b.data, b.start, b.length); b.data = data; - b.start = 0; - b.cap = cap; - // Shared storage stays shared if no other handle held it, and becomes a vector if one did. - if (b.shared) b.shared = undefined; + b.cap = total - b.start; } /** * `BufMut::put` of a `Bytes` or a `BytesMut`. At zero capacity `bytes` takes its storage, - * of a kind that depends on its handles, and a vector's capacity is only approximate here. + * reading past as much of it as it did. */ export function bytesMutPutStorage(b: BytesMut, s: Bytes): void { if (s.length === 0) return; - const vector = b.shared === false; + if (b.exact ? b.cap === 0 : b.length === 0) { + const start = Math.max(b.start, s.start); + b.data = bytes(start + s.length); + b.start = start; + b.cap = s.length; + b.exact = false; + } bytesMutExtend(b, s); - if (vector) b.shared = undefined; } /** `BytesMut::extend_from_slice`, and `BufMut::put_slice`. */ @@ -363,11 +391,11 @@ export function bytesMutResize(b: BytesMut, len: usize, value: number): void { /** `BytesMut::split_to`: the first `at` bytes, sharing the storage, leaving the rest. */ export function bytesMutSplitTo(b: BytesMut, at: usize): BytesMut { if (at > b.length) panic(`split_to out of bounds: ${at} <= ${b.length}`); - const head = new BytesMut(b.data, b.start, at, at, true); + const head = new BytesMut(b.data, b.start, at, at, false); b.start += at; b.length -= at; b.cap -= at; - b.shared = true; + b.exact = false; return head; } @@ -378,11 +406,11 @@ export function bytesMutUnsplit(b: BytesMut, other: BytesMut): void { b.start = other.start; b.length = other.length; b.cap = other.cap; - b.shared = other.shared; + b.exact = other.exact; return; } if (other.cap === 0) return; - if (b.shared && other.shared && b.data === other.data && b.start + b.length === other.start) { + if (!b.exact && !other.exact && b.data === other.data && b.start + b.length === other.start) { b.length += other.length; b.cap += other.cap; return; @@ -396,6 +424,7 @@ export function bytesMutAdvance(b: BytesMut, cnt: usize): void { b.start += cnt; b.length -= cnt; b.cap -= cnt; + if (b.start > MAX_VEC_POS) b.exact = false; } /** `Buf::get_*` of `BytesMut`: its first `n` bytes, the other way around if `le`, read past. */ diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index 51405949e..0e0e0fd3e 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -593,6 +593,8 @@ fn stock() { String::from_utf8_lossy(&output.stderr) ); snapshot("stock", &out); + // A hand-written caller, which names inputs the generated ones never reach. + std::fs::copy(fixture("stock").join("caller.ts"), out.join("caller.ts")).unwrap(); typecheck(&out); - differential("stock-fixture", &["--config", GETRANDOM], &out, "harness.ts", 5_000); + differential("stock-fixture", &["--config", GETRANDOM], &out, "caller.ts", 5_000); } diff --git a/ts/tests/reserve.ts b/ts/tests/reserve.ts new file mode 100644 index 000000000..b58e2b211 --- /dev/null +++ b/ts/tests/reserve.ts @@ -0,0 +1,43 @@ +// A `BytesMut` whose storage was shared throws a rust2-ts error on a reserve past 512 MiB, +// counting what it read past, which native Rust can't show: there `bytes` panics with +// "overflow" or "capacity overflow", or grows, by whether other handles of it dropped. +// +// usage: node reserve.ts + +import { strict as assert } from "node:assert"; + +import * as rt from "../runtime/rt.ts"; + +const LIMIT = 2 ** 29; +const unsure = (f: () => void) => assert.throws(f, (e: Error) => !(e instanceof rt.Panic) && e.message.startsWith("rust2-ts: ")); +const from = (s: string) => rt.bytesMutFrom(rt.stringAsBytes(s)); + +// One past the limit, counting the two bytes read past. +const edge = from("edges"); +rt.bytesMutAdvance(edge, 2); +const head = rt.bytesMutSplitTo(edge, 0); +unsure(() => rt.bytesMutReserve(edge, LIMIT + 1 - 2 - 3)); +// Its sibling, from the same place, reaches it exactly. +rt.bytesMutReserve(head, LIMIT - 2); + +// Uniquely held after the split, `bytes` panics with "overflow", and held, "capacity overflow". +const unique = from("ab"); +rt.bytesMutSplitTo(unique, 1); +unsure(() => rt.bytesMutReserve(unique, 0xffffffff - 1)); + +// Grown, split again, and grown within what it holds here, `bytes` may have moved it into a vector. +const grown = from("x"); +rt.bytesMutSplitTo(grown, 0); +rt.bytesMutReserve(grown, 1); +rt.bytesMutSplitTo(grown, 0); +rt.bytesMutReserve(grown, 2); +unsure(() => rt.bytesMutReserve(grown, 0xffffffff)); + +// Taken from a `Bytes`, the same. +unsure(() => rt.bytesMutReserve(rt.bytesMutFromBytes(rt.stringAsBytes("x")), LIMIT)); + +// A vector of its own panics as `Vec` does past `isize::MAX`. +assert.throws( + () => rt.bytesMutReserve(from("x"), 0xffffffff), + (e: Error) => e instanceof rt.Panic && e.message === "capacity overflow", +); diff --git a/ts/tests/runtime.rs b/ts/tests/runtime.rs index c6c6a3c2b..e043d312d 100644 --- a/ts/tests/runtime.rs +++ b/ts/tests/runtime.rs @@ -36,6 +36,20 @@ fn once_recursive() { assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); } +/// A `BytesMut` whose storage was shared throws on a reserve past its limit, which +/// `reserve.ts` checks. +#[test] +fn bytes_mut_reserve() { + let script = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("reserve.ts"); + let output = Command::new("node") + .arg(script) + .output() + .expect("running node, which the dev shell provides"); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); +} + /// The runtime's B-tree runs `btree.ts`'s script of random operations as std's does. #[test] fn btree_script() { From 07f093c856bd665a6a17e1ee53d1014bcf445dc7 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:47:32 -0700 Subject: [PATCH 9/9] chore(quest): name the std calls bytes' getters need in ts-unsafe Co-Authored-By: Claude Opus 5.5 --- quest/m3/ts-unsafe.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/quest/m3/ts-unsafe.md b/quest/m3/ts-unsafe.md index 734e363c4..5ffab38ef 100644 --- a/quest/m3/ts-unsafe.md +++ b/quest/m3/ts-unsafe.md @@ -41,6 +41,9 @@ none of its own `unsafe`. - A slice's pointer cast to an array's of its length, `*(s as *const [u8] as *const [u8; N])`, which `bytes`' `Buf::get_u16` and wider read a crate's own buffer through ([#222](https://github.com/kixelated/rust2/pull/222)): the bytes keep their type, so - this reinterprets nothing. Those getters also need `<[u8]>::get` of a range. + this reinterprets nothing. Those getters also need `<[u8]>::get` and `get_mut` of a + range, and each integer's `from_le_bytes` and `from_ne_bytes`, and `chunks_vectored` + needs `std::io::IoSlice`: 184 of moq-net's 197 refusals in `bytes`, the rest being 12 + of [`f32`](/quest/m3/ts-f32.md) and one of [`&mut &[u8]`](/quest/m3/ts-mut-ref.md). Public API: the translator's output.