Skip to content

Truly independent web browser

AK: Add Column, a Rust array that grows in place

Andreas Kling12c7d2448a68
diff --git a/AK/Rust/src/column.rs b/AK/Rust/src/column.rs
new file mode 100644
index 00000000000..9ba6dae5752
--- /dev/null
+++ b/AK/Rust/src/column.rs
@@ -0,0 +1,344 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Arrays that grow in place, in memory that comes straight from the system.
+//!
+//! A `Column` reserves the address space for the most elements it may hold when it gets its first element, and takes
+//! memory for the pages it uses as it grows. Its elements never move, so growing copies nothing and leaves nothing
+//! behind, and the memory of a column that shrank goes back to the system and not into the free lists of an allocator
+//! (see `Column::trim()`). Reserved address space costs nothing until it is used, so a limit can be far above what a
+//! column usually holds, and a column that never holds an element costs the system nothing at all.
+
+use core::ffi::CStr;
+use core::fmt;
+use core::marker::PhantomData;
+use core::ops::{Deref, DerefMut};
+
+use crate::region::Region;
+
+/// A column is at its limit, and has no room for what was to be added.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ColumnFull;
+
+/// A growable array of plain values, which stay where they are when it grows.
+///
+/// It holds at most the number of elements it was made for: the limit is a budget of its owner, not a size it grows
+/// to. An owner for which more elements are possible adds them with the `try_` functions and gives up what it does
+/// when they fail. A column that is cleared keeps its memory for its next use; `trim()` gives it back.
+pub struct Column<T: Copy> {
+ region: Region,
+ len: usize,
+ /// How many elements the memory of the region has room for, and at most `limit`.
+ capacity: usize,
+ limit: usize,
+ elements: PhantomData<T>,
+}
+
+impl<T: Copy> Column<T> {
+ /// The memory a column takes at least, and at most, when it has to grow.
+ const MIN_GROWTH: usize = 64 * 1024;
+ const MAX_GROWTH: usize = 16 * 1024 * 1024;
+
+ // NB: A region starts at a multiple of 4096.
+ const LAYOUT_IS_SUPPORTED: () = assert!(size_of::<T>() != 0 && align_of::<T>() <= 4096);
+
+ /// A column that holds up to `limit` elements. It takes no memory and no address space before it has elements.
+ /// `name` shows up for its memory in /proc/<pid>/smaps on Linux.
+ pub fn new(limit: usize, name: &'static CStr) -> Self {
+ let () = Self::LAYOUT_IS_SUPPORTED;
+ let size = limit
+ .checked_mul(size_of::<T>())
+ .expect("the limit of a column fits in the address space");
+ Self {
+ region: Region::new(size, name),
+ len: 0,
+ capacity: 0,
+ limit,
+ elements: PhantomData,
+ }
+ }
+
+ /// The most elements the column can hold.
+ pub fn limit(&self) -> usize {
+ self.limit
+ }
+
+ /// How many bytes of memory the column has taken from the system.
+ pub fn memory(&self) -> usize {
+ self.region.committed()
+ }
+
+ /// Adds an element, if the column is below its limit.
+ pub fn try_push(&mut self, value: T) -> Result<(), ColumnFull> {
+ if self.len == self.capacity {
+ self.grow(1)?;
+ }
+ // SAFETY: `capacity` is above `len`, so the element is in the memory of the region, which is aligned for it.
+ unsafe { self.first().add(self.len).write(value) };
+ self.len += 1;
+ Ok(())
+ }
+
+ /// Adds elements, if that does not take the column past its limit. Adds none of them otherwise.
+ pub fn try_extend_from_slice(&mut self, values: &[T]) -> Result<(), ColumnFull> {
+ if values.len() > self.capacity - self.len {
+ self.grow(values.len())?;
+ }
+ // SAFETY: The elements are in the memory of the region, as `capacity` is at least `len` plus their count, and
+ // `values` is not part of the column, which is borrowed mutably.
+ unsafe { core::ptr::copy_nonoverlapping(values.as_ptr(), self.first().add(self.len), values.len()) };
+ self.len += values.len();
+ Ok(())
+ }
+
+ /// Makes the column `len` elements long, if that is within its limit: drops the elements from index `len` on, or
+ /// adds copies of `value`.
+ pub fn try_resize(&mut self, len: usize, value: T) -> Result<(), ColumnFull> {
+ if len > self.capacity {
+ self.grow(len - self.len)?;
+ }
+ for index in self.len..len {
+ // SAFETY: `capacity` is at least `len`, so the element is in the memory of the region, which is aligned
+ // for it.
+ unsafe { self.first().add(index).write(value) };
+ }
+ self.len = len;
+ Ok(())
+ }
+
+ /// Adds an element. Panics if the column is at its limit.
+ pub fn push(&mut self, value: T) {
+ if self.try_push(value).is_err() {
+ self.panic_at_limit();
+ }
+ }
+
+ /// Adds elements. Panics if that takes the column past its limit.
+ pub fn extend_from_slice(&mut self, values: &[T]) {
+ if self.try_extend_from_slice(values).is_err() {
+ self.panic_at_limit();
+ }
+ }
+
+ /// Drops the elements from index `len` on. The column keeps its memory.
+ pub fn truncate(&mut self, len: usize) {
+ self.len = self.len.min(len);
+ }
+
+ /// Drops all elements. The column keeps its memory.
+ pub fn clear(&mut self) {
+ self.len = 0;
+ }
+
+ /// Gives memory back to the system: all that is past the elements and past the room for `keep` elements.
+ pub fn trim(&mut self, keep: usize) {
+ // NB: Neither count is above `limit`, whose size in bytes new() computed.
+ let kept = self.len.max(keep.min(self.limit)) * size_of::<T>();
+ self.region.decommit_past(kept);
+ self.capacity = (self.region.committed() / size_of::<T>()).min(self.limit);
+ }
+
+ fn first(&self) -> *mut T {
+ self.region.base().as_ptr().cast()
+ }
+
+ #[cold]
+ fn panic_at_limit(&self) -> ! {
+ panic!("a column holds no more than {} elements", self.limit);
+ }
+
+ /// Takes memory for `additional` more elements, if the column can hold that many.
+ #[cold]
+ fn grow(&mut self, additional: usize) -> Result<(), ColumnFull> {
+ let needed = self
+ .len
+ .checked_add(additional)
+ .filter(|needed| *needed <= self.limit)
+ .ok_or(ColumnFull)?;
+ let step = self.region.committed().clamp(Self::MIN_GROWTH, Self::MAX_GROWTH);
+ // NB: Memory that is taken and never written costs nothing on Unix, where a page becomes real when it is
+ // first written, so the steps can be large.
+ let size = (needed * size_of::<T>())
+ .max(self.region.committed() + step)
+ .min(self.region.reserved());
+ self.region.commit(size);
+ self.capacity = (self.region.committed() / size_of::<T>()).min(self.limit);
+ Ok(())
+ }
+}
+
+impl<T: Copy> Deref for Column<T> {
+ type Target = [T];
+
+ fn deref(&self) -> &[T] {
+ // SAFETY: The first `len` elements were written, the region keeps their memory for as long as the column
+ // lives, and nothing changes them while the column is borrowed.
+ unsafe { crate::slice_from_raw_parts(self.first(), self.len) }
+ }
+}
+
+impl<T: Copy> DerefMut for Column<T> {
+ fn deref_mut(&mut self) -> &mut [T] {
+ // SAFETY: As in deref(), and the mutable borrow of the column is the only access to them.
+ unsafe { crate::slice_from_raw_parts_mut(self.first(), self.len) }
+ }
+}
+
+impl<T: Copy + fmt::Debug> fmt::Debug for Column<T> {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.debug_list().entries(self.iter()).finish()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn elements_stay_in_place_while_a_column_grows() {
+ let mut column = Column::<u32>::new(1 << 20, c"test");
+ assert_eq!(column.memory(), 0);
+ assert!(column.is_empty());
+ assert!(!column.region.has_address_space());
+ column.clear();
+ column.trim(0);
+ assert!(!column.region.has_address_space());
+ column.push(7);
+ let first = column.as_ptr();
+ for value in 1..100_000 {
+ column.push(value);
+ }
+ assert_eq!(column.as_ptr(), first);
+ assert_eq!(column.len(), 100_000);
+ assert_eq!(column[0], 7);
+ assert!(column[1..].iter().copied().eq(1..100_000));
+ }
+
+ #[test]
+ fn extends_from_slices() {
+ let mut column = Column::<u16>::new(1 << 20, c"test");
+ let values: Vec<u16> = (0..50_000).collect();
+ column.extend_from_slice(&values[..3]);
+ column.extend_from_slice(&[]);
+ column.extend_from_slice(&values[3..]);
+ column.extend_from_slice(&values);
+ assert_eq!(column[..50_000], values[..]);
+ assert_eq!(column[50_000..], values[..]);
+ column[49_999] = 1;
+ assert_eq!(column[49_999], 1);
+ }
+
+ #[test]
+ fn a_cleared_column_keeps_its_memory_and_a_trimmed_one_gives_it_back() {
+ let mut column = Column::<u64>::new(1 << 20, c"test");
+ column.extend_from_slice(&vec![1; 100_000]);
+ let grown = column.memory();
+ assert!(grown >= 800_000);
+ column.truncate(10);
+ column.truncate(20);
+ assert_eq!(column[..], [1; 10]);
+ assert_eq!(column.memory(), grown);
+
+ column.trim(1000);
+ assert!(column.memory() >= 8000 && column.memory() < grown);
+ column.trim(0);
+ assert!(column.memory() >= 80 && column.memory() < 8000 + 2 * crate::region::page_size());
+ assert_eq!(column[..], [1; 10]);
+
+ // NB: Memory that comes back holds zeros, and the column must not show them as elements.
+ column.extend_from_slice(&vec![2; 100_000]);
+ assert_eq!(column.len(), 100_010);
+ assert_eq!(column[..10], [1; 10]);
+ assert!(column[10..].iter().all(|value| *value == 2));
+
+ column.clear();
+ assert!(column.is_empty());
+ column.trim(0);
+ assert_eq!(column.memory(), 0);
+ column.push(3);
+ assert_eq!(column[..], [3]);
+ }
+
+ #[test]
+ fn holds_as_many_elements_as_its_limit() {
+ let mut column = Column::<u8>::new(3, c"test");
+ column.extend_from_slice(&[1, 2]);
+ column.push(3);
+ assert_eq!(column[..], [1, 2, 3]);
+ assert_eq!(column.limit(), 3);
+ }
+
+ #[test]
+ #[should_panic(expected = "a column holds no more than 3 elements")]
+ fn a_push_past_the_limit_panics() {
+ let mut column = Column::<u8>::new(3, c"test");
+ for value in 0..4 {
+ column.push(value);
+ }
+ }
+
+ #[test]
+ #[should_panic(expected = "a column holds no more than 3 elements")]
+ fn a_slice_past_the_limit_panics() {
+ let mut column = Column::<u64>::new(3, c"test");
+ column.push(0);
+ column.extend_from_slice(&[1, 2, 3]);
+ }
+
+ #[test]
+ fn adds_nothing_past_the_limit_when_asked_to_try() {
+ let mut column = Column::<u32>::new(4, c"test");
+ assert_eq!(column.try_extend_from_slice(&[1, 2, 3]), Ok(()));
+ assert_eq!(column.try_extend_from_slice(&[4, 5]), Err(ColumnFull));
+ assert_eq!(column.try_resize(5, 0), Err(ColumnFull));
+ assert_eq!(column[..], [1, 2, 3]);
+ assert_eq!(column.try_push(4), Ok(()));
+ assert_eq!(column.try_push(5), Err(ColumnFull));
+ assert_eq!(column[..], [1, 2, 3, 4]);
+ }
+
+ #[test]
+ fn resizes_with_copies_of_a_value() {
+ let mut column = Column::<u32>::new(1 << 20, c"test");
+ column.push(1);
+ assert_eq!(column.try_resize(100_000, 7), Ok(()));
+ assert_eq!(column.len(), 100_000);
+ assert_eq!(column[0], 1);
+ assert!(column[1..].iter().all(|value| *value == 7));
+ assert_eq!(column.try_resize(2, 9), Ok(()));
+ assert_eq!(column[..], [1, 7]);
+ // NB: The elements a resize adds are all new, whatever the memory held before.
+ assert_eq!(column.try_resize(4, 9), Ok(()));
+ assert_eq!(column[..], [1, 7, 9, 9]);
+ }
+
+ #[test]
+ fn holds_elements_with_an_alignment() {
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ #[repr(align(16))]
+ struct Wide(u64, u8);
+
+ let mut column = Column::<Wide>::new(10_000, c"test");
+ for index in 0..10_000 {
+ column.push(Wide(index, 1));
+ }
+ assert_eq!(column[9_999], Wide(9_999, 1));
+ assert!(column.as_ptr().is_aligned());
+ }
+
+ #[test]
+ fn moves_to_another_thread() {
+ let mut column = Column::<u32>::new(1024, c"test");
+ column.push(1);
+ let column = std::thread::spawn(move || {
+ column.push(2);
+ column
+ })
+ .join()
+ .unwrap();
+ assert_eq!(column[..], [1, 2]);
+ }
+}
diff --git a/AK/Rust/src/lib.rs b/AK/Rust/src/lib.rs
index 39e233baec0..3cfe0c7f7fd 100644
--- a/AK/Rust/src/lib.rs
+++ b/AK/Rust/src/lib.rs
@@ -6,9 +6,11 @@
//! Rust views of shared AK data structures.
+mod column;
mod generic_lexer;
pub mod math;
pub mod perf_map;
+mod region;
mod scope_guard;
mod slice;
pub mod stack;
@@ -17,6 +19,7 @@ pub mod waiter_list;
#[cfg(all(windows, target_arch = "x86_64"))]
pub mod windows_code_memory;
+pub use column::{Column, ColumnFull};
pub use generic_lexer::GenericLexer;
pub use scope_guard::ScopeGuard;
pub use slice::{Span, SpanMut, slice_from_raw_parts, slice_from_raw_parts_mut};
diff --git a/AK/Rust/src/region.rs b/AK/Rust/src/region.rs
new file mode 100644
index 00000000000..de8276eabe7
--- /dev/null
+++ b/AK/Rust/src/region.rs
@@ -0,0 +1,298 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Ranges of address space of a process's own, with memory that comes straight from the system and goes back to it.
+
+use core::ffi::CStr;
+use core::num::NonZeroUsize;
+use core::ptr::NonNull;
+
+/// What the system does for a region. Addresses and sizes are multiples of the page size.
+#[cfg(all(unix, not(miri)))]
+mod system {
+ use core::ffi::CStr;
+ use core::ptr::NonNull;
+
+ pub fn page_size() -> usize {
+ // SAFETY: sysconf() has no preconditions.
+ let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
+ usize::try_from(size).expect("the page size is positive")
+ }
+
+ /// Maps `size` bytes that nothing can access, at `address` in place of what is mapped there, or anywhere if it is
+ /// null.
+ ///
+ /// # Safety
+ ///
+ /// Unless `address` is null, the range must be inside a mapping from `reserve()` that nothing reads or writes.
+ unsafe fn map_inaccessible(address: *mut libc::c_void, size: usize, name: &CStr) -> *mut libc::c_void {
+ let fixed = if address.is_null() { 0 } else { libc::MAP_FIXED };
+ // SAFETY: A new mapping at an address of the system's choosing has no preconditions, and the caller keeps the
+ // contract for a mapping in place of another.
+ let mapping = unsafe {
+ libc::mmap(
+ address,
+ size,
+ libc::PROT_NONE,
+ libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE | fixed,
+ -1,
+ 0,
+ )
+ };
+ assert_ne!(mapping, libc::MAP_FAILED, "mapping address space for a column failed");
+ // NB: The name tells the memory of columns apart in /proc/<pid>/smaps. A kernel that cannot name mappings
+ // fails the call, which changes nothing.
+ #[cfg(target_os = "linux")]
+ // SAFETY: The range is the mapping made above, and the kernel copies the name.
+ unsafe {
+ libc::prctl(
+ libc::PR_SET_VMA,
+ libc::PR_SET_VMA_ANON_NAME as libc::c_ulong,
+ mapping.addr() as libc::c_ulong,
+ size as libc::c_ulong,
+ name.as_ptr(),
+ );
+ }
+ #[cfg(not(target_os = "linux"))]
+ let _ = name;
+ mapping
+ }
+
+ /// Reserves `size` bytes of address space, which is no memory yet.
+ pub fn reserve(size: usize, name: &CStr) -> NonNull<u8> {
+ // SAFETY: The address is null.
+ let mapping = unsafe { map_inaccessible(core::ptr::null_mut(), size, name) };
+ NonNull::new(mapping.cast()).expect("no mapping is at address zero")
+ }
+
+ /// Makes a range memory that can be read and written. The memory holds zeros.
+ ///
+ /// # Safety
+ ///
+ /// The range must be inside a mapping from `reserve()`, and not be memory already.
+ pub unsafe fn commit(address: NonNull<u8>, size: usize) {
+ // SAFETY: The caller keeps the contract.
+ let result = unsafe { libc::mprotect(address.as_ptr().cast(), size, libc::PROT_READ | libc::PROT_WRITE) };
+ assert_eq!(result, 0, "the system has no memory for a column");
+ }
+
+ /// Gives the memory of a range back to the system. The range stays reserved.
+ ///
+ /// # Safety
+ ///
+ /// The range must be inside a mapping from `reserve()`, and nothing may read or write it until `commit()`.
+ pub unsafe fn decommit(address: NonNull<u8>, size: usize, name: &CStr) {
+ // NB: A new mapping in place of the pages drops them at once on every Unix. Advice to the kernel either leaves
+ // the pages for it to take later, or is not the same call everywhere.
+ // SAFETY: The caller keeps the contract.
+ unsafe { map_inaccessible(address.as_ptr().cast(), size, name) };
+ }
+
+ /// Gives the address space of a mapping back.
+ ///
+ /// # Safety
+ ///
+ /// `base` and `size` must be those of a mapping from `reserve()` that nothing uses anymore.
+ pub unsafe fn release(base: NonNull<u8>, size: usize) {
+ // SAFETY: The caller keeps the contract.
+ let result = unsafe { libc::munmap(base.as_ptr().cast(), size) };
+ assert_eq!(result, 0, "unmapping the address space of a column failed");
+ }
+}
+
+/// What the system does for a region. Addresses and sizes are multiples of the page size.
+#[cfg(all(windows, not(miri)))]
+mod system {
+ use core::ffi::{CStr, c_void};
+ use core::ptr::NonNull;
+
+ const MEM_COMMIT: u32 = 0x1000;
+ const MEM_RESERVE: u32 = 0x2000;
+ const MEM_DECOMMIT: u32 = 0x4000;
+ const MEM_RELEASE: u32 = 0x8000;
+ const PAGE_NOACCESS: u32 = 0x01;
+ const PAGE_READWRITE: u32 = 0x04;
+
+ #[link(name = "kernel32")]
+ unsafe extern "system" {
+ fn VirtualAlloc(address: *mut c_void, size: usize, allocation_type: u32, protect: u32) -> *mut c_void;
+ fn VirtualFree(address: *mut c_void, size: usize, free_type: u32) -> i32;
+ }
+
+ pub fn page_size() -> usize {
+ 4096
+ }
+
+ /// Reserves `size` bytes of address space, which is no memory yet.
+ pub fn reserve(size: usize, _name: &CStr) -> NonNull<u8> {
+ // SAFETY: A reservation at an address of the system's choosing has no preconditions.
+ let base = unsafe { VirtualAlloc(core::ptr::null_mut(), size, MEM_RESERVE, PAGE_NOACCESS) };
+ NonNull::new(base.cast()).expect("reserving address space for a column failed")
+ }
+
+ /// Makes a range memory that can be read and written. The memory holds zeros.
+ ///
+ /// # Safety
+ ///
+ /// The range must be inside a reservation from `reserve()`, and not be memory already.
+ pub unsafe fn commit(address: NonNull<u8>, size: usize) {
+ // SAFETY: The caller keeps the contract.
+ let result = unsafe { VirtualAlloc(address.as_ptr().cast(), size, MEM_COMMIT, PAGE_READWRITE) };
+ assert!(!result.is_null(), "the system has no memory for a column");
+ }
+
+ /// Gives the memory of a range back to the system. The range stays reserved.
+ ///
+ /// # Safety
+ ///
+ /// The range must be inside a reservation from `reserve()`, and nothing may read or write it until `commit()`.
+ pub unsafe fn decommit(address: NonNull<u8>, size: usize, _name: &CStr) {
+ // SAFETY: The caller keeps the contract.
+ let result = unsafe { VirtualFree(address.as_ptr().cast(), size, MEM_DECOMMIT) };
+ assert_ne!(result, 0, "giving the memory of a column back failed");
+ }
+
+ /// Gives the address space of a reservation back.
+ ///
+ /// # Safety
+ ///
+ /// `base` must come from `reserve()`, and nothing may use the reservation anymore.
+ pub unsafe fn release(base: NonNull<u8>, _size: usize) {
+ // SAFETY: The caller keeps the contract.
+ let result = unsafe { VirtualFree(base.as_ptr().cast(), 0, MEM_RELEASE) };
+ assert_ne!(result, 0, "releasing the address space of a column failed");
+ }
+}
+
+/// Miri has no way to change what a page allows, so one allocation that holds zeros stands in for a region there.
+#[cfg(miri)]
+mod system {
+ use core::ffi::CStr;
+ use core::ptr::NonNull;
+ use std::alloc::{Layout, alloc_zeroed, dealloc, handle_alloc_error};
+
+ pub fn page_size() -> usize {
+ 4096
+ }
+
+ fn layout(size: usize) -> Layout {
+ Layout::from_size_align(size, page_size()).expect("the size of a region is a multiple of its alignment")
+ }
+
+ pub fn reserve(size: usize, _name: &CStr) -> NonNull<u8> {
+ // SAFETY: A region is at least a page, so the layout has a size.
+ let base = unsafe { alloc_zeroed(layout(size)) };
+ NonNull::new(base).unwrap_or_else(|| handle_alloc_error(layout(size)))
+ }
+
+ pub unsafe fn commit(_address: NonNull<u8>, _size: usize) {}
+
+ pub unsafe fn decommit(_address: NonNull<u8>, _size: usize, _name: &CStr) {}
+
+ pub unsafe fn release(base: NonNull<u8>, size: usize) {
+ // SAFETY: The caller passes what `reserve()` allocated with this layout.
+ unsafe { dealloc(base.as_ptr(), layout(size)) };
+ }
+}
+
+/// A range of address space of which the first `committed` bytes are memory that can be read and written. The rest is
+/// reserved: nothing else gets mapped there, and it takes no memory. A region takes its address space when it first
+/// gets memory, so one that is never used costs the system nothing.
+pub(crate) struct Region {
+ /// Where the address space of the region is, once it has some.
+ base: Option<NonNull<u8>>,
+ reserved: usize,
+ committed: usize,
+ name: &'static CStr,
+}
+
+/// What a region without address space says it starts at: an address that is not null, with nothing there.
+const NO_BASE: NonNull<u8> = NonNull::without_provenance(NonZeroUsize::new(4096).unwrap());
+
+impl Region {
+ /// Where the region starts, which is a multiple of 4096. A region with no memory may have nothing there.
+ pub(crate) fn base(&self) -> NonNull<u8> {
+ self.base.unwrap_or(NO_BASE)
+ }
+
+ /// How many bytes of address space the region has.
+ pub(crate) fn reserved(&self) -> usize {
+ self.reserved
+ }
+
+ /// Whether the region has taken its address space.
+ #[cfg(test)]
+ pub(crate) fn has_address_space(&self) -> bool {
+ self.base.is_some()
+ }
+
+ /// How many bytes of the region are memory. They are its first ones.
+ pub(crate) fn committed(&self) -> usize {
+ self.committed
+ }
+
+ /// A region of at least `size` bytes, none of them memory yet.
+ pub(crate) fn new(size: usize, name: &'static CStr) -> Self {
+ let reserved = size
+ .max(1)
+ .checked_next_multiple_of(system::page_size())
+ .expect("a region fits in the address space");
+ Self {
+ base: None,
+ reserved,
+ committed: 0,
+ name,
+ }
+ }
+
+ /// Makes at least the first `size` bytes memory. What was memory before keeps its contents.
+ pub(crate) fn commit(&mut self, size: usize) {
+ assert!(size <= self.reserved, "a region does not grow past what it reserved");
+ let committed = size.next_multiple_of(system::page_size());
+ if committed <= self.committed {
+ return;
+ }
+ let base = *self
+ .base
+ .get_or_insert_with(|| system::reserve(self.reserved, self.name));
+ // SAFETY: Both sizes are multiples of the page size and at most `reserved`, so the range is the part of the
+ // reservation from where its memory ends.
+ unsafe { system::commit(base.add(self.committed), committed - self.committed) };
+ self.committed = committed;
+ }
+
+ /// Gives the memory past the first `size` bytes back to the system.
+ pub(crate) fn decommit_past(&mut self, size: usize) {
+ let kept = size.next_multiple_of(system::page_size());
+ if kept >= self.committed {
+ return;
+ }
+ let base = self.base.expect("a region with memory has address space");
+ // SAFETY: The range is the end of the memory of the reservation, and `committed` shrinks to leave it out, so
+ // nothing reads or writes it until commit() makes it memory again.
+ unsafe { system::decommit(base.add(kept), self.committed - kept, self.name) };
+ self.committed = kept;
+ }
+}
+
+impl Drop for Region {
+ fn drop(&mut self) {
+ let Some(base) = self.base else {
+ return;
+ };
+ // SAFETY: The reservation is this region's, which nothing can use once it is dropped.
+ unsafe { system::release(base, self.reserved) };
+ }
+}
+
+// SAFETY: A region owns its mapping, and no thread has a special tie to a mapping.
+unsafe impl Send for Region {}
+
+/// The size of a page of memory.
+#[cfg(test)]
+pub(crate) fn page_size() -> usize {
+ system::page_size()
+}