diff --git a/quest/m2/ts-model/README.md b/quest/m2/ts-model/README.md index 11ac8c40d..c2470cc8b 100644 --- a/quest/m2/ts-model/README.md +++ b/quest/m2/ts-model/README.md @@ -51,5 +51,4 @@ Public API: the translator's output for moq-net's model. - [The rest of std the model reaches](/quest/m2/ts-model/std-rest.md) - `Vec` and `VecDeque` capacity, and `RandomState` - [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 4199bf1cf..e7c5b27f2 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -17,6 +17,8 @@ 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 +- [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 new file mode 100644 index 000000000..1ad61442c --- /dev/null +++ b/quest/m3/ts-bytes-capacity.md @@ -0,0 +1,25 @@ +# [M] The capacity of a BytesMut + +## Goal + +[rust2-ts](/ts/README.md) translates `BytesMut::capacity`, `split_off`, `try_reclaim`, +`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 + +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. 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. +- Measure the count's cost on the codec's [TS benchmark](/ts/README.md#bench). + +Public API: the translator's output. 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..5ffab38ef 100644 --- a/quest/m3/ts-unsafe.md +++ b/quest/m3/ts-unsafe.md @@ -38,5 +38,12 @@ 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` 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. 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 44b3f0459..37085ab69 100644 --- a/ts/README.md +++ b/ts/README.md @@ -114,6 +114,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 @@ -308,9 +309,32 @@ 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. `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` + 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. 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 + `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 `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 @@ -602,7 +626,11 @@ 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. `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/reject/census.md b/ts/fixtures/reject/census.md index 005315035..397a6e972 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: 97 +- Function instances: 110 - Generic functions no instance reached, lowered over their type parameters: 7 ## By construct @@ -17,56 +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: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: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:517: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:560: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:536: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 | `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: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: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: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:662: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:582: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: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: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:496: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:554: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: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: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:604:1 | +| 1 | union `_`, whose fields overlap in `_` and `f64`, which JS keeps apart | fixtures/reject/src/lib.rs:640:1 | ## By API @@ -82,24 +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:630: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: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: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:589:11 | -| 2 | `std::vec::IntoIter` | fixtures/reject/src/lib.rs:444: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:604: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 | @@ -108,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:662:11 | -| 1 | `Span2` | fixtures/reject/src/lib.rs:630: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:506:30 | -| 1 | `Waiting` | fixtures/reject/src/lib.rs:517: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:496:26 | -| 1 | `dyn Keyed` | fixtures/reject/src/lib.rs:554: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:454: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: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: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:587: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:536:12 | -| 1 | `std::sync::Weak` | fixtures/reject/src/lib.rs:470: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 | @@ -144,53 +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:479: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:444: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: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: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:560: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: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: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: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: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: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: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: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: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: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: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:496: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:554: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:618: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 | @@ -202,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: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: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:560: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: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: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 @@ -230,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: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: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` @@ -262,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: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: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
@@ -306,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: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: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: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: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
@@ -346,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 @@ -378,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: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:553:2: `Waiting>` is not supported: its field `poll` is `Poll`, typed `rt.Poll`, whose `Pending` would be `rt.OuterPending` as `Poll>`
@@ -396,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:560: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
@@ -408,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: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:572:12: `std::sync::Mutex::::get_mut` with a mutable reference to a value JS copies, which its mapping would copy
@@ -424,9 +436,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:485:4: `f64::mul_add`, which rounds once, where JS would round twice
@@ -450,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: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:613:27: a cast from a pointer to `u32` to one to `u8`, which reads the bytes of one type as another
@@ -468,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:662: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
@@ -492,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:582: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
@@ -504,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: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: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: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: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:638: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: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:682:10: a raw pointer to `(u32, u32)` in an element, a payload, or a union field, which is not supported yet
@@ -534,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:496: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
@@ -546,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:554: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
@@ -570,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:653: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:618: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
@@ -606,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:604: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 8e55fd4cf..cbc26b2ea 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -54,39 +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: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: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 -`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 +`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 a44111a09..909a01d4e 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -425,6 +425,42 @@ 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() +} + +/// `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 1ad180351..b55342865 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -52,6 +52,8 @@ roots = [ "ok_passed", "places_equal", "owned_bytes", + "bytes_mut_capacity", + "bytes_mut_put", "fma", "float_printed", "weak_object", 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.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..0a25eb402 --- /dev/null +++ b/ts/fixtures/stock/expected/buf.ts @@ -0,0 +1,503 @@ +// 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"; +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[] = []; + 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) { + if (!(rt.usizeRem(n, 2) === 0)) { + rt.bytesMutReserve(buf, n); + } else { + const fresh: rt.BytesMut = rt.bytesMutFrom(Ops.take(ops, rt.usizeRem(n, 6))); + 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, _80); + } + } else if (_20 === 8) { + 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))); + } 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 _115: rt.BytesMut = rt.bytesMutSplitTo(buf2, buf2.length); + pieces.push(_115); + } else if (_20 === 13) { + 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 _136: rt.ByteSlice = rt.bytesMutView(buf); + rt.idx(_136, at); + _136.data[_136.start + at] = _136.data[_136.start + at] ^ 255; + } + 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 _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); + rt.bytesMutPutWord(buf, first, 1, false); + rt.bytesMutPutStorage(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 _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 _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 _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))); +} + +/** 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; +} + +/** + * `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. + */ +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 vec: rt.ByteVec = new rt.ByteVec(); + 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); + 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.bytesMutPutStorage(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/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/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..c1d739567 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, reserves, 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, reserves]; } /** 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..085b91632 --- /dev/null +++ b/ts/fixtures/stock/src/buf.rs @@ -0,0 +1,339 @@ +//! `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 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); + } + } + 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() + } + } +} + +/// `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. + 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, chunk by chunk. + let mut vec = Vec::new(); + vec.put(Pieces::new(input, cut)); + out.extend_from_slice(&vec); + 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..61c241f83 100644 --- a/ts/fixtures/stock/src/harness.rs +++ b/ts/fixtures/stock/src/harness.rs @@ -10,7 +10,17 @@ 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, + crate::buf::reserves, + ] } /// 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 5a6e2b243..a6667d3a6 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -566,7 +566,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..4bf5cef85 100644 --- a/ts/runtime/rt/bytes.ts +++ b/ts/runtime/rt/bytes.ts @@ -1,9 +1,38 @@ -// `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; + +/** + * 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; @@ -61,3 +90,409 @@ 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. 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) { + 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"); + 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. 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 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. + */ + exact: boolean; + + constructor(data: Uint8Array, start: number, length: number, cap: number, exact: boolean) { + this.data = data; + this.start = start; + this.length = length; + this.cap = cap; + 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, true); +} + +/** `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>`, 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; +} + +/** + * `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 = 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; +} + +/** 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. 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; + 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; + } + // `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.cap = total - b.start; +} + +/** + * `BufMut::put` of a `Bytes` or a `BytesMut`. At zero capacity `bytes` takes its storage, + * reading past as much of it as it did. + */ +export function bytesMutPutStorage(b: BytesMut, s: Bytes): void { + if (s.length === 0) return; + 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); +} + +/** `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, false); + b.start += at; + b.length -= at; + b.cap -= at; + b.exact = false; + 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.exact = other.exact; + return; + } + if (other.cap === 0) return; + if (!b.exact && !other.exact && 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; + 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. */ +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 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..ca5a30f76 100644 --- a/ts/src/census.rs +++ b/ts/src/census.rs @@ -141,7 +141,9 @@ const VERBATIM: &[&str] = &[ ".await", "?", "Binary", + "BufMut::put", "Bytes::from_owner", + "BytesMut", "Copy", "Debug", "DebugList::entries", 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 a24e8021c..d929a7898 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -134,6 +134,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 64127fede..fe7c29e8c 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)>, @@ -226,28 +226,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)) } } @@ -894,7 +896,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, } @@ -1147,6 +1150,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. @@ -1485,6 +1489,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..b64c547e2 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,127 @@ 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()), + }) +} + +/// 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`. +/// `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() => 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(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 +351,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 +380,233 @@ 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 +/// 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); + 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 { + 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. + 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)); + } + // 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() + .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(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 +665,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)))) } 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 9141452bd..816147711 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)); +} + /// A lazy thread-local's first value comes as wasm32's `LazyStorage` makes it, which /// `local.ts` checks. #[test]