vile / scheme / arena_usage.v
52 lines · 48 sloc · 1.8 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import arena
4
5// ArenaUsageLimitRequest reports the usage observed before request/cleanup
6// allocations. It contains no borrowed VM, arena, or context pointer.
7pub struct ArenaUsageLimitRequest {
8 Error
9pub:
10 limit i64
11 used i64
12}
13
14pub fn (request &ArenaUsageLimitRequest) msg() string {
15 return 'arena usage limit exceeded: ${request.used} bytes used; limit ${request.limit}'
16}
17
18// with_arena_usage_limit samples the absolute current used() of a host-owned
19// arena at execution entries, between instructions and after successful work.
20// The arena must be current on entry and remain alive throughout work. Zero
21// disables this added limit; active ancestor controls still apply.
22//
23// This is a cooperative usage check, not a hard allocator or OOM cap. Parsing,
24// compilation and native calls can overshoot or shrink again between checks.
25// Capacity, private scratch arenas, other allocators/threads and resource handles
26// are outside this count. The controller itself and prior arena allocations count.
27// The scope does not reset/free/pop the arena or change Value/error ownership.
28pub fn (mut vm VM) with_arena_usage_limit(region &arena.Arena, limit i64, work EvaluationFn) !Value {
29 vm.ready()!
30 if limit < 0 { return failure('arena usage limit must be nonnegative') }
31 if !region.is_current() { return failure('arena usage limit requires the current arena') }
32 if limit == 0 {
33 vm.check_entry_control()!
34 result := work(mut vm)!
35 vm.check_entry_control()!
36 return result
37 }
38 mut state := vm.system_state()
39 previous := state.evaluation
40 control := &EvaluationControl{
41 previous: previous
42 kind: .arena_usage
43 region: region
44 limit: limit
45 }
46 state.evaluation = control
47 defer { state.evaluation = previous }
48 control.check_control()!
49 result := work(mut vm)!
50 control.check_control()!
51 return result
52}
53