From cad8954760b0042608ab470c32b12b85e36111d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?JasonXuDeveloper=20-=20=E5=82=91?= Date: Thu, 19 Nov 2026 14:01:55 +1100 Subject: [PATCH 1/3] refactor(rust): keep codec fragments in one module Include the codec files in their original order to preserve Rust codegen-unit assignment and the scope of the map macro. Retain the shared fixed-width set writer from #354. Refs #248 --- runtimes/rust/src/impls.rs | 323 +++++++++++++++++++++++++-- runtimes/rust/src/impls/maps.rs | 83 ------- runtimes/rust/src/impls/numbers.rs | 5 +- runtimes/rust/src/impls/sequences.rs | 225 +------------------ runtimes/rust/src/impls/sets.rs | 10 - runtimes/rust/src/impls/strings.rs | 7 +- runtimes/rust/src/impls/tuples.rs | 7 +- runtimes/rust/src/impls/wrappers.rs | 8 +- 8 files changed, 308 insertions(+), 360 deletions(-) diff --git a/runtimes/rust/src/impls.rs b/runtimes/rust/src/impls.rs index e32d9e2c5..058572b75 100644 --- a/runtimes/rust/src/impls.rs +++ b/runtimes/rust/src/impls.rs @@ -1,29 +1,194 @@ -//! Trait implementations for primitives, strings, wrappers, tuples and the standard collections. +//! [`NinoRead`] and [`NinoWrite`] for primitives, strings, `Option`, `Box`, tuples and the std collections. use core::any::Any; +use core::hash::{BuildHasher, Hash}; +use std::collections::{hash_map, BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; use crate::defer::Step; use crate::error::{Error, ErrorKind, Result}; use crate::reader::Reader; -use crate::traits::NinoRead; - -mod maps; -mod numbers; -mod sequences; -mod sets; -mod strings; -mod tuples; -mod wrappers; - -pub(crate) use maps::map; -pub(crate) use sequences::{ - grow_fixed, prefetches, read_each, read_each_into, read_fixed, read_fixed_into, write_counted_fixed, write_fixed, - write_prefetched, -}; -#[cfg(feature = "indexmap")] -pub(crate) use sets::write_set; -#[cfg(feature = "indexmap")] -pub(crate) use sets::{fill_set, FillSet}; +use crate::traits::{NinoRead, NinoWrite}; +use crate::writer::Writer; + +fn vec_item(v: &mut dyn Any, i: usize) -> Option<&mut dyn Any> { + v.downcast_mut::>()?.get_mut(i).map(|x| x as &mut dyn Any) +} + +fn deque_item(v: &mut dyn Any, i: usize) -> Option<&mut dyn Any> { + v.downcast_mut::>()?.get_mut(i).map(|x| x as &mut dyn Any) +} + +/// Reads `count` elements one by one into a `Vec` (deferred bodies in them reached by `index`). +#[inline] +fn read_into_vec( + r: &mut Reader<'_>, + count: usize, + index: fn(&mut dyn Any, usize) -> Option<&mut dyn Any>, +) -> Result> { + let mut values = Vec::with_capacity(r.capacity::(count)); + for i in 0..count { + if T::MAY_DEFER { + let mark = r.defer_mark(); + values.push(T::read(r)?); + r.defer_trail(mark, Step::Index(index, i)); + } else { + values.push(T::read(r)?); + } + } + Ok(values) +} + +/// [`NinoRead::read_many`]'s default: each element in turn. +#[inline] +pub(crate) fn read_each(r: &mut Reader<'_>, count: usize) -> Result> { + read_into_vec(r, count, vec_item::) +} + +/// [`NinoRead::read_many_into`]'s default: the first elements read into, by index, the rest read new. +#[inline] +pub(crate) fn read_each_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { + if values.is_empty() { + // Nothing to read into: the plain read, its allocation budget included. + *values = T::read_many(r, count)?; + return Ok(()); + } + values.truncate(count); + for (i, v) in values.iter_mut().enumerate() { + if T::MAY_DEFER { + let mark = r.defer_mark(); + v.read_into(r)?; + r.defer_trail(mark, Step::Index(vec_item::, i)); + } else { + v.read_into(r)?; + } + } + let have = values.len(); + // `have <= count`: no wrap. + values.reserve(r.capacity::(count.wrapping_sub(have))); + for i in have..count { + if T::MAY_DEFER { + let mark = r.defer_mark(); + values.push(T::read(r)?); + r.defer_trail(mark, Step::Index(vec_item::, i)); + } else { + values.push(T::read(r)?); + } + } + Ok(()) +} + +/// [`NinoRead::read_many_into`]'s default for a fixed-size type: [`read_fixed`] into the `Vec`'s buffer. +#[inline] +pub(crate) fn read_fixed_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { + if values.capacity() < count { + // Not enough room: the plain read, its allocation budget included. + *values = read_fixed(r, count)?; + return Ok(()); + } + let size = count.checked_mul(T::FIXED_SIZE).ok_or_else(Error::too_large)?; + let bytes = r.take(size)?; + crate::simd::decode_block_into(values, bytes.chunks_exact(T::FIXED_SIZE), T::decode_fixed) +} + +/// [`NinoRead::read_many`]'s default for a fixed-size type: the elements' bytes with one length check, then +/// [`NinoRead::decode_fixed`] on each. +#[inline] +pub(crate) fn read_fixed(r: &mut Reader<'_>, count: usize) -> Result> { + let size = count.checked_mul(T::FIXED_SIZE).ok_or_else(Error::too_large)?; + let capacity = r.capacity::(count); + let bytes = r.take(size)?; + if capacity < count { + return grow_fixed(bytes.chunks_exact(T::FIXED_SIZE), capacity, T::decode_fixed); + } + crate::simd::decode_block(bytes.chunks_exact(T::FIXED_SIZE), T::decode_fixed) +} + +/// A block of fixed-size elements past the allocation budget ([`Reader::capacity`]): `capacity` of them allocated up +/// front, the `Vec` grown for the rest. +#[cold] +#[inline(never)] +pub(crate) fn grow_fixed( + chunks: impl Iterator, + capacity: usize, + decode: impl Fn(C) -> Result, +) -> Result> { + let mut values = Vec::with_capacity(capacity); + for c in chunks { + values.push(decode(c)?); + } + Ok(values) +} + +/// The elements a prefetching loop runs ahead: at element `i`, element `i + 2 * PREFETCH_AHEAD`'s targets are asked +/// for ([`NinoWrite::prefetch`]), and element `i + PREFETCH_AHEAD`'s targets' own ([`NinoWrite::prefetch_members`], +/// their lines asked for a batch earlier). The same as the Go runtime's. +const PREFETCH_AHEAD: usize = 8; + +/// Whether a slice of `len` elements is written prefetching ahead: at least 512 elements, and more estimated data (an +/// element's size and the bytes it points to, [`NinoWrite::PREFETCH_BYTES`]) than the last-level cache holds +/// ([`crate::simd::last_level_cache`]). Data that fits is likely in the cache already, where a prefetch per element +/// costs more than it saves. +#[inline] +pub(crate) fn prefetches(len: usize) -> bool { + len >= 512 && outgrows_cache(len, core::mem::size_of::().saturating_add(T::PREFETCH_BYTES)) +} + +/// Whether `len` elements of `bytes` each are more than the last-level cache holds: out of line, so that a short +/// list's code is one compare. +#[cold] +#[inline(never)] +fn outgrows_cache(len: usize, bytes: usize) -> bool { + len.saturating_mul(bytes) > crate::simd::last_level_cache() +} + +/// [`NinoWrite::write_many`] for a long slice of elements that point elsewhere ([`prefetches`]): the same bytes, +/// each element's targets asked for [`PREFETCH_AHEAD`] elements before they are written, in two stages. Out of line, +/// so that the loop of every other slice stays as it was. +#[inline(never)] +pub(crate) fn write_prefetched<'a, T: NinoWrite>(values: &'a [T], w: &mut Writer<'a>) -> Result<()> { + for (i, v) in values.iter().enumerate() { + // `i < values.len() <= isize::MAX`: the sums cannot wrap. + if let Some(ahead) = values.get(i.wrapping_add(2 * PREFETCH_AHEAD)) { + ahead.prefetch(); + } + if let Some(next) = values.get(i.wrapping_add(PREFETCH_AHEAD)) { + next.prefetch_members(); + } + v.write(w)?; + } + Ok(()) +} + +/// [`NinoWrite::write_many`]'s default for a fixed-size type: room for every element, then +/// [`NinoWrite::encode_fixed`] into each element's bytes. +#[inline] +pub(crate) fn write_fixed(values: &[T], w: &mut Writer<'_>) { + if T::FIXED_SIZE <= crate::simd::FIXED_STACK { + crate::simd::extend_fixed(w.buffer(), [], values, T::FIXED_SIZE, T::encode_fixed); + return; + } + let out = w.reserve(values.len().saturating_mul(T::FIXED_SIZE)); + for (v, o) in values.iter().zip(out.chunks_exact_mut(T::FIXED_SIZE)) { + v.encode_fixed(o); + } +} + +/// [`NinoWrite::write_counted`]'s default for a fixed-size type: the length and the elements in one block. +#[inline] +pub(crate) fn write_counted_fixed(values: &[T], w: &mut Writer<'_>) -> Result<()> { + let length = i32::try_from(values.len()).map_err(|_| Error::too_large())?; + if T::FIXED_SIZE <= crate::simd::FIXED_STACK { + crate::simd::extend_fixed(w.buffer(), length.to_le_bytes(), values, T::FIXED_SIZE, T::encode_fixed); + return Ok(()); + } + let out = w.reserve(values.len().saturating_mul(T::FIXED_SIZE).saturating_add(4)); + let Some((head, out)) = out.split_first_chunk_mut::<4>() else { return Ok(()) }; + *head = length.to_le_bytes(); + for (v, o) in values.iter().zip(out.chunks_exact_mut(T::FIXED_SIZE)) { + v.encode_fixed(o); + } + Ok(()) +} /// Reads a value that is hashed or ordered (a dictionary key, a set element): a body deferred inside it could not /// be put in place after the value is in the collection, so that is reported instead. @@ -40,6 +205,78 @@ pub(crate) fn read_key(r: &mut Reader<'_>) -> Result { Ok(value) } +/// Whether a map of `K` and `V` is written as one block of entries ([`write_entries_fixed`]): both fixed-size, an +/// entry small enough for [`crate::simd::extend_fixed_iter`]'s buffer. +const fn entries_fixed(key: usize, value: usize) -> bool { + key != 0 && value != 0 && key.saturating_add(value) <= crate::simd::FIXED_STACK +} + +/// A map's length and entries (fixed-size keys and values, [`entries_fixed`]) in one block: one reservation, each +/// key and value encoded into its bytes, no length check, `Result` or reservation an entry. +#[inline] +fn write_entries_fixed<'e, K, V, I>(entries: I, w: &mut Writer<'_>) -> Result<()> +where + K: NinoWrite + 'e, + V: NinoWrite + 'e, + I: ExactSizeIterator, +{ + let length = i32::try_from(entries.len()).map_err(|_| Error::too_large())?; + let size = K::FIXED_SIZE.saturating_add(V::FIXED_SIZE); + crate::simd::extend_fixed_iter(w.buffer(), length.to_le_bytes(), entries, size, |(k, v), out| { + if let Some((a, b)) = out.split_at_mut_checked(K::FIXED_SIZE) { + k.encode_fixed(a); + v.encode_fixed(b); + } + }); + Ok(()) +} + +/// Whether this target reads a map's fixed-size entries as a slice each, the key and value decoded from it and +/// inserted through the entry API: x86_64, where that measured faster, and 32-bit x86 (the same code). On Arm64 it was +/// 3–4% slower (Neoverse-N2), the entry held in a vector register across the hash call. +const ENTRY_SLICES: bool = cfg!(any(target_arch = "x86", target_arch = "x86_64")); + +/// Whether a map's entries are read with one bounds check each ([`read_entries_fixed`]): keys and values of a fixed +/// size that is also their least, on x86 ([`ENTRY_SLICES`]) and, elsewhere, when an entry is 8 bytes (two `i32`s, an +/// `i64` and a `u32` and `u16`, ...), read as one array. Other entries off x86 keep the generic loop, which reads the +/// same entries in the same order. +const fn entries_fixed_read() -> bool { + (ENTRY_SLICES || K::FIXED_SIZE.saturating_add(V::FIXED_SIZE) == 8) + && K::FIXED_SIZE != 0 + && V::FIXED_SIZE != 0 + && K::MIN_SIZE == K::FIXED_SIZE + && V::MIN_SIZE == V::FIXED_SIZE +} + +/// Reads `count` entries of fixed-size keys and values: one bounds check for each entry's bytes, its key and value +/// decoded from them and handed to `insert`, in order, so a cut entry, a bad value or a repeated key fails at the same +/// entry and with the same error as reading them one at a time. Off x86 an entry is 8 bytes, taken as one array: the +/// key and value stay in general-purpose registers (Neoverse-N2: 0.8% faster than the generic loop). +#[inline] +fn read_entries_fixed( + r: &mut Reader<'_>, + count: usize, + mut insert: impl FnMut(K, V) -> Result<()>, +) -> Result<()> { + if !ENTRY_SLICES { + for _ in 0..count { + let entry = r.array::<8>()?; + // Never `None`: `K::FIXED_SIZE + V::FIXED_SIZE` is 8 here ([`entries_fixed_read`]). + let Some((k, v)) = entry.split_at_checked(K::FIXED_SIZE) else { break }; + insert(K::decode_fixed(k)?, V::decode_fixed(v)?)?; + } + return Ok(()); + } + let size = K::FIXED_SIZE.saturating_add(V::FIXED_SIZE); + for _ in 0..count { + let entry = r.take(size)?; + // Never `None`: an entry is `K::FIXED_SIZE + V::FIXED_SIZE` bytes. + let Some((k, v)) = entry.split_at_checked(K::FIXED_SIZE) else { break }; + insert(K::decode_fixed(k)?, V::decode_fixed(v)?)?; + } + Ok(()) +} + /// A [`Step::Dyn`] from a closure. pub fn dyn_step(f: F) -> Step where @@ -47,3 +284,49 @@ where { Step::Dyn(std::rc::Rc::new(f)) } + +// Keep these files in this module and in their original order. The map macro is shared with IndexMap. +// A module boundary also changes rustc's codegen unit partitioning, even for untouched functions (#248). +include!("impls/numbers.rs"); +include!("impls/strings.rs"); +include!("impls/wrappers.rs"); +include!("impls/sequences.rs"); +include!("impls/sets.rs"); +include!("impls/maps.rs"); +include!("impls/tuples.rs"); + +#[cfg(test)] +#[allow(clippy::indexing_slicing, clippy::arithmetic_side_effects, clippy::unwrap_used)] +mod tests { + use crate::{serialize, NinoWrite, Writer}; + + /// The prefetching loops write the same bytes as their elements written one by one: strings (in batches), + /// optional strings and boxed strings (two stages), with lengths that end the batches and the look-ahead + /// anywhere, and lists too short to look ahead at all. + #[test] + fn prefetched_lists() { + let kinds = ["", "a", "é", "字", "🎉 строка", "crème brûlée"]; + let text = |i: usize| format!("{}{}", kinds[i % kinds.len()], i % 97); + fn check(values: &[T], prefetched: impl for<'a> Fn(&'a [T], &mut Writer<'a>)) { + let mut expected = Vec::new(); + values.iter().for_each(|v| expected.extend(serialize(v).unwrap())); + let mut w = Writer::new(); + prefetched(values, &mut w); + assert_eq!(w.into_vec(), expected, "{} elements", values.len()); + } + for n in [0usize, 1, 7, 8, 9, 15, 16, 17, 23, 24, 25, 1000, 1007, 1016, 1023] { + let strings: Vec = (0..n).map(text).collect(); + check(&strings, |v: &[String], w: &mut Writer<'_>| crate::strings::write_strings_prefetched(w, v).unwrap()); + let options: Vec> = (0..n).map(|i| (i % 5 != 0).then(|| text(i))).collect(); + check(&options, |v: &[Option], w: &mut Writer<'_>| super::write_prefetched(v, w).unwrap()); + let boxes: Vec>> = (0..n).map(|i| (i % 7 != 0).then(|| Box::new(text(i)))).collect(); + check(&boxes, |v: &[Option>], w: &mut Writer<'_>| super::write_prefetched(v, w).unwrap()); + } + } + + /// The last-level cache size is read (on Linux) or assumed, never zero. + #[test] + fn last_level_cache_is_known() { + assert!(crate::simd::last_level_cache() >= 1 << 20); + } +} diff --git a/runtimes/rust/src/impls/maps.rs b/runtimes/rust/src/impls/maps.rs index 85df1024f..423378667 100644 --- a/runtimes/rust/src/impls/maps.rs +++ b/runtimes/rust/src/impls/maps.rs @@ -1,86 +1,3 @@ -use core::any::Any; -use core::hash::{BuildHasher, Hash}; -use std::collections::{hash_map, BTreeMap, HashMap}; - -use crate::error::{Error, ErrorKind, Result}; -use crate::reader::Reader; -use crate::traits::{NinoRead, NinoWrite}; -use crate::writer::Writer; - -use super::{dyn_step, read_key}; - -/// Whether a map of `K` and `V` is written as one block of entries ([`write_entries_fixed`]): both fixed-size, an -/// entry small enough for [`crate::simd::extend_fixed_iter`]'s buffer. -const fn entries_fixed(key: usize, value: usize) -> bool { - key != 0 && value != 0 && key.saturating_add(value) <= crate::simd::FIXED_STACK -} - -/// A map's length and entries (fixed-size keys and values, [`entries_fixed`]) in one block: one reservation, each -/// key and value encoded into its bytes, no length check, `Result` or reservation an entry. -#[inline] -fn write_entries_fixed<'e, K, V, I>(entries: I, w: &mut Writer<'_>) -> Result<()> -where - K: NinoWrite + 'e, - V: NinoWrite + 'e, - I: ExactSizeIterator, -{ - let length = i32::try_from(entries.len()).map_err(|_| Error::too_large())?; - let size = K::FIXED_SIZE.saturating_add(V::FIXED_SIZE); - crate::simd::extend_fixed_iter(w.buffer(), length.to_le_bytes(), entries, size, |(k, v), out| { - if let Some((a, b)) = out.split_at_mut_checked(K::FIXED_SIZE) { - k.encode_fixed(a); - v.encode_fixed(b); - } - }); - Ok(()) -} - -/// Whether this target reads a map's fixed-size entries as a slice each, the key and value decoded from it and -/// inserted through the entry API: x86_64, where that measured faster, and 32-bit x86 (the same code). On Arm64 it was -/// 3–4% slower (Neoverse-N2), the entry held in a vector register across the hash call. -const ENTRY_SLICES: bool = cfg!(any(target_arch = "x86", target_arch = "x86_64")); - -/// Whether a map's entries are read with one bounds check each ([`read_entries_fixed`]): keys and values of a fixed -/// size that is also their least, on x86 ([`ENTRY_SLICES`]) and, elsewhere, when an entry is 8 bytes (two `i32`s, an -/// `i64` and a `u32` and `u16`, ...), read as one array. Other entries off x86 keep the generic loop, which reads the -/// same entries in the same order. -const fn entries_fixed_read() -> bool { - (ENTRY_SLICES || K::FIXED_SIZE.saturating_add(V::FIXED_SIZE) == 8) - && K::FIXED_SIZE != 0 - && V::FIXED_SIZE != 0 - && K::MIN_SIZE == K::FIXED_SIZE - && V::MIN_SIZE == V::FIXED_SIZE -} - -/// Reads `count` entries of fixed-size keys and values: one bounds check for each entry's bytes, its key and value -/// decoded from them and handed to `insert`, in order, so a cut entry, a bad value or a repeated key fails at the same -/// entry and with the same error as reading them one at a time. Off x86 an entry is 8 bytes, taken as one array: the -/// key and value stay in general-purpose registers (Neoverse-N2: 0.8% faster than the generic loop). -#[inline] -fn read_entries_fixed( - r: &mut Reader<'_>, - count: usize, - mut insert: impl FnMut(K, V) -> Result<()>, -) -> Result<()> { - if !ENTRY_SLICES { - for _ in 0..count { - let entry = r.array::<8>()?; - // Never `None`: `K::FIXED_SIZE + V::FIXED_SIZE` is 8 here ([`entries_fixed_read`]). - let Some((k, v)) = entry.split_at_checked(K::FIXED_SIZE) else { break }; - insert(K::decode_fixed(k)?, V::decode_fixed(v)?)?; - } - return Ok(()); - } - let size = K::FIXED_SIZE.saturating_add(V::FIXED_SIZE); - for _ in 0..count { - let entry = r.take(size)?; - // Never `None`: an entry is `K::FIXED_SIZE + V::FIXED_SIZE` bytes. - let Some((k, v)) = entry.split_at_checked(K::FIXED_SIZE) else { break }; - insert(K::decode_fixed(k)?, V::decode_fixed(v)?)?; - } - Ok(()) -} - /// `NinoRead` for a hash map type `$map` whose keys have `$bound`: its length, then each key and value, read /// into an empty map by `$fill(map, r, count)` (which rejects a repeated key); read into an existing map, it is cleared /// and refilled, keeping its buffer. One body for `HashMap` and `IndexMap` (convert.rs). diff --git a/runtimes/rust/src/impls/numbers.rs b/runtimes/rust/src/impls/numbers.rs index f16af1eb7..95d94773b 100644 --- a/runtimes/rust/src/impls/numbers.rs +++ b/runtimes/rust/src/impls/numbers.rs @@ -1,7 +1,4 @@ -use crate::error::{Error, ErrorKind, Result}; -use crate::reader::Reader; -use crate::traits::{NinoRead, NinoWrite}; -use crate::writer::Writer; +// ---------------------------------------------------------------------- numbers macro_rules! number { ($($t:ty, $n:literal, $method:ident;)*) => {$( diff --git a/runtimes/rust/src/impls/sequences.rs b/runtimes/rust/src/impls/sequences.rs index c29f4d9c2..531bcc97a 100644 --- a/runtimes/rust/src/impls/sequences.rs +++ b/runtimes/rust/src/impls/sequences.rs @@ -1,191 +1,4 @@ -use core::any::Any; -use std::collections::VecDeque; - -use crate::defer::Step; -use crate::error::{Error, Result}; -use crate::reader::Reader; -use crate::traits::{NinoRead, NinoWrite}; -use crate::writer::Writer; - -fn vec_item(v: &mut dyn Any, i: usize) -> Option<&mut dyn Any> { - v.downcast_mut::>()?.get_mut(i).map(|x| x as &mut dyn Any) -} - -fn deque_item(v: &mut dyn Any, i: usize) -> Option<&mut dyn Any> { - v.downcast_mut::>()?.get_mut(i).map(|x| x as &mut dyn Any) -} - -/// Reads `count` elements one by one into a `Vec` (deferred bodies in them reached by `index`). -#[inline] -fn read_into_vec( - r: &mut Reader<'_>, - count: usize, - index: fn(&mut dyn Any, usize) -> Option<&mut dyn Any>, -) -> Result> { - let mut values = Vec::with_capacity(r.capacity::(count)); - for i in 0..count { - if T::MAY_DEFER { - let mark = r.defer_mark(); - values.push(T::read(r)?); - r.defer_trail(mark, Step::Index(index, i)); - } else { - values.push(T::read(r)?); - } - } - Ok(values) -} - -/// [`NinoRead::read_many`]'s default: each element in turn. -#[inline] -pub(crate) fn read_each(r: &mut Reader<'_>, count: usize) -> Result> { - read_into_vec(r, count, vec_item::) -} - -/// [`NinoRead::read_many_into`]'s default: the first elements read into, by index, the rest read new. -#[inline] -pub(crate) fn read_each_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { - if values.is_empty() { - // Nothing to read into: the plain read, its allocation budget included. - *values = T::read_many(r, count)?; - return Ok(()); - } - values.truncate(count); - for (i, v) in values.iter_mut().enumerate() { - if T::MAY_DEFER { - let mark = r.defer_mark(); - v.read_into(r)?; - r.defer_trail(mark, Step::Index(vec_item::, i)); - } else { - v.read_into(r)?; - } - } - let have = values.len(); - // `have <= count`: no wrap. - values.reserve(r.capacity::(count.wrapping_sub(have))); - for i in have..count { - if T::MAY_DEFER { - let mark = r.defer_mark(); - values.push(T::read(r)?); - r.defer_trail(mark, Step::Index(vec_item::, i)); - } else { - values.push(T::read(r)?); - } - } - Ok(()) -} - -/// [`NinoRead::read_many_into`]'s default for a fixed-size type: [`read_fixed`] into the `Vec`'s buffer. -#[inline] -pub(crate) fn read_fixed_into(r: &mut Reader<'_>, count: usize, values: &mut Vec) -> Result<()> { - if values.capacity() < count { - // Not enough room: the plain read, its allocation budget included. - *values = read_fixed(r, count)?; - return Ok(()); - } - let size = count.checked_mul(T::FIXED_SIZE).ok_or_else(Error::too_large)?; - let bytes = r.take(size)?; - crate::simd::decode_block_into(values, bytes.chunks_exact(T::FIXED_SIZE), T::decode_fixed) -} - -/// [`NinoRead::read_many`]'s default for a fixed-size type: the elements' bytes with one length check, then -/// [`NinoRead::decode_fixed`] on each. -#[inline] -pub(crate) fn read_fixed(r: &mut Reader<'_>, count: usize) -> Result> { - let size = count.checked_mul(T::FIXED_SIZE).ok_or_else(Error::too_large)?; - let capacity = r.capacity::(count); - let bytes = r.take(size)?; - if capacity < count { - return grow_fixed(bytes.chunks_exact(T::FIXED_SIZE), capacity, T::decode_fixed); - } - crate::simd::decode_block(bytes.chunks_exact(T::FIXED_SIZE), T::decode_fixed) -} - -/// A block of fixed-size elements past the allocation budget ([`Reader::capacity`]): `capacity` of them allocated up -/// front, the `Vec` grown for the rest. -#[cold] -#[inline(never)] -pub(crate) fn grow_fixed( - chunks: impl Iterator, - capacity: usize, - decode: impl Fn(C) -> Result, -) -> Result> { - let mut values = Vec::with_capacity(capacity); - for c in chunks { - values.push(decode(c)?); - } - Ok(values) -} - -/// The elements a prefetching loop runs ahead: at element `i`, element `i + 2 * PREFETCH_AHEAD`'s targets are asked -/// for ([`NinoWrite::prefetch`]), and element `i + PREFETCH_AHEAD`'s targets' own ([`NinoWrite::prefetch_members`], -/// their lines asked for a batch earlier). The same as the Go runtime's. -const PREFETCH_AHEAD: usize = 8; - -/// Whether a slice of `len` elements is written prefetching ahead: at least 512 elements, and more estimated data (an -/// element's size and the bytes it points to, [`NinoWrite::PREFETCH_BYTES`]) than the last-level cache holds -/// ([`crate::simd::last_level_cache`]). Data that fits is likely in the cache already, where a prefetch per element -/// costs more than it saves. -#[inline] -pub(crate) fn prefetches(len: usize) -> bool { - len >= 512 && outgrows_cache(len, core::mem::size_of::().saturating_add(T::PREFETCH_BYTES)) -} - -/// Whether `len` elements of `bytes` each are more than the last-level cache holds: out of line, so that a short -/// list's code is one compare. -#[cold] -#[inline(never)] -fn outgrows_cache(len: usize, bytes: usize) -> bool { - len.saturating_mul(bytes) > crate::simd::last_level_cache() -} - -/// [`NinoWrite::write_many`] for a long slice of elements that point elsewhere ([`prefetches`]): the same bytes, -/// each element's targets asked for [`PREFETCH_AHEAD`] elements before they are written, in two stages. Out of line, -/// so that the loop of every other slice stays as it was. -#[inline(never)] -pub(crate) fn write_prefetched<'a, T: NinoWrite>(values: &'a [T], w: &mut Writer<'a>) -> Result<()> { - for (i, v) in values.iter().enumerate() { - // `i < values.len() <= isize::MAX`: the sums cannot wrap. - if let Some(ahead) = values.get(i.wrapping_add(2 * PREFETCH_AHEAD)) { - ahead.prefetch(); - } - if let Some(next) = values.get(i.wrapping_add(PREFETCH_AHEAD)) { - next.prefetch_members(); - } - v.write(w)?; - } - Ok(()) -} - -/// [`NinoWrite::write_many`]'s default for a fixed-size type: room for every element, then -/// [`NinoWrite::encode_fixed`] into each element's bytes. -#[inline] -pub(crate) fn write_fixed(values: &[T], w: &mut Writer<'_>) { - if T::FIXED_SIZE <= crate::simd::FIXED_STACK { - crate::simd::extend_fixed(w.buffer(), [], values, T::FIXED_SIZE, T::encode_fixed); - return; - } - let out = w.reserve(values.len().saturating_mul(T::FIXED_SIZE)); - for (v, o) in values.iter().zip(out.chunks_exact_mut(T::FIXED_SIZE)) { - v.encode_fixed(o); - } -} - -/// [`NinoWrite::write_counted`]'s default for a fixed-size type: the length and the elements in one block. -#[inline] -pub(crate) fn write_counted_fixed(values: &[T], w: &mut Writer<'_>) -> Result<()> { - let length = i32::try_from(values.len()).map_err(|_| Error::too_large())?; - if T::FIXED_SIZE <= crate::simd::FIXED_STACK { - crate::simd::extend_fixed(w.buffer(), length.to_le_bytes(), values, T::FIXED_SIZE, T::encode_fixed); - return Ok(()); - } - let out = w.reserve(values.len().saturating_mul(T::FIXED_SIZE).saturating_add(4)); - let Some((head, out)) = out.split_first_chunk_mut::<4>() else { return Ok(()) }; - *head = length.to_le_bytes(); - for (v, o) in values.iter().zip(out.chunks_exact_mut(T::FIXED_SIZE)) { - v.encode_fixed(o); - } - Ok(()) -} +// ---------------------------------------------------------------------- sequences /// Writes a length and the elements; `None` is null. #[inline] @@ -332,39 +145,3 @@ impl NinoWrite for VecDeque { w.or_null_length(value) } } - -#[cfg(test)] -#[allow(clippy::indexing_slicing, clippy::arithmetic_side_effects, clippy::unwrap_used)] -mod tests { - use crate::{serialize, NinoWrite, Writer}; - - /// The prefetching loops write the same bytes as their elements written one by one: strings (in batches), - /// optional strings and boxed strings (two stages), with lengths that end the batches and the look-ahead - /// anywhere, and lists too short to look ahead at all. - #[test] - fn prefetched_lists() { - let kinds = ["", "a", "é", "字", "🎉 строка", "crème brûlée"]; - let text = |i: usize| format!("{}{}", kinds[i % kinds.len()], i % 97); - fn check(values: &[T], prefetched: impl for<'a> Fn(&'a [T], &mut Writer<'a>)) { - let mut expected = Vec::new(); - values.iter().for_each(|v| expected.extend(serialize(v).unwrap())); - let mut w = Writer::new(); - prefetched(values, &mut w); - assert_eq!(w.into_vec(), expected, "{} elements", values.len()); - } - for n in [0usize, 1, 7, 8, 9, 15, 16, 17, 23, 24, 25, 1000, 1007, 1016, 1023] { - let strings: Vec = (0..n).map(text).collect(); - check(&strings, |v: &[String], w: &mut Writer<'_>| crate::strings::write_strings_prefetched(w, v).unwrap()); - let options: Vec> = (0..n).map(|i| (i % 5 != 0).then(|| text(i))).collect(); - check(&options, |v: &[Option], w: &mut Writer<'_>| super::write_prefetched(v, w).unwrap()); - let boxes: Vec>> = (0..n).map(|i| (i % 7 != 0).then(|| Box::new(text(i)))).collect(); - check(&boxes, |v: &[Option>], w: &mut Writer<'_>| super::write_prefetched(v, w).unwrap()); - } - } - - /// The last-level cache size is read (on Linux) or assumed, never zero. - #[test] - fn last_level_cache_is_known() { - assert!(crate::simd::last_level_cache() >= 1 << 20); - } -} diff --git a/runtimes/rust/src/impls/sets.rs b/runtimes/rust/src/impls/sets.rs index 47b1eb043..ce3396e59 100644 --- a/runtimes/rust/src/impls/sets.rs +++ b/runtimes/rust/src/impls/sets.rs @@ -1,13 +1,3 @@ -use core::hash::Hash; -use std::collections::{BTreeSet, HashSet}; - -use crate::error::{Error, ErrorKind, Result}; -use crate::reader::Reader; -use crate::traits::{NinoRead, NinoWrite}; -use crate::writer::Writer; - -use super::read_key; - macro_rules! set { ($set:ident, $($bound:tt)*) => { /// A set: its length, then each element. A repeated element is rejected. diff --git a/runtimes/rust/src/impls/strings.rs b/runtimes/rust/src/impls/strings.rs index 7726c5b56..dbcc276a9 100644 --- a/runtimes/rust/src/impls/strings.rs +++ b/runtimes/rust/src/impls/strings.rs @@ -1,9 +1,4 @@ -use crate::error::{Error, Result}; -use crate::reader::Reader; -use crate::traits::{NinoRead, NinoWrite}; -use crate::writer::Writer; - -use super::sequences::prefetches; +// ---------------------------------------------------------------------- strings impl NinoRead for String { const MIN_SIZE: usize = 1; diff --git a/runtimes/rust/src/impls/tuples.rs b/runtimes/rust/src/impls/tuples.rs index c6b87eab2..0e341e63d 100644 --- a/runtimes/rust/src/impls/tuples.rs +++ b/runtimes/rust/src/impls/tuples.rs @@ -1,9 +1,4 @@ -use core::any::Any; - -use crate::error::{Error, Result}; -use crate::reader::Reader; -use crate::traits::{NinoRead, NinoWrite}; -use crate::writer::Writer; +// ---------------------------------------------------------------------- tuples macro_rules! tuple { ($($name:ident $index:tt),+) => { diff --git a/runtimes/rust/src/impls/wrappers.rs b/runtimes/rust/src/impls/wrappers.rs index 71254b163..98e464be3 100644 --- a/runtimes/rust/src/impls/wrappers.rs +++ b/runtimes/rust/src/impls/wrappers.rs @@ -1,10 +1,4 @@ -use core::any::Any; - -use crate::defer::Step; -use crate::error::Result; -use crate::reader::Reader; -use crate::traits::{NinoRead, NinoWrite}; -use crate::writer::Writer; +// ---------------------------------------------------------------------- Option, Box fn option_inner(v: &mut dyn Any) -> Option<&mut dyn Any> { v.downcast_mut::>()?.as_mut().map(|x| x as &mut dyn Any) From 3a2be47cea86216b68bac1aad2443dba4d6ddec4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?JasonXuDeveloper=20-=20=E5=82=91?= Date: Thu, 19 Nov 2026 14:01:55 +1100 Subject: [PATCH 2/3] ci(rust): check formatting of included codec fragments Cargo fmt follows module declarations. Check files loaded through include! explicitly and document both commands for local runs. --- .github/workflows/runtimes.yml | 5 ++++- runtimes/rust/AGENTS.md | 11 +++++++---- runtimes/rust/README.md | 1 + 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/.github/workflows/runtimes.yml b/.github/workflows/runtimes.yml index 398a07003..00894bf31 100644 --- a/.github/workflows/runtimes.yml +++ b/.github/workflows/runtimes.yml @@ -275,7 +275,10 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' }} - name: Format - run: cargo fmt --all --check + run: | + cargo fmt --all --check + # rustfmt does not follow the ordered include! fragments. + rustfmt --edition 2021 --check src/impls/*.rs - name: Clippy if: ${{ !cancelled() }} diff --git a/runtimes/rust/AGENTS.md b/runtimes/rust/AGENTS.md index 0d750ce79..e57807579 100644 --- a/runtimes/rust/AGENTS.md +++ b/runtimes/rust/AGENTS.md @@ -26,11 +26,11 @@ src/ writer.rs Writer: appends to a Vec error.rs the one error type (Error, ErrorKind) traits.rs the traits generated code implements and calls (NinoRead, NinoWrite, bodies) - impls.rs trait implementation modules, ordered keys and deferred steps + impls.rs shared codec helpers, ordered keys, deferred steps and the ordered codec fragments impls/numbers.rs primitive numbers and booleans, including their fixed-size blocks impls/strings.rs String and str impls/wrappers.rs Option and Box - impls/sequences.rs Vec, slices and VecDeque, including block and prefetch helpers + impls/sequences.rs Vec, slices and VecDeque impls/sets.rs HashSet, BTreeSet and shared set helpers impls/maps.rs HashMap, BTreeMap and the map! reader shared with IndexMap impls/tuples.rs tuples and pairs @@ -114,11 +114,14 @@ Generated files: `tests/generated/*` is rewritten by `NINO_UPDATE_GENERATED=1 do (`type_consts!`); anything the wire format cannot express is a compile error naming the field, with a case in `tests/compile_fail/`. Give a new attribute a corpus or derive test. -- Before committing: `cargo fmt --all --check`, `cargo clippy --workspace --all-features --all-targets -- -D warnings` -- Write a macro call's arguments one per line once they hold a bound (`HashMap,` / `fill_hash_map,` / `Eq + Hash`): the rustfmt in CI's `stable` toolchain (November 2026) splits them, while rustfmt 1.9.0 accepts both forms, so a local check passed and main's Runtimes run failed on `map!` in `impls.rs` and `convert.rs` (5a03c0a5). +- Before committing: `cargo fmt --all --check`, `rustfmt --edition 2021 --check src/impls/*.rs` for the included + fragments, `cargo clippy --workspace --all-features --all-targets -- -D warnings`, and `cargo test --workspace --all-features` with `NINO_CORPUS` set (the conformance, derive and fuzz tests skip without a corpus), then `cargo test -p nino-serialization --lib --test spec --test values` without features, as runtimes.yml does: a test there that uses the derive or another feature goes behind `#[cfg(feature = "...")]` (round 104's `canonical_layout_int128_field` broke that job). `tests/conformance/types.rs` is generated by `tests/conformance/gen.py`; edit the generator. Builds share one `CARGO_TARGET_DIR`: Rust targets are large. +- Write a macro call's arguments one per line once they hold a bound (`HashMap,` / `fill_hash_map,` / `Eq + Hash`). + The rustfmt in CI's `stable` toolchain (November 2026) splits them, while rustfmt 1.9.0 accepts both forms. + A local check passed and main's Runtimes run failed on `map!` in `impls.rs` and `convert.rs` (5a03c0a5). diff --git a/runtimes/rust/README.md b/runtimes/rust/README.md index 923d2e99a..d84d62611 100644 --- a/runtimes/rust/README.md +++ b/runtimes/rust/README.md @@ -273,6 +273,7 @@ still parse from these strings (`FromStr`) and print to them (`Display`). ```sh cargo fmt --all --check +rustfmt --edition 2021 --check src/impls/*.rs cargo clippy --workspace --all-features --all-targets -- -D warnings cargo test --workspace --all-features ``` From 73766a8d84675d020ea30dceba55c45b18e1487c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?JasonXuDeveloper=20-=20=E5=82=91?= Date: Thu, 19 Nov 2026 14:01:55 +1100 Subject: [PATCH 3/3] docs(skills): record the machine-code check for Rust splits Document how to preserve the Rust module and item order for source-only splits, isolate existing optimizations in the baseline, and verify formatting coverage. --- .claude/skills/audit-layout/SKILL.md | 6 ++++++ .claude/skills/optimize-runtimes/SKILL.md | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.claude/skills/audit-layout/SKILL.md b/.claude/skills/audit-layout/SKILL.md index c4d68e34f..f9ef6f6b5 100644 --- a/.claude/skills/audit-layout/SKILL.md +++ b/.claude/skills/audit-layout/SKILL.md @@ -109,6 +109,12 @@ its own `AGENTS.md` maps every file in it. - In the Unity project an asmdef, not the folder name, decides where an assembly compiles: `Assets/Test/Editor/Model` and `CrossRef` build for players too and sit under `Editor/` because only the editor tests use them (their namespaces say `Test.Editor`); move them only together with their namespaces. +- **Preserve the original module and item order when splitting Rust files whose machine code must stay identical.** + Moving impls to child modules can change rustc's codegen-unit partitioning and alter even untouched hot functions + (`DateOnly::new` in #248). Use ordered `include!` fragments when ordinary modules change the instructions. + Compare the release binaries from the same checkout path and flags with the same hot-path implementations on both + sides (`optimize-runtimes`). Check the fragments with `rustfmt --check` as well as `cargo fmt --all --check`, + which does not follow `include!`. ## Adding files that nothing builds diff --git a/.claude/skills/optimize-runtimes/SKILL.md b/.claude/skills/optimize-runtimes/SKILL.md index 3f66bd7d6..0b727bf0e 100644 --- a/.claude/skills/optimize-runtimes/SKILL.md +++ b/.claude/skills/optimize-runtimes/SKILL.md @@ -10,7 +10,8 @@ metadata: The techniques that made the Go, Rust and TypeScript runtimes and nino-gen's generated code faster or slower. The .NET and Unity techniques, reading .NET machine code and the prefetch design of every runtime are `optimize` (prefetch: its references/prefetch.md). How to measure on runners is `benchmark` (runtime A/B), where the next win is -`audit-perf`, each runtime's rules are `runtimes/*/AGENTS.md` and `audit-runtimes`. +`audit-perf`, each runtime's rules are `runtimes/*/AGENTS.md` and `audit-runtimes`. For Rust source splits that must +keep machine code identical, see [audit-layout](../audit-layout/SKILL.md#splitting-long-files). ## The techniques, by topic