Repository navigation
Expand file tree
/
Copy pathstack.rs
More file actions
522 lines (480 loc) · 24.2 KB
/
Copy pathstack.rs
File metadata and controls
522 lines (480 loc) · 24.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Stack-budget guard for the recursive walkers (#1581).
//!
//! Every language walker recurses per AST level (`visit_node` →
//! `visit_for_calls_and_structure` → …). tree-sitter's own parser is
//! iterative, so a pathologically nested file — clang's
//! `parser_overflow.c` nests 16,384 `{`, fuzzer corpora go deeper — parses
//! fine and then overflows the WALKER's native stack. A native overflow is
//! uncatchable: the parse worker is a thread of the `codegraph` process, so
//! the SIGSEGV takes the whole indexer down with no message, no partial
//! index and no per-file fallback. Worker threads get Node's 4 MiB default
//! stack; the main thread's 8 MiB only moves the cliff (100k levels still
//! kill it).
//!
//! The guard turns "about to overflow" into the kernel's existing `defer:`
//! routing signal: `exhausted()` is checked at the top of every recursive
//! walker function (the `stack_guard!` macro in lib.rs), returns `true` once
//! the stack pointer is within `RED_ZONE` of the thread's stack limit, and
//! latches a per-thread flag. `run_guarded` wraps a whole extraction: when
//! the flag is set afterwards the result is discarded and replaced by a
//! `defer:` error, which the TS side (`src/extraction/kernel/index.ts`)
//! already treats as "this file takes the wasm path" — and the wasm walker
//! catches its own JS `RangeError` per file, so the file lands as a partial
//! result with a recorded parse error instead of a dead process.
//!
//! The per-thread stack bounds come from the OS (glibc/musl
//! `pthread_getattr_np`, macOS `pthread_get_stackaddr_np`, Win32
//! `GetCurrentThreadStackLimits`), computed once per thread and cached, so
//! the guard is exact on the 4 MiB worker, the 8 MiB main thread and any
//! `resourceLimits.stackSizeMb` alike. Where the bounds are unavailable the
//! guard falls back to a fixed descent budget measured from the entry stack
//! pointer. Hot path: one thread-local load and one compare.
//!
//! The same guard holds each extraction's string arena to a budget
//! (`arena_budget_for`): a chain nested D levels deep stores the rest of the
//! chain as a callee name at every level in several walkers, so its arena
//! grows with D squared, and a 2 MB file asked for tens of gigabytes — an
//! allocation failure, which is not a panic and aborts the process.
//! `run_guarded` arms the budget for the thread, `Arena::put` checks it before
//! copying, and a string past it trips the guard by setting the stack
//! threshold above every stack pointer: the walkers unwind through the
//! `stack_guard!()` they already start with, with no second check on the hot
//! path, and the file defers. Every piece of this is per thread and reset at
//! the start of each extraction, so extractions may run on many threads.
use std::cell::Cell;
/// Headroom kept free below the deepest walker frame: the napi return path,
/// tree-sitter's node accessors and the error formatting all still need to
/// run after the guard trips, and the frames BETWEEN two guard checks (an
/// `extract_class` between two `visit_node`s) are never more than a few KiB.
const RED_ZONE: usize = 256 * 1024;
/// Descent budget when the OS can't report the thread's stack bounds — safe
/// on anything from Node's 4 MiB worker default upwards.
const FALLBACK_BUDGET: usize = 1024 * 1024;
/// The arena budget of one extraction (see `arena_budget_for`): a fixed
/// allowance, plus so many arena bytes per source byte, never past the cap.
pub const ARENA_BUDGET_BASE: usize = 64 << 20;
pub const ARENA_BUDGET_PER_SOURCE_BYTE: usize = 32;
/// Under 4 GiB, so an arena offset (a `u32`) can never wrap.
pub const ARENA_BUDGET_CAP: usize = 3 << 30;
thread_local! {
/// Lowest stack-pointer value the walker may reach before the guard
/// trips. `0` = not computed yet for this thread. `usize::MAX` once the
/// arena budget is passed: every stack pointer is below it, so the
/// guard's one compare unwinds the walk with no second check.
static THRESHOLD: Cell<usize> = const { Cell::new(0) };
/// The threshold from the thread's real OS bounds, fixed for its
/// lifetime; `0` while not computed, or where the OS can't say (the
/// per-call fallback budget is used then).
static OS_THRESHOLD: Cell<usize> = const { Cell::new(0) };
/// Latched by `exhausted()`; read by `run_guarded` after the walk.
static OVERFLOWED: Cell<bool> = const { Cell::new(false) };
/// The arena budget of the extraction running on this thread, read once
/// when its `Arena` is made. Outside `run_guarded`, the cap.
static ARENA_LIMIT: Cell<usize> = const { Cell::new(ARENA_BUDGET_CAP) };
/// Latched by `pass_arena_budget()`; read by `run_guarded` after the walk.
static ARENA_PASSED: Cell<bool> = const { Cell::new(false) };
}
/// Approximate current stack pointer: the address of a local. Stacks grow
/// downward on every target the kernel ships for (x86_64 / aarch64).
#[inline(always)]
fn current_sp() -> usize {
let marker = 0u8;
std::hint::black_box(&marker) as *const u8 as usize
}
/// Low (deepest) address of the calling thread's stack, from the OS.
#[cfg(target_os = "linux")]
fn os_stack_low() -> Option<usize> {
// SAFETY: plain pthread queries on the calling thread; `attr` is
// initialised by pthread_getattr_np and destroyed before returning.
unsafe {
let mut attr: libc::pthread_attr_t = std::mem::zeroed();
if libc::pthread_getattr_np(libc::pthread_self(), &mut attr) != 0 {
return None;
}
let mut addr: *mut libc::c_void = std::ptr::null_mut();
let mut size: libc::size_t = 0;
let rc = libc::pthread_attr_getstack(&attr, &mut addr, &mut size);
libc::pthread_attr_destroy(&mut attr);
if rc != 0 || addr.is_null() || size == 0 {
return None;
}
Some(addr as usize)
}
}
#[cfg(target_os = "macos")]
fn os_stack_low() -> Option<usize> {
// SAFETY: plain pthread queries on the calling thread.
unsafe {
let me = libc::pthread_self();
// pthread_get_stackaddr_np returns the HIGH end (the stack base).
let high = libc::pthread_get_stackaddr_np(me) as usize;
let size = libc::pthread_get_stacksize_np(me);
if high == 0 || size == 0 || size > high {
return None;
}
Some(high - size)
}
}
#[cfg(windows)]
fn os_stack_low() -> Option<usize> {
#[link(name = "kernel32")]
extern "system" {
// Win8+ (the bundled Node runtime needs Win10 anyway). Reports the
// full RESERVED range; Windows commits pages on demand down to it.
fn GetCurrentThreadStackLimits(low_limit: *mut usize, high_limit: *mut usize);
}
let mut low: usize = 0;
let mut high: usize = 0;
// SAFETY: both out-pointers are valid for the duration of the call.
unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) };
if low == 0 || high <= low {
return None;
}
Some(low)
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
fn os_stack_low() -> Option<usize> {
None
}
/// Arm the guard for one extraction on the calling thread: clear the latch
/// and (re)compute the threshold. OS bounds are computed once per thread;
/// the fallback budget is re-anchored at every call's entry stack pointer.
/// The threshold is written at every call, so a budget passed in the last
/// extraction (which set it to `usize::MAX`) never outlives it.
pub fn begin() {
OVERFLOWED.with(|o| o.set(false));
let os = OS_THRESHOLD.with(|t| t.get());
if os != 0 {
THRESHOLD.with(|t| t.set(os));
return;
}
match os_stack_low() {
Some(low) => {
let threshold = low.saturating_add(RED_ZONE);
OS_THRESHOLD.with(|t| t.set(threshold));
THRESHOLD.with(|t| t.set(threshold));
}
None => {
THRESHOLD.with(|t| t.set(current_sp().saturating_sub(FALLBACK_BUDGET).max(1)));
}
}
}
/// The arena budget of one extraction: 64 MiB, plus 32 bytes per byte of
/// source, capped at 3 GiB. A callee name is the text of a subtree, so a
/// chain nested D levels deep (`f()()()…`, `a.b().c().d()…`) stores the rest
/// of the chain at every level and its arena grows with D squared; the budget
/// turns that into a deferral where it would otherwise end in an allocation
/// failure, which aborts the process. Real code stays far below it.
pub fn arena_budget_for(source_len: usize) -> usize {
ARENA_BUDGET_BASE
.saturating_add(source_len.saturating_mul(ARENA_BUDGET_PER_SOURCE_BYTE))
.min(ARENA_BUDGET_CAP)
}
/// The arena budget of the extraction running on this thread. Read by
/// `Arena::default()`, once per extraction, so `Arena::put` checks a field of
/// its own and never a thread-local.
pub fn arena_limit() -> usize {
ARENA_LIMIT.with(|l| l.get())
}
/// Called by `Arena::put` when a string would take the arena past its budget:
/// latch it, and set the stack threshold above every stack pointer, so the
/// next `stack_guard!()` in any walker returns at once and the walk unwinds as
/// it does on a stack overflow. `begin()` restores the threshold.
#[cold]
pub fn pass_arena_budget() {
ARENA_PASSED.with(|p| p.set(true));
THRESHOLD.with(|t| t.set(usize::MAX));
}
/// Whether the arena budget was passed since the last `run_guarded` began.
pub fn arena_budget_passed() -> bool {
ARENA_PASSED.with(|p| p.get())
}
/// `true` once the walker has descended to within `RED_ZONE` of the stack
/// limit. Latches `OVERFLOWED` so `run_guarded` can discard the result. A
/// thread that never called `begin()` (a direct unit-test call) arms itself
/// lazily from the current position.
#[inline(always)]
pub fn exhausted() -> bool {
let threshold = THRESHOLD.with(|t| t.get());
if threshold == 0 {
begin();
return exhausted();
}
if current_sp() < threshold {
OVERFLOWED.with(|o| o.set(true));
true
} else {
false
}
}
/// Whether the guard tripped since the last `begin()`.
pub fn overflowed() -> bool {
OVERFLOWED.with(|o| o.get())
}
/// Run one extraction of a `source_len`-byte source under the guard and the
/// arena budget (`arena_budget_for`). A walk that tripped either returns a
/// `defer:` error — the TS side's routine "take the wasm path" signal —
/// regardless of what the truncated walk produced.
pub fn run_guarded<T>(source_len: usize, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
run_guarded_with_arena_budget(arena_budget_for(source_len), f)
}
/// `run_guarded` with the arena budget given. Both latches are reset when it
/// begins, the budget is armed for this thread while `f` runs, and the
/// thread is left with the cap and its real stack threshold afterwards, so a
/// direct walker call later on the same thread (a unit test) is not cut short
/// by this run's budget.
pub fn run_guarded_with_arena_budget<T>(
arena_budget: usize,
f: impl FnOnce() -> Result<T, String>,
) -> Result<T, String> {
begin();
ARENA_PASSED.with(|p| p.set(false));
ARENA_LIMIT.with(|l| l.set(arena_budget.min(ARENA_BUDGET_CAP)));
let out = f();
ARENA_LIMIT.with(|l| l.set(ARENA_BUDGET_CAP));
if arena_budget_passed() {
// The threshold was set above every stack pointer; `begin()` puts
// the real one back (and leaves the overflow latch cleared).
begin();
return Err(
"defer: the walk passed its arena budget (a long nested chain) — wasm recovery handles it"
.to_string(),
);
}
if overflowed() {
return Err(
"defer: nesting too deep for the native walker — wasm recovery handles it".to_string(),
);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// 1 MiB is a quarter of Node's worker default; a guard that holds here
/// holds on every real thread. Without the guard these walks SIGSEGV the
/// test process instead of failing an assertion.
const SMALL_STACK: usize = 1 << 20;
const DEPTH: usize = 30_000;
fn on_small_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
std::thread::Builder::new()
.stack_size(SMALL_STACK)
.spawn(f)
.expect("spawn")
.join()
.expect("walker thread panicked")
}
fn nested_parens(prefix: &str, suffix: &str) -> String {
format!("{prefix}{}1{}{suffix}", "(".repeat(DEPTH), ")".repeat(DEPTH))
}
#[test]
fn os_bounds_are_sane_on_this_platform() {
// Every shipped target has an OS implementation; the fallback budget
// is only for platforms the kernel is not built for.
let low = os_stack_low().expect("OS stack bounds available");
let sp = current_sp();
assert!(low < sp, "stack low {low:#x} must be below the current sp {sp:#x}");
assert!(sp - low < 1 << 31, "implausible stack size {}", sp - low);
}
#[test]
fn small_stack_reports_its_own_bounds() {
on_small_stack(|| {
let low = os_stack_low().expect("OS stack bounds available");
let used = current_sp() - low;
// std/the OS round the requested size up a little (macOS reports
// 1,060,864 for a 1 MiB request); the point is that the bounds
// describe THIS thread's small stack, not the main thread's.
assert!(
used <= SMALL_STACK + 128 * 1024,
"used {used} is not within the {SMALL_STACK}-byte stack"
);
});
}
#[test]
fn deep_braces_c_defer_instead_of_crashing() {
let src = format!("void foo(void) {{\n{}{}\n}}\n", "{".repeat(DEPTH), "}".repeat(DEPTH));
let r = on_small_stack(move || run_guarded(src.len(), || crate::ccpp::extract("deep.c", &src, "c")));
let err = r.err().expect("deep nesting must defer");
assert!(err.starts_with("defer:"), "unexpected error: {err}");
}
type Extract = fn(&str) -> Result<crate::buffers::EmitOut, String>;
#[test]
fn deep_parens_cpp_rust_ts_python_defer_instead_of_crashing() {
let cases: [(&str, Extract, String); 4] = [
("deep.cpp", |s| crate::ccpp::extract("deep.cpp", s, "cpp"), nested_parens("int f() { return ", "; }\n")),
("deep.rs", |s| crate::rustlang::extract("deep.rs", s), nested_parens("fn f() -> i32 { ", " }\n")),
("deep.ts", |s| crate::tsjs::extract("deep.ts", s, "typescript"), nested_parens("function f() { return ", "; }\n")),
("deep.py", |s| crate::python::extract("deep.py", s), nested_parens("def f():\n return ", "\n")),
];
for (name, extract, src) in cases {
let r = on_small_stack(move || run_guarded(src.len(), || extract(&src)));
let err = r.err().unwrap_or_else(|| panic!("{name}: deep nesting must defer"));
assert!(err.starts_with("defer:"), "{name}: unexpected error: {err}");
}
}
#[test]
fn normal_files_are_untouched_by_the_guard() {
let src = "int add(int a, int b) { return a + b; }\nint main(void) { return add(1, 2); }\n";
let r = on_small_stack(move || run_guarded(src.len(), || crate::ccpp::extract("ok.c", src, "c")));
assert!(r.is_ok(), "a shallow file must not defer: {:?}", r.err());
assert!(!overflowed());
}
#[test]
fn latch_resets_between_runs() {
let deep = format!("void foo(void) {{\n{}{}\n}}\n", "{".repeat(DEPTH), "}".repeat(DEPTH));
on_small_stack(move || {
assert!(run_guarded(deep.len(), || crate::ccpp::extract("deep.c", &deep, "c")).is_err());
// The latch from the deep file must not poison the next, shallow one.
let ok = run_guarded(7, || crate::ccpp::extract("ok.c", "int x;\n", "c"));
assert!(ok.is_ok(), "latch leaked into the next run: {:?}", ok.err());
});
}
// --- the arena budget -----------------------------------------------------
/// Node's worker default, the stack every production extraction runs on.
const WORKER_STACK: usize = 4 << 20;
const ARENA_DEFER: &str = "defer: the walk passed its arena budget";
const NESTING_DEFER: &str = "defer: nesting too deep";
fn on_worker_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
std::thread::Builder::new()
.stack_size(WORKER_STACK)
.spawn(f)
.expect("spawn")
.join()
.expect("walker thread panicked")
}
/// `prefix` + `unit` × n + `suffix`, `bytes` long or a little under.
fn chain(prefix: &str, unit: &str, suffix: &str, bytes: usize) -> String {
let n = (bytes - prefix.len() - suffix.len()) / unit.len();
format!("{prefix}{}{suffix}", unit.repeat(n))
}
/// The chains the walkers store as one callee name per level, 100 KB
/// each. Without the budget each asks for gigabytes (measured on the base
/// kernel in a 4 MiB worker: a peak of 1.5 to 3 GB before the stack guard
/// stopped the walk; at 2 MB, past 4 GB in two seconds).
fn quadratic_chains() -> Vec<(&'static str, Extract, String)> {
const KB100: usize = 100_000;
vec![
("python f()()…", |s| crate::python::extract("x.py", s), chain("def g():\n return f", "()", "\n", KB100)),
("lua f()()…", |s| crate::lua::extract("x.lua", s, "lua"), chain("function g()\n return f", "()", "\nend\n", KB100)),
("lua a:b():b()…", |s| crate::lua::extract("x.lua", s, "lua"), chain("function g()\n return a", ":b()", "\nend\n", KB100)),
("java a.b().b()…", |s| crate::java::extract("X.java", s), chain("class X { void m() { a", ".b()", "; } }\n", KB100)),
("r f()()…", |s| crate::rlang::extract("x.R", s), chain("x <- f", "()", "\n", KB100)),
("scala f()()…", |s| crate::scala::extract("x.scala", s), chain("object O { val x = f", "()", " }\n", KB100)),
]
}
/// Small files of the same languages, and their arenas with no budget.
fn normal_files() -> Vec<(&'static str, Extract, &'static str)> {
vec![
("python", |s| crate::python::extract("ok.py", s), "def f(a):\n return g(a).h()\n"),
("lua", |s| crate::lua::extract("ok.lua", s, "lua"), "function f(a)\n return g(a):h()\nend\n"),
("java", |s| crate::java::extract("Ok.java", s), "class Ok { int f(int a) { return g(a).h(); } }\n"),
("typescript", |s| crate::tsjs::extract("ok.ts", s, "typescript"), "export function f(a: number) { return g(a).h(); }\n"),
]
}
#[test]
fn quadratic_chains_defer_on_the_arena_budget() {
for (name, extract, src) in quadratic_chains() {
let r = on_worker_stack(move || {
let r = run_guarded(src.len(), || extract(&src));
(r.err(), arena_budget_passed())
});
let err = r.0.unwrap_or_else(|| panic!("{name}: a chain past the budget must defer"));
assert!(err.starts_with(ARENA_DEFER), "{name}: unexpected error: {err}");
assert!(r.1, "{name}: the budget latch must be set");
}
}
/// TypeScript stores a call chain only while it is a dotted name, so its
/// arena grows with the square of a chain's depth on nested named
/// functions instead (each signature holds the rest), and that shape is
/// slow to build past the real budget in the TS walker itself. The same
/// path is shown with a budget below what the file needs.
#[test]
fn typescript_defers_on_a_budget_it_passes() {
// `function a(p = function a(p = … 0){}){}`: 60 levels.
let src = format!("const z = {}0{};\n", "function a(p = ".repeat(60), "){}".repeat(60));
let full = on_worker_stack({
let src = src.clone();
move || run_guarded(src.len(), || crate::tsjs::extract("x.ts", &src, "typescript"))
})
.expect("under the real budget the file extracts");
assert!(full.arena.len() > 16 * 1024, "the file needs {} arena bytes", full.arena.len());
let r = on_worker_stack(move || {
run_guarded_with_arena_budget(16 * 1024, || crate::tsjs::extract("x.ts", &src, "typescript")).err()
});
let err = r.expect("past its budget the file must defer");
assert!(err.starts_with(ARENA_DEFER), "unexpected error: {err}");
}
/// A file far under the budget gives byte for byte what the walker gives
/// with no budget armed at all.
#[test]
fn normal_files_are_untouched_by_the_arena_budget() {
for (name, extract, src) in normal_files() {
let (guarded, passed, direct) = on_worker_stack(move || {
let guarded = run_guarded(src.len(), || extract(src)).expect("a normal file extracts");
let passed = arena_budget_passed();
let direct = extract(src).expect("a normal file extracts");
(guarded, passed, direct)
});
assert!(!passed, "{name}: the budget latch must stay clear");
assert_eq!(guarded.arena, direct.arena, "{name}: arena");
assert_eq!(guarded.nodes, direct.nodes, "{name}: nodes");
assert_eq!(guarded.edges, direct.edges, "{name}: edges");
assert_eq!(guarded.refs, direct.refs, "{name}: refs");
}
}
/// After a file passes its budget, the next file on the thread extracts
/// normally, the stack guard is back at its real threshold (a deep file
/// still defers for nesting, not for the arena), and a direct walker call
/// outside `run_guarded` is not cut short.
#[test]
fn arena_latch_resets_between_runs() {
let (python, _, deep_chain) = quadratic_chains().into_iter().next().unwrap();
let deep = format!("void foo(void) {{\n{}{}\n}}\n", "{".repeat(DEPTH), "}".repeat(DEPTH));
on_worker_stack(move || {
let r = run_guarded(deep_chain.len(), || crate::python::extract("x.py", &deep_chain));
assert!(r.err().is_some_and(|e| e.starts_with(ARENA_DEFER)), "{python}: must defer");
assert!(!exhausted(), "the threshold must not outlive the run");
assert_eq!(arena_limit(), ARENA_BUDGET_CAP, "the budget must not outlive the run");
for (name, extract, src) in normal_files() {
let ok = run_guarded(src.len(), || extract(src));
assert!(ok.is_ok(), "{name}: the latch leaked into the next run: {:?}", ok.err());
assert!(!arena_budget_passed(), "{name}: the latch must be clear");
}
assert!(crate::python::extract("ok.py", "def f():\n return g()\n").is_ok());
let r = run_guarded(deep.len(), || crate::ccpp::extract("deep.c", &deep, "c"));
assert!(r.err().is_some_and(|e| e.starts_with(NESTING_DEFER)), "deep nesting must still defer as nesting");
});
}
/// `Arena::put` checks before it copies: past the budget it copies
/// nothing, returns an empty reference at the current end, and trips the
/// guard; `put_list` checks the joined length before it joins.
#[test]
fn arena_put_stops_at_the_budget() {
on_worker_stack(|| {
let r: Result<(), String> = run_guarded_with_arena_budget(10, || {
let mut a = crate::buffers::Arena::default();
assert_eq!(a.put("12345678"), (0, 8));
assert!(!exhausted());
assert_eq!(a.put("abc"), (8, 0), "past the budget: an empty reference");
assert_eq!(a.len(), 8, "nothing copied");
assert!(arena_budget_passed());
assert!(exhausted(), "the guard unwinds every walker from here");
assert_eq!(a.put_list(&["a".to_string(), "b".to_string()]), (8, 0));
assert_eq!(a.put("xy"), (8, 2), "a string that fits still fits");
assert_eq!(a.into_vec(), b"12345678xy");
Ok(())
});
assert!(r.err().is_some_and(|e| e.starts_with(ARENA_DEFER)));
let mut a = crate::buffers::Arena::default();
assert_eq!(a.put_list(&["a".to_string(), "b".to_string()]), (0, 3));
});
}
#[test]
fn arena_budget_formula() {
assert_eq!(arena_budget_for(0), 64 << 20);
assert_eq!(arena_budget_for(1_000_000), (64 << 20) + 32_000_000);
assert_eq!(arena_budget_for(usize::MAX), 3 << 30);
assert_eq!(arena_budget_for(100 << 20), 3 << 30);
assert!(ARENA_BUDGET_CAP < u32::MAX as usize);
}
}