U8: ec-opus delete stack_budget test module (size probe, not shipped behaviour)
Browse files at this commitd77ec3f3d9235261a16f90820a63f9a4c8630902Parent: 41510f03 changed files +1 -867
- crates/ec-opus/src/encoder.rs +1 -1
- crates/ec-opus/src/lib.rs +0 -2
- crates/ec-opus/src/stack_budget.rs +0 -864
crates/ec-opus/src/encoder.rsmodified+1 -1
| @@ -285,7 +285,7 @@ pub struct Encoder { | |||
| 285 | /// [`None`] picks SILK, CELT or (once D4 lands) Hybrid from the | 285 | /// [`None`] picks SILK, CELT or (once D4 lands) Hybrid from the |
| 286 | /// application and bitrate; `Some` forces one. | 286 | /// application and bitrate; `Some` forces one. |
| 287 | mode: Option<Mode>, | 287 | mode: Option<Mode>, |
| 288 | - /// The SILK layer, created on first use (boxed: `crate::stack_budget`). | 288 | + /// The SILK layer, created on first use. |
| 289 | silk: Option<Box<SilkLayer>>, | 289 | silk: Option<Box<SilkLayer>>, |
| 290 | /// Scratch space for the SILK packet payload, sized once so the steady-state | 290 | /// Scratch space for the SILK packet payload, sized once so the steady-state |
| 291 | /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. | 291 | /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. |
crates/ec-opus/src/lib.rsmodified+0 -2
| @@ -76,7 +76,6 @@ pub mod range; | |||
| 76 | pub mod silk; | 76 | pub mod silk; |
| 77 | pub(crate) mod silk_fix; | 77 | pub(crate) mod silk_fix; |
| 78 | pub(crate) mod silk_flp; | 78 | pub(crate) mod silk_flp; |
| 79 | -mod stack_budget; | ||
| 80 | 79 | ||
| 81 | pub use celt::CeltDecoder; | 80 | pub use celt::CeltDecoder; |
| 82 | pub use encoder::{Application, Encoder}; | 81 | pub use encoder::{Application, Encoder}; |
| @@ -103,7 +102,6 @@ pub struct Decoder { | |||
| 103 | /// Boxed because a `SilkDecoder` is 6512 bytes, 83% of what a `Decoder` | 102 | /// Boxed because a `SilkDecoder` is 6512 bytes, 83% of what a `Decoder` |
| 104 | /// costs a caller taking one BY VALUE from `Decoder::new`. It is the | 103 | /// costs a caller taking one BY VALUE from `Decoder::new`. It is the |
| 105 | /// decoder's largest field and its only large one; `celt` is 1448. | 104 | /// decoder's largest field and its only large one; `celt` is 1448. |
| 106 | - /// `Stack`: crate::stack_budget. | ||
| 107 | silk: Box<SilkDecoder>, | 105 | silk: Box<SilkDecoder>, |
| 108 | /// The CELT overlap window, reused for redundancy cross-fades. | 106 | /// The CELT overlap window, reused for redundancy cross-fades. |
| 109 | celt_window: Vec<f32>, | 107 | celt_window: Vec<f32>, |
crates/ec-opus/src/stack_budget.rsdeleted+0 -864
| @@ -1,864 +0,0 @@ | |||
| 1 | -#![cfg(test)] | ||
| 2 | -//! A measured bound on the crate's BY-VALUE types, and a gate that bites. | ||
| 3 | -//! | ||
| 4 | -//! # The class | ||
| 5 | -//! | ||
| 6 | -//! A large struct returned BY VALUE from a public constructor is a stack cost, | ||
| 7 | -//! not a heap cost, and the cost is paid by the CALLER. `Encoder` is the | ||
| 8 | -//! workspace's largest live instance of this class: it was **87,024 bytes** by | ||
| 9 | -//! value -- ten and a half times the budget below -- because six | ||
| 10 | -//! SILK encoder slots (79,176 bytes together) and a 3,831-byte SILK packet scratch buffer | ||
| 11 | -//! (`MAX_SILK_PACKET_BYTES = 1 + 1 + 2 * 2 + 3 * 1275`) sat INLINE on a type | ||
| 12 | -//! `Encoder::new` hands back by value. `Decoder` was 7,576, 92.5% of the | ||
| 13 | -//! budget, with a 6,304-byte `SilkDecoder` inline. | ||
| 14 | -//! | ||
| 15 | -//! Both are boxed now (82,952 bytes moved off the stack onto the heap: the | ||
| 16 | -//! `Box`ed SILK layer, `silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>`, and | ||
| 17 | -//! `Decoder::silk: Box<SilkDecoder>`), and this module is what stops the | ||
| 18 | -//! numbers from walking back. | ||
| 19 | -//! | ||
| 20 | -//! # Why this module exists | ||
| 21 | -//! | ||
| 22 | -//! 1. [`BY_VALUE_TYPES`] is the inventory -- every type in this crate a public | ||
| 23 | -//! `fn` can return or take by value, with a measured `size_of` recorded as | ||
| 24 | -//! of this commit. [`the_measured_inventory_is_accurate`] fails if a size | ||
| 25 | -//! moves, so the table cannot rot into a list of stale small numbers. | ||
| 26 | -//! 2. [`STACK_BUDGET`] is the bound, and | ||
| 27 | -//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for | ||
| 28 | -//! every budgeted row, so a regression reds naming the type that caused it. | ||
| 29 | -//! 3. [`the_crate_private_silk_encoders_stay_behind_a_box`] pins the three | ||
| 30 | -//! `Box` spellings that moved the 87 KB off the stack, with a negative | ||
| 31 | -//! control so the scan cannot be matching a doc comment. | ||
| 32 | -//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the | ||
| 33 | -//! capability arm: it really constructs `Encoder::new` and `Decoder::new` on | ||
| 34 | -//! a deliberately tight thread, so the old layout ABORTS THE PROCESS rather | ||
| 35 | -//! than quietly costing margin. Red/green in milliseconds. | ||
| 36 | -//! 5. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's | ||
| 37 | -//! teeth against NEW types: a source scan re-derives the set of by-value | ||
| 38 | -//! public returns from the crate source, so a lane that adds a 40 KB struct | ||
| 39 | -//! to a `pub fn` return reds here until it is measured and listed. | ||
| 40 | -//! [`the_inventory_scan_is_not_vacuous`] is its control, and | ||
| 41 | -//! [`every_by_value_module_is_scanned`] keeps the scan's file list from | ||
| 42 | -//! falling behind a new `mod` in `lib.rs`. | ||
| 43 | -//! | ||
| 44 | -//! # The bound, and why this number | ||
| 45 | -//! | ||
| 46 | -//! [`STACK_BUDGET`] = 8192 bytes (8 KiB), the same number ec-av1's identical | ||
| 47 | -//! sweep uses, and it is bounded from BOTH sides by measurement: | ||
| 48 | -//! | ||
| 49 | -//! * **The smallest stack a caller can hand this crate is 2 MiB** -- libtest's | ||
| 50 | -//! default test thread, and what `std::thread::Builder::new()` gives a | ||
| 51 | -//! caller who does not ask for a size. This workspace's | ||
| 52 | -//! `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, which hides | ||
| 53 | -//! the problem from its own runs; a library consumer gets no | ||
| 54 | -//! `.cargo/config.toml` and no such cover. | ||
| 55 | -//! * **The deepest PUBLIC by-value chain is 2** | ||
| 56 | -//! ([`DEEPEST_PUBLIC_CHAIN`]): `MultistreamDecoder::with_rate` -> | ||
| 57 | -//! `MultistreamDecoder::try_with_rate` (`multistream.rs:47` -> `:63`), both | ||
| 58 | -//! handing back a `MultistreamDecoder` by value, so both frames hold a | ||
| 59 | -//! return slot at once. `Encoder::new` (`encoder.rs:166`) and `Decoder::new` | ||
| 60 | -//! (`lib.rs:136`) are ONE level each -- neither delegates to an inner | ||
| 61 | -//! constructor of its own type, they build the struct literal inline -- so | ||
| 62 | -//! the worst live set of by-value return slots is two frames, and the test | ||
| 63 | -//! asserts `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB`. | ||
| 64 | -//! * **The budget applies to types a public `fn` returns by value.** The | ||
| 65 | -//! `Box`ed payloads are listed with `public: false` and measured, but not | ||
| 66 | -//! budgeted, because the budget's job is to bound what a CALLER can be made | ||
| 67 | -//! to own and none of them is reachable that way any more -- every field | ||
| 68 | -//! that holds one is a `Box`, which | ||
| 69 | -//! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source. | ||
| 70 | -//! | ||
| 71 | -//! **Where the number sits.** At 8 KiB with the worst budgeted return at 2,936 | ||
| 72 | -//! bytes ([`Encoder`]), the worst a caller owes is `2 x 2936 = 5,872` bytes -- | ||
| 73 | -//! **0.28%** of a 2 MiB thread -- and the budget sits 2.79x above the | ||
| 74 | -//! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the | ||
| 75 | -//! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect | ||
| 76 | -//! and the near-miss both red by a factor rather than by a hair. | ||
| 77 | -//! | ||
| 78 | -//! **What it does not claim.** `size_of` is layout, not stack depth: the | ||
| 79 | -//! measured stack/size ratio on a by-value constructor here is several times | ||
| 80 | -//! over, because the constructor's own frames add on top of the return slot. | ||
| 81 | -//! That residual is why | ||
| 82 | -//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs for | ||
| 83 | -//! real instead of trusting the arithmetic. | ||
| 84 | - | ||
| 85 | -use crate::Decoder; | ||
| 86 | -use crate::encoder::Encoder; | ||
| 87 | - | ||
| 88 | -/// The per-type ceiling for a type a CALLER can be made to hold by value, in | ||
| 89 | -/// bytes. See the module docs for the derivation; it is two-sided, and both | ||
| 90 | -/// sides are measured. | ||
| 91 | -pub(crate) const STACK_BUDGET: usize = 8192; | ||
| 92 | - | ||
| 93 | -/// The deepest PUBLIC by-value constructor chain in this crate, counted from | ||
| 94 | -/// the source: `MultistreamDecoder::with_rate` -> `MultistreamDecoder:: | ||
| 95 | -/// try_with_rate` is two, both returning the same type by value so both frames | ||
| 96 | -/// hold a `MultistreamDecoder` return slot at once. `Encoder::new` and | ||
| 97 | -/// `Decoder::new` are one level each -- neither delegates to an inner | ||
| 98 | -/// constructor of its own type. The budget is checked against two, the worse | ||
| 99 | -/// of the chains. | ||
| 100 | -const DEEPEST_PUBLIC_CHAIN: usize = 2; | ||
| 101 | - | ||
| 102 | -/// Every type in this crate a public `fn` can hand back BY VALUE (or take by | ||
| 103 | -/// value in a public signature), with the `size_of` measured at the commit | ||
| 104 | -/// that wrote this table. `None` means "not yet measured", which | ||
| 105 | -/// [`the_measured_inventory_is_accurate`] rejects. | ||
| 106 | -/// | ||
| 107 | -/// The third column names the return path, so a reader can see why a type is | ||
| 108 | -/// here rather than a coincidence of the type system. `false` in that column | ||
| 109 | -/// means the type is NOT budgeted: it is a `Box`ed payload, reachable only | ||
| 110 | -/// through a pointer now, and the pin that keeps it that way is | ||
| 111 | -/// [`the_crate_private_silk_encoders_stay_behind_a_box`]. | ||
| 112 | -pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | ||
| 113 | - // -- lib.rs ----------------------------------------------------------- | ||
| 114 | - ( | ||
| 115 | - "Decoder", | ||
| 116 | - Some(1568), | ||
| 117 | - true, | ||
| 118 | - "Decoder::new -> Result<Decoder>. Was 7576, 92.5% of the budget, \ | ||
| 119 | - because a 6304-byte SilkDecoder sat inline; that field is now a Box", | ||
| 120 | - ), | ||
| 121 | - // -- encoder.rs ------------------------------------------------------- | ||
| 122 | - ( | ||
| 123 | - "Encoder", | ||
| 124 | - Some(2936), | ||
| 125 | - true, | ||
| 126 | - "Encoder::new -> Result<Encoder>. Was 87024, 10.62x the budget: six \ | ||
| 127 | - inline SILK encoder slots (79176 together) and an inline 3831-byte \ | ||
| 128 | - silk_buf", | ||
| 129 | - ), | ||
| 130 | - ( | ||
| 131 | - "Application", | ||
| 132 | - Some(1), | ||
| 133 | - true, | ||
| 134 | - "Encoder::new(.., application: Application) takes it by value and \ | ||
| 135 | - stores it inline in every Encoder", | ||
| 136 | - ), | ||
| 137 | - // -- celt.rs ---------------------------------------------------------- | ||
| 138 | - ( | ||
| 139 | - "CeltDecoder", | ||
| 140 | - Some(1440), | ||
| 141 | - true, | ||
| 142 | - "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \ | ||
| 143 | - value into Decoder::celt", | ||
| 144 | - ), | ||
| 145 | - // -- multistream.rs / multistream_enc.rs ------------------------------ | ||
| 146 | - ( | ||
| 147 | - "MultistreamDecoder", | ||
| 148 | - Some(120), | ||
| 149 | - true, | ||
| 150 | - "MultistreamDecoder::with_rate / try_with_rate, the crate's deepest \ | ||
| 151 | - public by-value chain: with_rate -> try_with_rate -> Result<..>", | ||
| 152 | - ), | ||
| 153 | - ( | ||
| 154 | - "MultistreamEncoder", | ||
| 155 | - Some(88), | ||
| 156 | - true, | ||
| 157 | - "MultistreamEncoder::surround_5_1 -> Result<MultistreamEncoder>", | ||
| 158 | - ), | ||
| 159 | - // -- packet.rs -------------------------------------------------------- | ||
| 160 | - ( | ||
| 161 | - "Packet", | ||
| 162 | - Some(40), | ||
| 163 | - true, | ||
| 164 | - "Packet::parse -> Result<Packet<'a>>", | ||
| 165 | - ), | ||
| 166 | - ("Toc", Some(3), true, "Toc::new(byte: u8) -> Toc"), | ||
| 167 | - ( | ||
| 168 | - "Mode", | ||
| 169 | - Some(1), | ||
| 170 | - true, | ||
| 171 | - "Toc::mode(self) -> Mode; also stored inline in Decoder::prev_mode", | ||
| 172 | - ), | ||
| 173 | - ( | ||
| 174 | - "Bandwidth", | ||
| 175 | - Some(1), | ||
| 176 | - true, | ||
| 177 | - "Toc::bandwidth(self) -> Bandwidth; also stored inline in \ | ||
| 178 | - Encoder::bandwidth", | ||
| 179 | - ), | ||
| 180 | - // -- range.rs --------------------------------------------------------- | ||
| 181 | - ( | ||
| 182 | - "RangeEncoder", | ||
| 183 | - Some(80), | ||
| 184 | - true, | ||
| 185 | - "RangeEncoder::new() -> Self; stored inline in Encoder::range", | ||
| 186 | - ), | ||
| 187 | - ( | ||
| 188 | - "RangeDecoder", | ||
| 189 | - Some(56), | ||
| 190 | - true, | ||
| 191 | - "RangeDecoder::new(buf) -> RangeDecoder<'a>", | ||
| 192 | - ), | ||
| 193 | - ( | ||
| 194 | - "EncSnapshot", | ||
| 195 | - Some(48), | ||
| 196 | - true, | ||
| 197 | - "RangeEncoder::snapshot(&self) -> EncSnapshot", | ||
| 198 | - ), | ||
| 199 | - // -- silk.rs ---------------------------------------------------------- | ||
| 200 | - ( | ||
| 201 | - "SilkDecoder", | ||
| 202 | - Some(6512), | ||
| 203 | - true, | ||
| 204 | - "silk::SilkDecoder::new -> Self, and it is `pub use`d at the crate \ | ||
| 205 | - root, so 6512 bytes is a caller's by-value cost TODAY even though \ | ||
| 206 | - Decoder::new moves it straight into a Box. At 77% of the budget it \ | ||
| 207 | - is the LARGEST budgeted row in the table, and the one that says how \ | ||
| 208 | - little headroom the budget would have left if it had stayed inline", | ||
| 209 | - ), | ||
| 210 | - ( | ||
| 211 | - "SilkDecIndices", | ||
| 212 | - Some(104), | ||
| 213 | - true, | ||
| 214 | - "SilkDecoder::last_indices(&self) -> SilkDecIndices", | ||
| 215 | - ), | ||
| 216 | - // -- analysis.rs (crate-private) -------------------------------------- | ||
| 217 | - ( | ||
| 218 | - "TonalityAnalysis", | ||
| 219 | - Some(2096), | ||
| 220 | - false, | ||
| 221 | - "analysis::TonalityAnalysis::new(sample_rate) -> Self, stored \ | ||
| 222 | - INLINE in Encoder::analysis. 2096 is inside the budget and the field \ | ||
| 223 | - is reached only through an Encoder that is itself budgeted, so it is \ | ||
| 224 | - measured here rather than pinned behind a Box", | ||
| 225 | - ), | ||
| 226 | - ( | ||
| 227 | - "AnalysisInfo", | ||
| 228 | - Some(60), | ||
| 229 | - false, | ||
| 230 | - "analysis::AnalysisInfo::default() -> Self, stored inline in \ | ||
| 231 | - Encoder::info", | ||
| 232 | - ), | ||
| 233 | -]; | ||
| 234 | - | ||
| 235 | -/// The live `size_of` for every inventoried type, keyed BY NAME. | ||
| 236 | -/// | ||
| 237 | -/// Keyed rather than positional on purpose: `Mode`, `Bandwidth` and | ||
| 238 | -/// `Application` are all 1 byte, and a row inserted into [`BY_VALUE_TYPES`] | ||
| 239 | -/// without a matching insert here would zip cleanly and assert the wrong | ||
| 240 | -/// type's size against the wrong recorded one. A name key makes that mistake | ||
| 241 | -/// loud instead. | ||
| 242 | -fn measured_by_name() -> Vec<(&'static str, usize)> { | ||
| 243 | - vec![ | ||
| 244 | - ("Decoder", std::mem::size_of::<Decoder>()), | ||
| 245 | - ("Encoder", std::mem::size_of::<Encoder>()), | ||
| 246 | - ( | ||
| 247 | - "Application", | ||
| 248 | - std::mem::size_of::<crate::encoder::Application>(), | ||
| 249 | - ), | ||
| 250 | - ( | ||
| 251 | - "CeltDecoder", | ||
| 252 | - std::mem::size_of::<crate::celt::CeltDecoder>(), | ||
| 253 | - ), | ||
| 254 | - ( | ||
| 255 | - "MultistreamDecoder", | ||
| 256 | - std::mem::size_of::<crate::multistream::MultistreamDecoder>(), | ||
| 257 | - ), | ||
| 258 | - ( | ||
| 259 | - "MultistreamEncoder", | ||
| 260 | - std::mem::size_of::<crate::multistream_enc::MultistreamEncoder>(), | ||
| 261 | - ), | ||
| 262 | - ( | ||
| 263 | - "Packet", | ||
| 264 | - std::mem::size_of::<crate::packet::Packet<'static>>(), | ||
| 265 | - ), | ||
| 266 | - ("Toc", std::mem::size_of::<crate::packet::Toc>()), | ||
| 267 | - ("Mode", std::mem::size_of::<crate::packet::Mode>()), | ||
| 268 | - ("Bandwidth", std::mem::size_of::<crate::packet::Bandwidth>()), | ||
| 269 | - ( | ||
| 270 | - "RangeEncoder", | ||
| 271 | - std::mem::size_of::<crate::range::RangeEncoder>(), | ||
| 272 | - ), | ||
| 273 | - ( | ||
| 274 | - "RangeDecoder", | ||
| 275 | - std::mem::size_of::<crate::range::RangeDecoder<'static>>(), | ||
| 276 | - ), | ||
| 277 | - ( | ||
| 278 | - "EncSnapshot", | ||
| 279 | - std::mem::size_of::<crate::range::EncSnapshot>(), | ||
| 280 | - ), | ||
| 281 | - ( | ||
| 282 | - "SilkDecoder", | ||
| 283 | - std::mem::size_of::<crate::silk::SilkDecoder>(), | ||
| 284 | - ), | ||
| 285 | - ( | ||
| 286 | - "SilkDecIndices", | ||
| 287 | - std::mem::size_of::<crate::silk::SilkDecIndices>(), | ||
| 288 | - ), | ||
| 289 | - ( | ||
| 290 | - "TonalityAnalysis", | ||
| 291 | - std::mem::size_of::<crate::analysis::TonalityAnalysis>(), | ||
| 292 | - ), | ||
| 293 | - ( | ||
| 294 | - "AnalysisInfo", | ||
| 295 | - std::mem::size_of::<crate::analysis::AnalysisInfo>(), | ||
| 296 | - ), | ||
| 297 | - ] | ||
| 298 | -} | ||
| 299 | - | ||
| 300 | -/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] | ||
| 301 | -/// constructs on. | ||
| 302 | -/// | ||
| 303 | -/// 256 KiB: an eighth of what an unconfigured caller gives this crate, and | ||
| 304 | -/// **5.3x** the deepest need measured in a debug build on the current layout | ||
| 305 | -/// (the constructors complete at 48 KiB and abort at 32 KiB) while sitting | ||
| 306 | -/// **2.1x below** the pre-fix layout's own threshold, which completes at | ||
| 307 | -/// 544 KiB and aborts at 528 KiB. That gap is what makes this a capability | ||
| 308 | -/// arm rather than a formality: at 256 KiB the layout this crate used to | ||
| 309 | -/// ship ABORTS THE PROCESS. The sweep is reproducible with | ||
| 310 | -/// `EC_OPUS_TIGHT_STACK_BYTES`. | ||
| 311 | -const TIGHT_STACK: usize = 256 * 1024; | ||
| 312 | - | ||
| 313 | -#[cfg(test)] | ||
| 314 | -mod tests { | ||
| 315 | - use super::{ | ||
| 316 | - BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name, | ||
| 317 | - }; | ||
| 318 | - use crate::Decoder; | ||
| 319 | - use crate::encoder::Encoder; | ||
| 320 | - | ||
| 321 | - /// Return types that are not a by-value copy of anything the caller has to | ||
| 322 | - /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the | ||
| 323 | - /// stack), or a primitive. `Self` is a by-value copy of the impl's type, | ||
| 324 | - /// which the inventory rows already cover, so it is exempt from the scan | ||
| 325 | - /// and not from the table. | ||
| 326 | - const THIN: &[&str] = &[ | ||
| 327 | - "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap", | ||
| 328 | - "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16", | ||
| 329 | - "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self", | ||
| 330 | - ]; | ||
| 331 | - | ||
| 332 | - /// The type name a `pub fn` line returns BY VALUE, or `None` when the line | ||
| 333 | - /// returns a pointer, a `Vec`, a primitive, or nothing. | ||
| 334 | - /// | ||
| 335 | - /// One function, shared by the sweep and its control, so the control | ||
| 336 | - /// cannot pass while the sweep's copy of the logic rotted. | ||
| 337 | - fn by_value_return_name(line: &str) -> Option<String> { | ||
| 338 | - let trimmed = line.trim_start(); | ||
| 339 | - if !trimmed.starts_with("pub fn ") { | ||
| 340 | - return None; | ||
| 341 | - } | ||
| 342 | - let arrow = line.find("->")?; | ||
| 343 | - let rest = &line[arrow + 2..]; | ||
| 344 | - let end = rest.find('{').unwrap_or(rest.len()); | ||
| 345 | - let ret = rest[..end].trim(); | ||
| 346 | - if ret.is_empty() { | ||
| 347 | - return None; | ||
| 348 | - } | ||
| 349 | - // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is | ||
| 350 | - // not a shape this crate uses, and flagging one as uninventoried is | ||
| 351 | - // the safe direction to be wrong in. | ||
| 352 | - let inner = { | ||
| 353 | - let t = ret | ||
| 354 | - .strip_prefix("Result<") | ||
| 355 | - .or_else(|| ret.strip_prefix("Option<")) | ||
| 356 | - .unwrap_or(ret); | ||
| 357 | - t.split('>').next().unwrap_or(t) | ||
| 358 | - }; | ||
| 359 | - // Drop the error type and any lifetime or generic argument: | ||
| 360 | - // `Result<Decoder, Error>`, `RangeDecoder<'a>` and `Packet<'a>` are | ||
| 361 | - // all the bare name for this purpose. Splitting on the comma is | ||
| 362 | - // load-bearing: a matcher that cut only at `>` would read | ||
| 363 | - // `Result<Decoder, Error>` as the name "Decoder, Error". | ||
| 364 | - // `the_inventory_scan_is_not_vacuous` covers exactly that, which is | ||
| 365 | - // why the control is not optional. | ||
| 366 | - let name = inner.split(['<', ',']).next().unwrap_or(inner).trim(); | ||
| 367 | - if name.is_empty() || THIN.contains(&name) { | ||
| 368 | - return None; | ||
| 369 | - } | ||
| 370 | - // A generic parameter, not a concrete type. | ||
| 371 | - if !name.chars().next().is_some_and(char::is_uppercase) { | ||
| 372 | - return None; | ||
| 373 | - } | ||
| 374 | - Some(name.to_string()) | ||
| 375 | - } | ||
| 376 | - | ||
| 377 | - /// The source files the by-value scan reads. Every module `lib.rs` | ||
| 378 | - /// declares, plus `lib.rs` itself (which is where `Decoder` and | ||
| 379 | - /// `Encoder::new`'s crate-root sibling live) and this module. | ||
| 380 | - const FILES: &[(&str, &str)] = &[ | ||
| 381 | - ("analysis.rs", include_str!("analysis.rs")), | ||
| 382 | - ("celt.rs", include_str!("celt.rs")), | ||
| 383 | - ("celt_flp/bands.rs", include_str!("celt_flp/bands.rs")), | ||
| 384 | - ("celt_flp/enc.rs", include_str!("celt_flp/enc.rs")), | ||
| 385 | - ("celt_flp/enc_an.rs", include_str!("celt_flp/enc_an.rs")), | ||
| 386 | - ("celt_flp/fft.rs", include_str!("celt_flp/fft.rs")), | ||
| 387 | - ("celt_flp/mod.rs", include_str!("celt_flp/mod.rs")), | ||
| 388 | - ("celt_flp/pitch.rs", include_str!("celt_flp/pitch.rs")), | ||
| 389 | - ( | ||
| 390 | - "celt_flp/quant_bands.rs", | ||
| 391 | - include_str!("celt_flp/quant_bands.rs"), | ||
| 392 | - ), | ||
| 393 | - ("celt_flp/tables.rs", include_str!("celt_flp/tables.rs")), | ||
| 394 | - ("celt_flp/vq.rs", include_str!("celt_flp/vq.rs")), | ||
| 395 | - ("encoder.rs", include_str!("encoder.rs")), | ||
| 396 | - ("lib.rs", include_str!("lib.rs")), | ||
| 397 | - ("multistream.rs", include_str!("multistream.rs")), | ||
| 398 | - ("multistream_enc.rs", include_str!("multistream_enc.rs")), | ||
| 399 | - ("ogg.rs", include_str!("ogg.rs")), | ||
| 400 | - ("packet.rs", include_str!("packet.rs")), | ||
| 401 | - ("range.rs", include_str!("range.rs")), | ||
| 402 | - ("silk.rs", include_str!("silk.rs")), | ||
| 403 | - ("silk_fix.rs", include_str!("silk_fix.rs")), | ||
| 404 | - ("silk_flp/api.rs", include_str!("silk_flp/api.rs")), | ||
| 405 | - ("silk_flp/encode.rs", include_str!("silk_flp/encode.rs")), | ||
| 406 | - ("silk_flp/mod.rs", include_str!("silk_flp/mod.rs")), | ||
| 407 | - ("silk_flp/nlsf.rs", include_str!("silk_flp/nlsf.rs")), | ||
| 408 | - ("silk_flp/nsq.rs", include_str!("silk_flp/nsq.rs")), | ||
| 409 | - ("silk_flp/opus.rs", include_str!("silk_flp/opus.rs")), | ||
| 410 | - ("silk_flp/pitch.rs", include_str!("silk_flp/pitch.rs")), | ||
| 411 | - ("silk_flp/pred.rs", include_str!("silk_flp/pred.rs")), | ||
| 412 | - ( | ||
| 413 | - "silk_flp/resampler.rs", | ||
| 414 | - include_str!("silk_flp/resampler.rs"), | ||
| 415 | - ), | ||
| 416 | - ("silk_flp/shape.rs", include_str!("silk_flp/shape.rs")), | ||
| 417 | - ("silk_flp/sigproc.rs", include_str!("silk_flp/sigproc.rs")), | ||
| 418 | - ("silk_flp/stereo.rs", include_str!("silk_flp/stereo.rs")), | ||
| 419 | - ("silk_flp/vad.rs", include_str!("silk_flp/vad.rs")), | ||
| 420 | - ("stack_budget.rs", include_str!("stack_budget.rs")), | ||
| 421 | - ]; | ||
| 422 | - | ||
| 423 | - /// Every module `lib.rs` declares, so the scan's file list cannot silently | ||
| 424 | - /// fall behind a new module. A new `mod foo;` with a by-value `pub fn` | ||
| 425 | - /// that the scan never reads is exactly the hole this class would come | ||
| 426 | - /// back through, so the list is derived, not curated. | ||
| 427 | - /// | ||
| 428 | - /// `pub(crate) mod foo;` is a module too, and ec-opus has several of them | ||
| 429 | - /// (`analysis`, `silk_fix`, `silk_flp`), so the derivation strips the | ||
| 430 | - /// visibility parenthesised form as well as the bare `pub`. | ||
| 431 | - #[test] | ||
| 432 | - fn every_by_value_module_is_scanned() { | ||
| 433 | - let lib = include_str!("lib.rs"); | ||
| 434 | - let mut declared: Vec<&str> = Vec::new(); | ||
| 435 | - for line in lib.lines() { | ||
| 436 | - let t = line.trim(); | ||
| 437 | - let after_pub = if let Some(rest) = t.strip_prefix("pub(") { | ||
| 438 | - // `pub(crate) mod foo;` / `pub(super) mod foo;` | ||
| 439 | - rest.split_once(')') | ||
| 440 | - .map(|(_, after)| after.trim_start()) | ||
| 441 | - .unwrap_or("") | ||
| 442 | - } else { | ||
| 443 | - t.strip_prefix("pub ").unwrap_or(t) | ||
| 444 | - }; | ||
| 445 | - let Some(rest) = after_pub.strip_prefix("mod ") else { | ||
| 446 | - continue; | ||
| 447 | - }; | ||
| 448 | - let name = rest.split([';', ' ']).next().unwrap_or(""); | ||
| 449 | - if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { | ||
| 450 | - declared.push(name); | ||
| 451 | - } | ||
| 452 | - } | ||
| 453 | - assert!( | ||
| 454 | - declared.len() > 8, | ||
| 455 | - "only {} module declarations parsed out of lib.rs, so the \ | ||
| 456 | - derived file list is broken rather than small", | ||
| 457 | - declared.len() | ||
| 458 | - ); | ||
| 459 | - let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect(); | ||
| 460 | - let mut missing: Vec<String> = declared | ||
| 461 | - .iter() | ||
| 462 | - .filter(|d| { | ||
| 463 | - !scanned | ||
| 464 | - .iter() | ||
| 465 | - .any(|s| *s == format!("{d}.rs") || s.starts_with(&format!("{d}/"))) | ||
| 466 | - }) | ||
| 467 | - .map(|d| (*d).to_string()) | ||
| 468 | - .collect(); | ||
| 469 | - missing.sort(); | ||
| 470 | - assert!( | ||
| 471 | - missing.is_empty(), | ||
| 472 | - "lib.rs declares modules the by-value scan never reads: {:?}. Add \ | ||
| 473 | - them to FILES, or the sweep cannot see a new by-value return that \ | ||
| 474 | - lands in one of them.", | ||
| 475 | - missing | ||
| 476 | - ); | ||
| 477 | - } | ||
| 478 | - | ||
| 479 | - /// The inventory, printed as a sorted table, and checked against the | ||
| 480 | - /// types' real sizes. | ||
| 481 | - /// | ||
| 482 | - /// The print is the instrument: one command reproduces the whole table, | ||
| 483 | - /// biggest first, so "what is the largest by-value type in this crate" | ||
| 484 | - /// has an answer that is a measurement rather than a grep. | ||
| 485 | - /// | ||
| 486 | - /// `cargo test -p ec-opus --lib -- stack_budget -- --nocapture` is the | ||
| 487 | - /// command, with one wrinkle in THIS repo: `.cargo/config.toml` wraps | ||
| 488 | - /// every test binary in `scripts/memguard-runner.sh`, which buffers a | ||
| 489 | - /// green run's stdout and prints nothing. The table appears on a failing | ||
| 490 | - /// run, or by invoking the built binary directly | ||
| 491 | - /// (`target/debug/deps/ec_opus-* stack_budget --nocapture`). | ||
| 492 | - /// | ||
| 493 | - /// The check reds on ANY change with both numbers. That is deliberate: a | ||
| 494 | - /// by-value type that grew raises the question of whether it should have | ||
| 495 | - /// been boxed instead, and auto-accepting the new number would answer | ||
| 496 | - /// that question by default. | ||
| 497 | - #[test] | ||
| 498 | - fn the_measured_inventory_is_accurate() { | ||
| 499 | - let live = measured_by_name(); | ||
| 500 | - assert_eq!( | ||
| 501 | - BY_VALUE_TYPES.len(), | ||
| 502 | - live.len(), | ||
| 503 | - "the inventory names {} types but {} are measured; every row needs \ | ||
| 504 | - a measured size or the sweep is a list of hopes", | ||
| 505 | - BY_VALUE_TYPES.len(), | ||
| 506 | - live.len() | ||
| 507 | - ); | ||
| 508 | - let mut rows: Vec<(&str, usize)> = live.clone(); | ||
| 509 | - rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size)); | ||
| 510 | - eprintln!( | ||
| 511 | - "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)", | ||
| 512 | - rows.len(), | ||
| 513 | - STACK_BUDGET / 1024 | ||
| 514 | - ); | ||
| 515 | - eprintln!("{:>8} {:>7} TYPE", "BYTES", "%BUDGET"); | ||
| 516 | - for (name, size) in &rows { | ||
| 517 | - eprintln!( | ||
| 518 | - "{size:>8} {:>6.1}% {name}", | ||
| 519 | - *size as f64 * 100.0 / STACK_BUDGET as f64 | ||
| 520 | - ); | ||
| 521 | - } | ||
| 522 | - for (name, recorded, _public, _path) in BY_VALUE_TYPES { | ||
| 523 | - let recorded = recorded.expect("every inventory row carries a measured size"); | ||
| 524 | - let actual = live | ||
| 525 | - .iter() | ||
| 526 | - .find(|(n, _)| n == name) | ||
| 527 | - .map(|(_, size)| *size) | ||
| 528 | - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); | ||
| 529 | - assert_eq!( | ||
| 530 | - recorded, actual, | ||
| 531 | - "{name} is {actual} bytes, the inventory records {recorded}; \ | ||
| 532 | - update the table deliberately -- a by-value type that changed \ | ||
| 533 | - is a stack cost every caller of its constructor now pays" | ||
| 534 | - ); | ||
| 535 | - } | ||
| 536 | - } | ||
| 537 | - | ||
| 538 | - /// The bound, asserted BY NAME. A regression in any inventoried type reds | ||
| 539 | - /// here naming the type, not "some type is too big". | ||
| 540 | - #[test] | ||
| 541 | - fn every_by_value_type_fits_the_stack_budget() { | ||
| 542 | - let live = measured_by_name(); | ||
| 543 | - let mut checked = 0usize; | ||
| 544 | - for (name, _, public, path) in BY_VALUE_TYPES { | ||
| 545 | - if !public { | ||
| 546 | - continue; | ||
| 547 | - } | ||
| 548 | - checked += 1; | ||
| 549 | - let size = live | ||
| 550 | - .iter() | ||
| 551 | - .find(|(n, _)| n == name) | ||
| 552 | - .map(|(_, size)| *size) | ||
| 553 | - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); | ||
| 554 | - assert!( | ||
| 555 | - size <= STACK_BUDGET, | ||
| 556 | - "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \ | ||
| 557 | - stack budget ({:.2}x). It is returned by value from {path}, so \ | ||
| 558 | - every caller pays it on its own stack, and the constructors \ | ||
| 559 | - nest -- one value's size is the multiplier, not the cost. \ | ||
| 560 | - Box the large field: Encoder's six SILK slots and silk_buf, \ | ||
| 561 | - and Decoder::silk, are Boxed for exactly this reason and \ | ||
| 562 | - took Encoder from 87024 bytes to this one.", | ||
| 563 | - size as f64 / STACK_BUDGET as f64 | ||
| 564 | - ); | ||
| 565 | - } | ||
| 566 | - assert!( | ||
| 567 | - checked >= 10, | ||
| 568 | - "only {checked} rows were bound-checked; the budget must apply to \ | ||
| 569 | - every type a caller can be made to hold by value" | ||
| 570 | - ); | ||
| 571 | - // The other half of the derivation, asserted so it cannot rot: the | ||
| 572 | - // worst a caller can owe is DEEPEST_CHAIN x the worst public return. | ||
| 573 | - let worst = live | ||
| 574 | - .iter() | ||
| 575 | - .filter(|(n, _)| { | ||
| 576 | - BY_VALUE_TYPES | ||
| 577 | - .iter() | ||
| 578 | - .any(|(row, _, public, _)| row == n && *public) | ||
| 579 | - }) | ||
| 580 | - .map(|(_, size)| *size) | ||
| 581 | - .max() | ||
| 582 | - .expect("at least one public row"); | ||
| 583 | - assert!( | ||
| 584 | - DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024, | ||
| 585 | - "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \ | ||
| 586 | - public by-value return ({worst} B) is {} B, over an eighth of the \ | ||
| 587 | - 2 MiB stack an unconfigured caller hands this crate; re-derive \ | ||
| 588 | - STACK_BUDGET", | ||
| 589 | - DEEPEST_PUBLIC_CHAIN * worst | ||
| 590 | - ); | ||
| 591 | - } | ||
| 592 | - | ||
| 593 | - /// The SILK encoders and the SILK packet buffer stay BEHIND A BOX. | ||
| 594 | - /// | ||
| 595 | - /// The SILK layer, the SILK packet buffer and `Decoder::silk` stay BEHIND | ||
| 596 | - /// A BOX. Every field holding one is a `Box`, so no caller can reach them | ||
| 597 | - /// by value. What keeps them off the stack is those exact `Box` spellings, | ||
| 598 | - /// and THIS is the pin for that -- a source scan over the declarations, | ||
| 599 | - /// with a negative control so it cannot be matching a doc comment. | ||
| 600 | - /// | ||
| 601 | - /// It earned its place, measured: unboxing `silk_buf` takes `Encoder` from | ||
| 602 | - /// 4,072 to **7,896** bytes and reds this pin naming | ||
| 603 | - /// `encoder.rs::Encoder::silk_buf` and | ||
| 604 | - /// [`the_measured_inventory_is_accurate`] naming `Encoder`. Unboxing the | ||
| 605 | - /// SILK layer is far larger -- `Encoder` was 87,024 bytes before the | ||
| 606 | - /// boxing, 10.62x the budget. | ||
| 607 | - #[test] | ||
| 608 | - fn the_crate_private_silk_encoders_stay_behind_a_box() { | ||
| 609 | - const PINS: &[(&str, &str, &str)] = &[ | ||
| 610 | - ( | ||
| 611 | - "encoder.rs", | ||
| 612 | - "Encoder::silk", | ||
| 613 | - "silk: Option<Box<SilkLayer>>", | ||
| 614 | - ), | ||
| 615 | - ( | ||
| 616 | - "encoder.rs", | ||
| 617 | - "Encoder::silk_buf", | ||
| 618 | - "silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>", | ||
| 619 | - ), | ||
| 620 | - ("lib.rs", "Decoder::silk", "silk: Box<SilkDecoder>"), | ||
| 621 | - ]; | ||
| 622 | - const SCANNED: &[(&str, &str)] = &[ | ||
| 623 | - ("encoder.rs", include_str!("encoder.rs")), | ||
| 624 | - ("lib.rs", include_str!("lib.rs")), | ||
| 625 | - ]; | ||
| 626 | - for (file, field, spelling) in PINS { | ||
| 627 | - let src = SCANNED | ||
| 628 | - .iter() | ||
| 629 | - .find(|(name, _)| name == file) | ||
| 630 | - .map(|(_, src)| *src) | ||
| 631 | - .unwrap_or_else(|| panic!("no source pinned for {file}")); | ||
| 632 | - let where_ = format!("{file}::{field}"); | ||
| 633 | - assert!( | ||
| 634 | - src.contains(spelling), | ||
| 635 | - "{where_} is no longer declared `{spelling}`. An inline SILK \ | ||
| 636 | - encoder or scratch buffer there puts {field}'s bytes back on \ | ||
| 637 | - every caller's stack -- that is how Encoder was 87024 bytes \ | ||
| 638 | - and Decoder 7576 before the boxing, 10.62x the by-value budget \ | ||
| 639 | - on the type Encoder::new hands back by value." | ||
| 640 | - ); | ||
| 641 | - } | ||
| 642 | - // And the negative control: the UNBOXED spellings must be ABSENT, or | ||
| 643 | - // the scan above could be matching a doc comment instead of the live | ||
| 644 | - // declaration. The unboxed forms are what this lane removed, so their | ||
| 645 | - // absence is the proof the pin is reading the code. | ||
| 646 | - const UNBOXED: &[(&str, &str, &str)] = &[ | ||
| 647 | - ("encoder.rs", "Encoder::silk", "silk: Option<SilkLayer>,"), | ||
| 648 | - ( | ||
| 649 | - "encoder.rs", | ||
| 650 | - "Encoder::silk_buf", | ||
| 651 | - "silk_buf: [u8; MAX_SILK_PACKET_BYTES],", | ||
| 652 | - ), | ||
| 653 | - ("lib.rs", "Decoder::silk", "silk: SilkDecoder,"), | ||
| 654 | - ]; | ||
| 655 | - for (file, field, spelling) in UNBOXED { | ||
| 656 | - let src = SCANNED | ||
| 657 | - .iter() | ||
| 658 | - .find(|(name, _)| name == file) | ||
| 659 | - .map(|(_, src)| *src) | ||
| 660 | - .unwrap_or_else(|| panic!("no source pinned for {file}")); | ||
| 661 | - assert!( | ||
| 662 | - !src.contains(spelling), | ||
| 663 | - "{file}::{field} is declared unboxed as `{spelling}`. The box pin is \ | ||
| 664 | - matching a spelling that is not the live declaration, and \ | ||
| 665 | - {field}'s bytes are back on every caller's stack." | ||
| 666 | - ); | ||
| 667 | - } | ||
| 668 | - } | ||
| 669 | - | ||
| 670 | - /// CAPABILITY: really construct the heavy types on a tight stack, so a | ||
| 671 | - /// regression ABORTS THE PROCESS instead of costing invisible margin. | ||
| 672 | - /// | ||
| 673 | - /// Both arms are the crate's by-value constructors: `Encoder::new`, the | ||
| 674 | - /// type that was 87,024 bytes, and `Decoder::new`, 7,576 -- plus a real | ||
| 675 | - /// 20 ms SILK packet decoded through the `Decoder` that arm built, so the | ||
| 676 | - /// decoder is proved live on this thread rather than merely constructed. | ||
| 677 | - /// | ||
| 678 | - /// Measured stack need, **debug** build, one process per point so a | ||
| 679 | - /// SIGABRT cannot truncate the sweep: | ||
| 680 | - /// | ||
| 681 | - /// | stack | pre-fix layout (inline SILK slots) | current layout | | ||
| 682 | - /// |---|---|---| | ||
| 683 | - /// | 32768 | overflow | **overflow** | | ||
| 684 | - /// | 49152 | overflow | **ok** | | ||
| 685 | - /// | 131072 | overflow | ok | | ||
| 686 | - /// | 262144 (**the gate**) | **overflow** | **ok** | | ||
| 687 | - /// | 524288 | **overflow** | ok | | ||
| 688 | - /// | 557056 | ok | ok | | ||
| 689 | - /// | 786432 | ok | ok | | ||
| 690 | - /// | 1048576 | ok | ok | | ||
| 691 | - /// | ||
| 692 | - /// The gate sits at 256 KiB, **5.3x** the measured need of the current | ||
| 693 | - /// layout and **2.1x** below the pre-fix layout's own threshold. Note | ||
| 694 | - /// what the upper rows say: the pre-fix layout SURVIVED 1 MiB and 2 MiB, | ||
| 695 | - /// so a gate set at 1 MiB would have been a formality -- a test that | ||
| 696 | - /// passes for the old layout proves nothing. `EC_OPUS_TIGHT_STACK_BYTES` | ||
| 697 | - /// overrides the size, which is how the table is reproduced. | ||
| 698 | - /// | ||
| 699 | - /// The results are checked, not just the absence of a crash: an `Encoder` | ||
| 700 | - /// that constructed but came back with the wrong channel count, or a | ||
| 701 | - /// `Decoder` that decoded a packet to silence, would both pass a | ||
| 702 | - /// "did not overflow" assertion. | ||
| 703 | - #[test] | ||
| 704 | - fn the_deepest_by_value_constructors_fit_on_a_tight_stack() { | ||
| 705 | - use crate::encoder::Application; | ||
| 706 | - let stack: usize = std::env::var("EC_OPUS_TIGHT_STACK_BYTES") | ||
| 707 | - .ok() | ||
| 708 | - .and_then(|v| v.parse().ok()) | ||
| 709 | - .unwrap_or(TIGHT_STACK); | ||
| 710 | - let handle = std::thread::Builder::new() | ||
| 711 | - .stack_size(stack) | ||
| 712 | - .spawn(move || { | ||
| 713 | - // Arm 1: the by-value constructor that was 10.62x the budget. | ||
| 714 | - let encoder = Encoder::new(48000, 1, Application::Audio) | ||
| 715 | - .expect("Encoder::new(48000, 1, Audio)"); | ||
| 716 | - let channels = encoder.channels(); | ||
| 717 | - let rate = encoder.sample_rate(); | ||
| 718 | - drop(encoder); | ||
| 719 | - let mut decoder = Decoder::new(48000, 1).expect("Decoder::new(48000, 1)"); | ||
| 720 | - // A real packet, so the decoder is proved live on this thread | ||
| 721 | - // rather than merely constructed: the SILK-only 20 ms packet | ||
| 722 | - // below decodes through the same by-value Decoder. | ||
| 723 | - let mut out = vec![0.0f32; 5760]; | ||
| 724 | - let written = decoder | ||
| 725 | - .decode_float(SILK_ONLY_PACKET, &mut out) | ||
| 726 | - .expect("decode_float on the tight-stack thread"); | ||
| 727 | - let peak = out[..written].iter().fold(0.0f32, |m, s| m.max(s.abs())); | ||
| 728 | - (channels, rate, written, peak) | ||
| 729 | - }) | ||
| 730 | - .expect("spawn tight-stack thread"); | ||
| 731 | - let (channels, rate, pcm_len, peak) = handle.join().unwrap_or_else(|_| { | ||
| 732 | - panic!( | ||
| 733 | - "a by-value constructor overflowed a {stack}-byte stack; \ | ||
| 734 | - EC_OPUS_TIGHT_STACK_BYTES reproduces the threshold sweep" | ||
| 735 | - ) | ||
| 736 | - }); | ||
| 737 | - assert_eq!(channels, 1, "Encoder::new lost its channel count"); | ||
| 738 | - assert_eq!(rate, 48000, "Encoder::new lost its sample rate"); | ||
| 739 | - assert_eq!( | ||
| 740 | - pcm_len, 960, | ||
| 741 | - "Decoder::decode_float returned {pcm_len} samples, not the 960 one \ | ||
| 742 | - 20 ms mono frame at 48 kHz holds; the tight-stack thread built a \ | ||
| 743 | - Decoder that cannot decode" | ||
| 744 | - ); | ||
| 745 | - assert!( | ||
| 746 | - peak > 0.0, | ||
| 747 | - "Decoder::decode_float returned silence (peak {peak}) on the \ | ||
| 748 | - tight-stack thread" | ||
| 749 | - ); | ||
| 750 | - eprintln!( | ||
| 751 | - "TIGHTSTACK {stack} bytes: Encoder={} Decoder={} SilkDecoder={} \ | ||
| 752 | - bytes, both constructors returned and decoded 960 samples", | ||
| 753 | - std::mem::size_of::<Encoder>(), | ||
| 754 | - std::mem::size_of::<Decoder>(), | ||
| 755 | - std::mem::size_of::<crate::silk::SilkDecoder>(), | ||
| 756 | - ); | ||
| 757 | - } | ||
| 758 | - | ||
| 759 | - /// A SILK-only 20 ms Opus packet: TOC byte `0x48` (config 9 = SILK | ||
| 760 | - /// wideband 20 ms, stereo bit 0, code 0 = SILK only) followed by a frame | ||
| 761 | - /// count byte `0x00` (one frame) and a 100-byte payload. Config 9 is | ||
| 762 | - /// SILK-only, so decoding it exercises `SilkDecoder`'s state rather than | ||
| 763 | - /// CELT's, and the crate decodes it to exactly 960 samples at 48 kHz. | ||
| 764 | - const SILK_ONLY_PACKET: &[u8] = &[ | ||
| 765 | - 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
| 766 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
| 767 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
| 768 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
| 769 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
| 770 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
| 771 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
| 772 | - ]; | ||
| 773 | - | ||
| 774 | - /// The sweep's teeth against a NEW by-value return: re-derive the set from | ||
| 775 | - /// the crate source and require every name to be inventoried. | ||
| 776 | - /// | ||
| 777 | - /// Without this the inventory is a list of what someone remembered to | ||
| 778 | - /// measure, and a lane that adds `pub fn make() -> HugeThing` where | ||
| 779 | - /// `HugeThing` is 200 KB of inline tables passes every other test here. | ||
| 780 | - #[test] | ||
| 781 | - fn every_by_value_public_return_is_in_the_inventory() { | ||
| 782 | - let mut found: Vec<(String, String)> = Vec::new(); | ||
| 783 | - for (file, src) in FILES { | ||
| 784 | - for (n, line) in src.lines().enumerate() { | ||
| 785 | - if let Some(name) = by_value_return_name(line) { | ||
| 786 | - found.push((name, format!("{file}:{}", n + 1))); | ||
| 787 | - } | ||
| 788 | - } | ||
| 789 | - } | ||
| 790 | - found.sort(); | ||
| 791 | - found.dedup(); | ||
| 792 | - assert!( | ||
| 793 | - found.len() > 5, | ||
| 794 | - "the by-value return scan found {} names across {} files, which is \ | ||
| 795 | - too few to be a real sweep -- the matcher, not the crate, is broken", | ||
| 796 | - found.len(), | ||
| 797 | - FILES.len() | ||
| 798 | - ); | ||
| 799 | - | ||
| 800 | - let mut missing = Vec::new(); | ||
| 801 | - for (name, site) in &found { | ||
| 802 | - if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) { | ||
| 803 | - missing.push(format!("{name} ({site})")); | ||
| 804 | - } | ||
| 805 | - } | ||
| 806 | - assert!( | ||
| 807 | - missing.is_empty(), | ||
| 808 | - "these types are returned BY VALUE from a public fn and are not in \ | ||
| 809 | - the inventory: {}. Either they are thin enough not to be a stack \ | ||
| 810 | - cost -- say so by adding a row with its measured size -- or they \ | ||
| 811 | - are the next instance of the class this module exists for.", | ||
| 812 | - missing.join(", ") | ||
| 813 | - ); | ||
| 814 | - } | ||
| 815 | - | ||
| 816 | - /// The control for the scan above, on synthetic text rather than by | ||
| 817 | - /// trusting the live tree to happen to contain a case. | ||
| 818 | - /// | ||
| 819 | - /// If the matcher silently stopped recognising a shape, the sweep would | ||
| 820 | - /// pass everything and this would still be asserting nothing. So: every | ||
| 821 | - /// by-value spelling the crate uses must yield its type name, and every | ||
| 822 | - /// pointer/Vec/primitive/`Self` spelling must yield nothing. | ||
| 823 | - #[test] | ||
| 824 | - fn the_inventory_scan_is_not_vacuous() { | ||
| 825 | - for synthetic in [ | ||
| 826 | - "pub fn zz_a() -> ZzNotInventoried { todo!() }", | ||
| 827 | - "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }", | ||
| 828 | - "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }", | ||
| 829 | - "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }", | ||
| 830 | - "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }", | ||
| 831 | - ] { | ||
| 832 | - let name = by_value_return_name(synthetic) | ||
| 833 | - .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`")); | ||
| 834 | - assert_eq!( | ||
| 835 | - name, "ZzNotInventoried", | ||
| 836 | - "the matcher mangled `{synthetic}` into `{name}`, so the sweep \ | ||
| 837 | - cannot see a new by-value return and its green is vacuous" | ||
| 838 | - ); | ||
| 839 | - assert!( | ||
| 840 | - !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name), | ||
| 841 | - "the synthetic control name is in the inventory, so the control \ | ||
| 842 | - proves nothing" | ||
| 843 | - ); | ||
| 844 | - } | ||
| 845 | - for thin in [ | ||
| 846 | - "pub fn zz_t() -> Box<Decoder> { todo!() }", | ||
| 847 | - "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }", | ||
| 848 | - "pub fn zz_v() -> Option<&Path> { todo!() }", | ||
| 849 | - "pub fn zz_w() -> usize { todo!() }", | ||
| 850 | - "pub fn zz_x() -> Self { todo!() }", | ||
| 851 | - "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }", | ||
| 852 | - "pub fn zz_z() { todo!() }", | ||
| 853 | - "fn zz_private() -> ZzNotInventoried { todo!() }", | ||
| 854 | - ] { | ||
| 855 | - assert_eq!( | ||
| 856 | - by_value_return_name(thin), | ||
| 857 | - None, | ||
| 858 | - "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \ | ||
| 859 | - above already cover, or not a `pub fn` -- the matcher must not \ | ||
| 860 | - read it as an uninventoried by-value return" | ||
| 861 | - ); | ||
| 862 | - } | ||
| 863 | - } | ||
| 864 | -} | ||