diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 22:03:14 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 22:23:51 -0300 |
| commit | 99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 (patch) | |
| tree | 813596ea84318a7bae4fd7416ba463de8e3b7107 /core/memory.zig | |
| parent | 92d553123673376adf6126ab90d49a22c5b833d2 (diff) | |
| download | pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.tar.gz pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.zip | |
core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/memory.zig')
| -rw-r--r-- | core/memory.zig | 565 |
1 files changed, 565 insertions, 0 deletions
diff --git a/core/memory.zig b/core/memory.zig new file mode 100644 index 00000000..c628ae49 --- /dev/null +++ b/core/memory.zig @@ -0,0 +1,565 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const config = @import("pardes_config"); + +const KiB = 1024; +const MiB = 1024 * KiB; + +pub const limits = struct { + pub const max_file_bytes = 256 * MiB; + pub const max_stream_bytes = 4 * MiB; + pub const effect_cap = 4096; + pub const pending_write_cap: usize = 4 * MiB; + pub const wrap_rows = 256; + pub const undo_max = 256; + /// The text a file's undo and redo steps hold together, kept by dropping + /// the oldest; the newest step always stays, so the bound per file is + /// this plus one snapshot (at most max_file_bytes). + pub const undo_bytes: usize = 64 * MiB; + pub const message_log = 128; + /// ranges one selection holds; helix has no limit, and a `%s` over a + /// file's words wants hundreds + pub const selections = 1024; + /// /log's ring, which records whether or not anyone reads it. + pub const log_bytes: usize = 64 * KiB; + pub const max_tag_tail: usize = 4096; + /// What the core's per-step scratch arena and the frame arena keep + /// between steps: a step that needed more (a huge Callstack's sources) + /// gives the rest back instead of holding its high-water mark. + pub const scratch_kept: usize = 16 * MiB; + pub const frame_kept: usize = 16 * MiB; + /// The other open files one language query copies for its server, in + /// bytes: past it the rest are left out (the asked file always goes). + pub const lsp_snapshot_bytes: usize = 64 * MiB; + /// One paste, from any shell: past it, the rest is left out and said. + pub const max_paste_bytes: usize = 4 * MiB; + pub const host_path_cap: usize = 4095; + /// -Dembed-sources: the editor serves its own sources under /src. + pub const embedded_sources = config.embed_sources; + + /// Each arena's fixed region. On a native target these are address + /// space reserved at startup, resident only where used (`Pages`), so + /// they are sized for the worst case: the core holds a 256 MiB file, its + /// edit's copy and its undo. + pub const arena = struct { + pub const pardes = 1024 * MiB; + pub const frame = 64 * MiB; + pub const lsp = 512 * MiB; + /// What a native shell allocates itself (`host`): its screen, the + /// bytes its ptys read, its 9P connections, its pipe jobs. + pub const host = 512 * MiB; + pub const tree_sitter = 256 * MiB; + pub const image = 256 * MiB; + /// What kinds keep past a call (`pa_api.heap`): the pdf addon's + /// documents, MuPDF's own memory and the pages' pixels. + pub const addon = 512 * MiB; + /// One language query's working memory (its parsed answers, the rows + /// it writes): a hard bound, nothing spills. Callstack walks until it + /// would leave less than its rendering reserve. + pub const lsp_query = 256 * MiB; + }; +}; + +const Allocator = std.mem.Allocator; +const debug_enabled = builtin.mode == .debug; + +pub const Allocators = struct { + pardes: Allocator, + frame: Allocator, + lsp: Allocator, + tree_sitter: Allocator, + image: Allocator, + addon: Allocator, +}; + +/// One arena's fixed region on a native target, handed out in runs of 4 KiB +/// granules to the general allocator above it (`Region.general`). A freed run +/// is used again, and big ones go back to the system (`release`; `trim` +/// gives back the rest), so what is resident follows what is in use. When no +/// run fits, the block spills to the heap (`spill`) and is counted in +/// `spilled`. Called only under the general allocator's mutex. +const Pages = struct { + region: []u8 = @constCast(&[_]u8{}), + used: []u64 = &.{}, + spill: Allocator = undefined, + spilled: usize = 0, + /// Past the highest granule used yet: where `trim` stops. + top: usize = 0, + + const granule = 4 * KiB; + /// A freed run from `release_min` up to `keep_min` goes back at once: + /// kept until `trim`, a V8 Callstack page's emptied buckets and middling + /// blocks took its peak from 160 to 219 MiB. A bigger one stays resident + /// until `trim`: the next block of its size takes it without faulting it + /// in again, which each keystroke in a 7 MB file does (its edit's copy of + /// the text frees the one before; given back at once, 2.0 -> 3.2 ms a key). + const release_min = 64 * KiB; + const keep_min = 1 * MiB; + + fn allocator(self: *Pages) Allocator { + return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + + fn owns(self: *const Pages, ptr: [*]u8) bool { + const at = @intFromPtr(ptr) -% @intFromPtr(self.region.ptr); + return at < self.region.len; + } + + fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { + const self: *Pages = @ptrCast(@alignCast(ctx)); + const n = std.math.divCeil(usize, len, granule) catch unreachable; + const step = @max(1, alignment.toByteUnits() / granule); + if (find(self.used, n, step)) |start| { + mark(self.used, start, n, true); + self.top = @max(self.top, start + n); + return self.region.ptr + start * granule; + } + const ptr = self.spill.rawAlloc(len, alignment, ra) orelse return null; + self.spilled += len; + return ptr; + } + + fn resize(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, new_len: usize, ra: usize) bool { + const self: *Pages = @ptrCast(@alignCast(ctx)); + if (!self.owns(buf.ptr)) { + if (!self.spill.rawResize(buf, alignment, new_len, ra)) return false; + self.spilled = self.spilled - buf.len + new_len; + return true; + } + const start = (@intFromPtr(buf.ptr) - @intFromPtr(self.region.ptr)) / granule; + const n = std.math.divCeil(usize, buf.len, granule) catch unreachable; + const want = std.math.divCeil(usize, new_len, granule) catch unreachable; + if (want <= n) { + self.release(start + want, n - want); + return true; + } + if (start + want > self.used.len * 64 or freeRun(self.used, start + n, want - n) < want - n) return false; + mark(self.used, start + n, want - n, true); + self.top = @max(self.top, start + want); + return true; + } + + fn remap(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, new_len: usize, ra: usize) ?[*]u8 { + const self: *Pages = @ptrCast(@alignCast(ctx)); + if (!self.owns(buf.ptr)) { + const ptr = self.spill.rawRemap(buf, alignment, new_len, ra) orelse return null; + self.spilled = self.spilled - buf.len + new_len; + return ptr; + } + return if (resize(ctx, buf, alignment, new_len, ra)) buf.ptr else null; + } + + fn free(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, ra: usize) void { + const self: *Pages = @ptrCast(@alignCast(ctx)); + if (!self.owns(buf.ptr)) { + self.spilled -= buf.len; + return self.spill.rawFree(buf, alignment, ra); + } + const start = (@intFromPtr(buf.ptr) - @intFromPtr(self.region.ptr)) / granule; + self.release(start, std.math.divCeil(usize, buf.len, granule) catch unreachable); + } + + fn release(self: *Pages, start: usize, n: usize) void { + mark(self.used, start, n, false); + if (n * granule >= release_min and n * granule < keep_min) advise(self.region[start * granule ..][0 .. n * granule], std.posix.MADV.DONTNEED); + } + + /// Gives back the pages of every free run below `top`: the small ones + /// `release` keeps resident, small and big. + fn trim(self: *Pages) void { + var i: usize = 0; + while (i < self.top) { + if (i % 64 == 0 and self.used[i / 64] == ~@as(u64, 0)) { + i += 64; + continue; + } + const run = freeRun(self.used, i, self.top - i); + if (run > 0) advise(self.region[i * granule ..][0 .. run * granule], std.posix.MADV.DONTNEED); + i += run + 1; + } + } + + /// The first free run of `n` granules starting at a multiple of `step`. + // ponytail: first fit, a scan of the region's bitmap (32 KiB for 1 GiB) + // per page-sized block; a free-run index if a profile ever shows it. + fn find(used: []const u64, n: usize, step: usize) ?usize { + const total = used.len * 64; + var start: usize = 0; + while (start + n <= total) { + if (start % 64 == 0 and used[start / 64] == ~@as(u64, 0)) { + start = std.mem.alignForward(usize, start + 64, step); + continue; + } + const got = freeRun(used, start, n); + if (got == n) return start; + start = std.mem.alignForward(usize, start + got + 1, step); + } + return null; + } + + /// How many of the `n` granules from `start` are free before a used one. + fn freeRun(used: []const u64, start: usize, n: usize) usize { + var i = start; + while (i < start + n) { + if (i % 64 == 0 and start + n - i >= 64 and used[i / 64] == 0) { + i += 64; + continue; + } + if (used[i / 64] >> @intCast(i % 64) & 1 != 0) break; + i += 1; + } + return i - start; + } + + fn mark(used: []u64, start: usize, n: usize, set: bool) void { + var i = start; + while (i < start + n) { + if (i % 64 == 0 and start + n - i >= 64) { + used[i / 64] = if (set) ~@as(u64, 0) else 0; + i += 64; + continue; + } + const bit = @as(u64, 1) << @intCast(i % 64); + if (set) used[i / 64] |= bit else used[i / 64] &= ~bit; + i += 1; + } + } +}; + +/// The general allocator over one arena's region: std's DebugAllocator for +/// its size classes, its checks and leak report only in a Debug build. +const General = std.heap.DebugAllocator(.{ + .safety = debug_enabled, + .thread_safe = true, + .backing_allocator_zeroes = false, + .page_size = 64 * KiB, +}); + +/// One arena: its region, the bitmap of its used granules, and the +/// allocator over them. A native region is address space mapped once, at the +/// first `init`, not .bss: gigabytes of .bss put static data out of reach of +/// x86-64's 32-bit offsets. +const Region = struct { + size: usize, + bits: []u64, + pages: Pages = .{}, + general: General = .init, + + fn init(r: *Region, spill: Allocator) Allocator { + // Without the mapping (an address-space limit) every block spills. + const region = if (r.pages.region.len > 0) r.pages.region else if (std.heap.page_allocator.rawAlloc(r.size, .fromByteUnits(64 * KiB), @returnAddress())) |ptr| ptr[0..r.size] else @constCast(&[_]u8{}); + sparse(region); + @memset(r.bits, 0); + r.pages = .{ .region = region, .used = r.bits[0 .. region.len / Pages.granule / 64], .spill = spill }; + r.general = .{ .backing_allocator = r.pages.allocator() }; + return r.general.allocator(); + } + + fn trim(r: *Region) void { + std.Io.Threaded.mutexLockUncancelable(&r.general.mutex); + defer std.Io.Threaded.mutexUnlock(&r.general.mutex); + r.pages.trim(); + } + + /// A fresh allocator in its place: a Debug deinit leaves 0xAA behind, + /// its mutex too, which a later `trim` would wait on for good. + fn deinit(r: *Region) bool { + const leaked = r.general.deinit() == .leak; + r.general = .{ .backing_allocator = r.pages.allocator() }; + return leaked; + } +}; + +/// Each arena's bitmap, spelled out per arena: a generic returning the +/// globals would share them between two arenas of one size. +fn bitsFor(size: usize) usize { + return size / Pages.granule / 64; +} +var pardes_bits: [bitsFor(limits.arena.pardes)]u64 = @splat(0); +var pardes_region: Region = .{ .size = limits.arena.pardes, .bits = &pardes_bits }; +var frame_bits: [bitsFor(limits.arena.frame)]u64 = @splat(0); +var frame_region: Region = .{ .size = limits.arena.frame, .bits = &frame_bits }; +var lsp_bits: [bitsFor(limits.arena.lsp)]u64 = @splat(0); +var lsp_region: Region = .{ .size = limits.arena.lsp, .bits = &lsp_bits }; +var tree_sitter_bits: [bitsFor(limits.arena.tree_sitter)]u64 = @splat(0); +var tree_sitter_region: Region = .{ .size = limits.arena.tree_sitter, .bits = &tree_sitter_bits }; +var image_bits: [bitsFor(limits.arena.image)]u64 = @splat(0); +var image_region: Region = .{ .size = limits.arena.image, .bits = &image_bits }; +var addon_bits: [bitsFor(limits.arena.addon)]u64 = @splat(0); +var addon_region: Region = .{ .size = limits.arena.addon, .bits = &addon_bits }; +var host_bits: [bitsFor(limits.arena.host)]u64 = @splat(0); +var host_region: Region = .{ .size = limits.arena.host, .bits = &host_bits }; + +/// The allocator a native shell allocates itself from, over its own arena, +/// for the life of the process (no `deinit`); what does not fit spills to +/// `spill`. A release build's: a Debug build keeps std.start's allocator +/// for its leak report. +pub fn host(spill: Allocator) Allocator { + return host_region.init(spill); +} + +var lsp_query_buffer: [limits.arena.lsp_query]u8 align(std.heap.page_size_max) = @splat(0); +var lsp_query_busy: std.atomic.Value(bool) = .init(false); +/// What a query may leave resident of the region (giveLspQuery). +const lsp_query_kept = 8 * MiB; + +/// The language query region, for the one query running; null while another +/// holds it (the shells cancel and join a query before starting the next). +pub fn takeLspQuery() ?[]u8 { + if (lsp_query_busy.swap(true, .acquire)) return null; + return &lsp_query_buffer; +} + +/// Gives the region back after a query. A big one's touched pages go back to +/// the system (zeroed again on their next touch, as .bss is), so one huge +/// answer does not stay resident; a small one's stay, for the next query to +/// reuse without faulting them in again. +pub fn giveLspQuery(used: usize) void { + if (comptime builtin.os.tag == .linux) if (used > lsp_query_kept) { + const page = std.heap.pageSize(); + const len = std.mem.alignForward(usize, @min(used, lsp_query_buffer.len), page); + std.posix.madvise(@as([*]align(std.heap.page_size_min) u8, @ptrCast(&lsp_query_buffer)), len, std.posix.MADV.DONTNEED) catch {}; + }; + lsp_query_busy.store(false, .release); +} + +/// `n` bytes as they come: `Allocator.alloc` fills a safe build's new memory +/// as `undefined` (0xAA), which writes, and makes resident, all of a buffer +/// sized for the worst case: every language query wrote its 51 MB answer +/// room, every search its 16 MiB. For buffers written before they are read. +pub fn unfilled(allocator: Allocator, n: usize) Allocator.Error![]u8 { + if (n == 0) return allocator.alloc(u8, 0); + const ptr = allocator.rawAlloc(n, .of(u8), @returnAddress()) orelse return error.OutOfMemory; + return ptr[0..n]; +} + +/// `bytes` copied into memory `unfilled` takes: a text-sized copy (an undo +/// snapshot) is written once, not filled first. +pub fn dupeUnfilled(allocator: Allocator, bytes: []const u8) Allocator.Error![]u8 { + const out = try unfilled(allocator, bytes.len); + @memcpy(out, bytes); + return out; +} + +/// Frees without the safe-build overwrite `free` does: text-sized buffers +/// and line indexes, freed as an edit grows or replaces them (and kept by a +/// replica's rollback copy, core/rollback.zig, while it holds the core it +/// was taken over, which a safe build's overwrite would spoil). +pub fn freeRaw(allocator: Allocator, items: anytype) void { + const E = @typeInfo(@TypeOf(items)).pointer.child; + const bytes = std.mem.sliceAsBytes(items); + if (bytes.len == 0) return; + if (pinned(allocator, bytes, .of(E))) return; + allocator.rawFree(@constCast(bytes), .of(E), @returnAddress()); +} + +// ---- a join's pins (core/replica.zig) ---- +// +// A replica client's join dumps the session's mutable state in its step and +// leaves its blobs out (walk.Deferred); its writer thread streams them after. +// A blob is never written in place and is freed raw (above), so until the +// writer has sent it, its free is put off: `pin` it, `unpin` it after. +var pins_lock: std.atomic.Value(bool) = .init(false); +var pins: std.AutoHashMapUnmanaged(usize, u32) = .empty; +var pin_count: std.atomic.Value(usize) = .init(0); +const PutOff = struct { allocator: Allocator, bytes: []const u8, alignment: std.mem.Alignment }; +var put_off: std.ArrayListUnmanaged(PutOff) = .empty; + +fn lockPins() void { + while (pins_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint(); +} + +/// The blob at `bytes.ptr` kept alive until it is unpinned as many times. +pub fn pin(bytes: []const u8) void { + lockPins(); + defer pins_lock.store(false, .release); + const got = pins.getOrPut(std.heap.page_allocator, @intFromPtr(bytes.ptr)) catch return; + got.value_ptr.* = if (got.found_existing) got.value_ptr.* + 1 else 1; + pin_count.store(pins.count(), .release); +} + +/// One pin of the blob at `bytes.ptr` let go: its free, put off, made now +/// the last one goes. +pub fn unpin(bytes: []const u8) void { + const addr = @intFromPtr(bytes.ptr); + lockPins(); + const n = pins.getPtr(addr) orelse { + pins_lock.store(false, .release); + return; + }; + n.* -= 1; + var due: ?PutOff = null; + if (n.* == 0) { + _ = pins.remove(addr); + pin_count.store(pins.count(), .release); + for (put_off.items, 0..) |f, i| if (@intFromPtr(f.bytes.ptr) == addr) { + due = put_off.swapRemove(i); + break; + }; + } + pins_lock.store(false, .release); + if (due) |f| { + f.allocator.rawFree(@constCast(f.bytes), f.alignment, @returnAddress()); + } +} + +/// Whether the blob at `bytes.ptr` is pinned: a join's writer is still to +/// send it, so it is not written in place (File.replace). +pub fn isPinned(bytes: []const u8) bool { + if (pin_count.load(.acquire) == 0) return false; + lockPins(); + defer pins_lock.store(false, .release); + return pins.contains(@intFromPtr(bytes.ptr)); +} + +/// Whether the free of `bytes` is put off (it is pinned). +fn pinned(allocator: Allocator, bytes: []const u8, alignment: std.mem.Alignment) bool { + if (pin_count.load(.acquire) == 0) return false; + lockPins(); + defer pins_lock.store(false, .release); + if (!pins.contains(@intFromPtr(bytes.ptr))) return false; + put_off.append(std.heap.page_allocator, .{ .allocator = allocator, .bytes = bytes, .alignment = alignment }) catch return false; + return true; +} + +/// Gives free memory back to the system, the arenas' and libc's, inside its +/// heap too: after a big result is formatted or a big pane torn down, the +/// tree-sitter arena kept 73 MiB of emptied buckets resident and glibc what +/// was freed (a V8 Callstack page left 21 MiB free in its heap; this returned +/// 20). Walks every arena and the heap, so for rare, large events only. +pub fn trim() void { + inline for (.{ &pardes_region, &frame_region, &lsp_region, &tree_sitter_region, &image_region, &addon_region, &host_region }) |r| r.trim(); + if (comptime builtin.os.tag != .linux or builtin.abi.isMusl() or !builtin.link_libc) return; + const glibc = struct { + extern "c" fn malloc_trim(pad: usize) c_int; + }; + _ = glibc.malloc_trim(0); +} + +/// Marks a big region that is touched sparsely as not for huge pages. With +/// transparent huge pages on `always` (a common default), touching one byte +/// of a 2 MiB-aligned stretch makes all 2 MiB resident: the 9P runner's +/// slots and these arenas' first pages held 45 MiB of an idle session's +/// 71 MiB that way. Only the region given, never the whole process (a prctl +/// would reach every shell and server pardes starts). +pub fn sparse(region: []u8) void { + if (comptime builtin.os.tag != .linux) return; + advise(region, std.posix.MADV.NOHUGEPAGE); +} + +/// madvise over the whole pages inside `region`. +fn advise(region: []u8, advice: u32) void { + if (comptime builtin.os.tag != .linux) return; + const page = std.heap.pageSize(); + const start = std.mem.alignForward(usize, @intFromPtr(region.ptr), page); + const end = std.mem.alignBackward(usize, @intFromPtr(region.ptr) + region.len, page); + if (end <= start) return; + std.posix.madvise(@ptrFromInt(start), end - start, advice) catch {}; +} + +// One session at a time; free its allocations before deinit. The language +// workers allocate their answers from `lsp` on their own threads. +pub fn init(fallback: Allocator) Allocators { + // Beneath a Debug build's arenas goes the page allocator rather than + // `fallback`: in a Debug build `fallback` is std.process.Init's gpa, a + // DebugAllocator already, and the arenas' own check every block. + const spill = if (debug_enabled) std.heap.page_allocator else fallback; + sparse(&lsp_query_buffer); + return .{ + .pardes = pardes_region.init(spill), + .frame = frame_region.init(spill), + .lsp = lsp_region.init(spill), + .tree_sitter = tree_sitter_region.init(spill), + .image = image_region.init(spill), + .addon = addon_region.init(spill), + }; +} + +/// A Debug build's leak report, each arena's own (it panics on a leak). +pub fn deinit() void { + if (!debug_enabled) return; + var leaked = false; + // The host's arena lives as long as the process (`host`). + inline for (.{ &pardes_region, &frame_region, &lsp_region, &tree_sitter_region, &image_region, &addon_region }) |r| leaked = r.deinit() or leaked; + if (leaked) @panic("allocator leaks detected"); +} + +test "arenas are separate, reuse what is freed, spill, and restart" { + var allocs = init(std.testing.allocator); + const core = try allocs.pardes.alloc(u8, 32); + const frame = try allocs.frame.alloc(u8, 32); + try std.testing.expect(pardes_region.pages.owns(core.ptr)); + try std.testing.expect(frame_region.pages.owns(frame.ptr)); + + // A freed block is used again: a FixedBufferAllocator's was not, unless + // it was the last one, so an arena filled once and spilled after. + const big = try unfilled(allocs.pardes, 8 * MiB); + const after = try allocs.pardes.alloc(u8, 32); + freeRaw(allocs.pardes, big); + const again = try unfilled(allocs.pardes, 8 * MiB); + try std.testing.expectEqual(big.ptr, again.ptr); + + const spill = try unfilled(allocs.pardes, limits.arena.pardes + 1); + try std.testing.expect(!pardes_region.pages.owns(spill.ptr)); + try std.testing.expectEqual(limits.arena.pardes + 1, pardes_region.pages.spilled); + freeRaw(allocs.pardes, spill); + try std.testing.expectEqual(0, pardes_region.pages.spilled); + freeRaw(allocs.pardes, again); + allocs.pardes.free(after); + allocs.frame.free(frame); + allocs.pardes.free(core); + deinit(); + + allocs = init(std.testing.allocator); + defer deinit(); + const restarted = try allocs.pardes.alloc(u8, 32); + defer allocs.pardes.free(restarted); + try std.testing.expect(pardes_region.pages.owns(restarted.ptr)); +} + +test "a region's runs: aligned first fit, growth in place, release" { + var used: [2]u64 = @splat(0); + Pages.mark(&used, 0, 3, true); + try std.testing.expectEqual(@as(?usize, 4), Pages.find(&used, 2, 4)); + try std.testing.expectEqual(@as(?usize, 3), Pages.find(&used, 70, 1)); + try std.testing.expectEqual(@as(?usize, null), Pages.find(&used, 126, 1)); + try std.testing.expectEqual(@as(?usize, 3), Pages.find(&used, 125, 1)); + Pages.mark(&used, 3, 125, true); + try std.testing.expectEqual(~@as(u64, 0), used[1]); + Pages.mark(&used, 10, 100, false); + try std.testing.expectEqual(@as(usize, 100), Pages.freeRun(&used, 10, 100)); + try std.testing.expectEqual(@as(usize, 100), Pages.freeRun(&used, 10, 101)); +} + +test "memory limits preserve desktop capacities" { + try std.testing.expectEqual(4096, limits.effect_cap); + try std.testing.expectEqual(@as(usize, 4 * MiB), limits.pending_write_cap); + try std.testing.expectEqual(256, limits.wrap_rows); + try std.testing.expectEqual(256, limits.undo_max); + try std.testing.expectEqual(128, limits.message_log); + try std.testing.expectEqual(1024, limits.selections); + try std.testing.expectEqual(@as(usize, 4096), limits.max_tag_tail); + try std.testing.expectEqual(@as(usize, 4095), limits.host_path_cap); + try std.testing.expectEqual(config.embed_sources, limits.embedded_sources); + try std.testing.expectEqual(1024 * MiB, limits.arena.pardes); + try std.testing.expectEqual(64 * MiB, limits.arena.frame); + try std.testing.expectEqual(512 * MiB, limits.arena.lsp); + try std.testing.expectEqual(256 * MiB, limits.arena.tree_sitter); + try std.testing.expectEqual(256 * MiB, limits.arena.image); + try std.testing.expectEqual(512 * MiB, limits.arena.addon); +} + +test "a pinned blob's free is put off until its last pin goes" { + const gpa = std.testing.allocator; + const b = try gpa.alloc(u8, 8192); + @memset(b, 7); + pin(b); + pin(b); + freeRaw(gpa, b); + // Still the blob's: a join's writer reads it. + try std.testing.expectEqual(@as(u8, 7), b[100]); + unpin(b); + try std.testing.expectEqual(@as(u8, 7), b[8000]); + // The last pin: freed now (the testing allocator says if not). + unpin(b); +} |
