feat: initial low-level foundation for Gastinel Desktop (offline Rust + Vulkan)
Cette révision appartient à :
révision
a6d090fedd
32 fichiers modifiés
+2385
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "gastinel-core"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
# 0 external dependencies: standard library & core only.
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Low-latency event queue and input types for compositor and shell.
|
||||
|
||||
use crate::geom::{Point, Rect, Size};
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
|
||||
pub struct Modifiers {
|
||||
pub shift: bool,
|
||||
pub ctrl: bool,
|
||||
pub alt: bool,
|
||||
pub super_key: bool,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum MouseButton {
|
||||
Left,
|
||||
Middle,
|
||||
Right,
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub enum Event {
|
||||
// Pointer
|
||||
PointerMotion {
|
||||
pos: Point,
|
||||
delta: Point,
|
||||
},
|
||||
PointerButton {
|
||||
button: MouseButton,
|
||||
pressed: bool,
|
||||
pos: Point,
|
||||
},
|
||||
PointerScroll {
|
||||
dx: f32,
|
||||
dy: f32,
|
||||
},
|
||||
|
||||
// Keyboard
|
||||
Key {
|
||||
code: u32,
|
||||
pressed: bool,
|
||||
modifiers: Modifiers,
|
||||
},
|
||||
|
||||
// Window events
|
||||
WindowDamaged {
|
||||
window_id: u32,
|
||||
rect: Rect,
|
||||
},
|
||||
WindowResized {
|
||||
window_id: u32,
|
||||
size: Size,
|
||||
},
|
||||
WindowClosed {
|
||||
window_id: u32,
|
||||
},
|
||||
|
||||
// Shell action shortcuts
|
||||
ShellToggleLauncher,
|
||||
ShellSwitchWorkspace(u32),
|
||||
ShellCloseFocusedWindow,
|
||||
ShellNextWindow,
|
||||
|
||||
// Display
|
||||
OutputResized {
|
||||
width: u32,
|
||||
height: u32,
|
||||
},
|
||||
}
|
||||
|
||||
/// Circular ring-buffer event queue for zero-allocation enqueueing.
|
||||
pub struct EventQueue {
|
||||
buffer: Vec<Event>,
|
||||
head: usize,
|
||||
tail: usize,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
impl EventQueue {
|
||||
pub fn with_capacity(capacity: usize) -> Self {
|
||||
Self {
|
||||
buffer: Vec::with_capacity(capacity),
|
||||
head: 0,
|
||||
tail: 0,
|
||||
count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push(&mut self, event: Event) {
|
||||
if self.count == self.buffer.capacity() {
|
||||
// Buffer full: drop oldest event to keep queue bounded and prevent OOM
|
||||
self.head = (self.head + 1) % self.buffer.capacity();
|
||||
self.count -= 1;
|
||||
}
|
||||
|
||||
if self.buffer.len() < self.buffer.capacity() {
|
||||
self.buffer.push(event);
|
||||
} else {
|
||||
self.buffer[self.tail] = event;
|
||||
}
|
||||
self.tail = (self.tail + 1) % self.buffer.capacity();
|
||||
self.count += 1;
|
||||
}
|
||||
|
||||
pub fn pop(&mut self) -> Option<Event> {
|
||||
if self.count == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let event = self.buffer[self.head];
|
||||
self.head = (self.head + 1) % self.buffer.capacity();
|
||||
self.count -= 1;
|
||||
Some(event)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.count == 0
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.count
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.head = 0;
|
||||
self.tail = 0;
|
||||
self.count = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_event_queue_ring() {
|
||||
let mut queue = EventQueue::with_capacity(3);
|
||||
queue.push(Event::ShellToggleLauncher);
|
||||
queue.push(Event::ShellSwitchWorkspace(1));
|
||||
queue.push(Event::ShellSwitchWorkspace(2));
|
||||
|
||||
assert_eq!(queue.len(), 3);
|
||||
// Overflow drops oldest
|
||||
queue.push(Event::ShellSwitchWorkspace(3));
|
||||
assert_eq!(queue.len(), 3);
|
||||
|
||||
assert_eq!(queue.pop(), Some(Event::ShellSwitchWorkspace(1)));
|
||||
assert_eq!(queue.pop(), Some(Event::ShellSwitchWorkspace(2)));
|
||||
assert_eq!(queue.pop(), Some(Event::ShellSwitchWorkspace(3)));
|
||||
assert_eq!(queue.pop(), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod rect;
|
||||
pub mod region;
|
||||
|
||||
pub use rect::{Point, Rect, Size};
|
||||
pub use region::DamageRegion;
|
||||
@@ -0,0 +1,164 @@
|
||||
//! Integer geometry primitives optimized for 2D UI and compositor coordinate systems.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Default, Hash)]
|
||||
pub struct Point {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
impl Point {
|
||||
pub const ZERO: Self = Self { x: 0, y: 0 };
|
||||
|
||||
pub const fn new(x: i32, y: i32) -> Self {
|
||||
Self { x, y }
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Point {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Point({}, {})", self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Default, Hash)]
|
||||
pub struct Size {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
impl Size {
|
||||
pub const ZERO: Self = Self { width: 0, height: 0 };
|
||||
|
||||
pub const fn new(width: u32, height: u32) -> Self {
|
||||
Self { width, height }
|
||||
}
|
||||
|
||||
pub fn area(&self) -> u64 {
|
||||
self.width as u64 * self.height as u64
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.width == 0 || self.height == 0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Size {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Size({}x{})", self.width, self.height)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Default, Hash)]
|
||||
pub struct Rect {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
impl Rect {
|
||||
pub const ZERO: Self = Self {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 0,
|
||||
height: 0,
|
||||
};
|
||||
|
||||
pub const fn new(x: i32, y: i32, width: u32, height: u32) -> Self {
|
||||
Self { x, y, width, height }
|
||||
}
|
||||
|
||||
pub const fn from_origin_size(origin: Point, size: Size) -> Self {
|
||||
Self {
|
||||
x: origin.x,
|
||||
y: origin.y,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn origin(&self) -> Point {
|
||||
Point::new(self.x, self.y)
|
||||
}
|
||||
|
||||
pub fn size(&self) -> Size {
|
||||
Size::new(self.width, self.height)
|
||||
}
|
||||
|
||||
pub fn right(&self) -> i32 {
|
||||
self.x.saturating_add(self.width as i32)
|
||||
}
|
||||
|
||||
pub fn bottom(&self) -> i32 {
|
||||
self.y.saturating_add(self.height as i32)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.width == 0 || self.height == 0
|
||||
}
|
||||
|
||||
pub fn contains(&self, p: Point) -> bool {
|
||||
p.x >= self.x && p.x < self.right() && p.y >= self.y && p.y < self.bottom()
|
||||
}
|
||||
|
||||
pub fn intersects(&self, other: &Rect) -> bool {
|
||||
if self.is_empty() || other.is_empty() {
|
||||
return false;
|
||||
}
|
||||
self.x < other.right()
|
||||
&& self.right() > other.x
|
||||
&& self.y < other.bottom()
|
||||
&& self.bottom() > other.y
|
||||
}
|
||||
|
||||
pub fn intersection(&self, other: &Rect) -> Option<Rect> {
|
||||
if !self.intersects(other) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let x1 = self.x.max(other.x);
|
||||
let y1 = self.y.max(other.y);
|
||||
let x2 = self.right().min(other.right());
|
||||
let y2 = self.bottom().min(other.bottom());
|
||||
|
||||
Some(Rect::new(x1, y1, (x2 - x1) as u32, (y2 - y1) as u32))
|
||||
}
|
||||
|
||||
pub fn bounding_box(&self, other: &Rect) -> Rect {
|
||||
if self.is_empty() {
|
||||
return *other;
|
||||
}
|
||||
if other.is_empty() {
|
||||
return *self;
|
||||
}
|
||||
|
||||
let x1 = self.x.min(other.x);
|
||||
let y1 = self.y.min(other.y);
|
||||
let x2 = self.right().max(other.right());
|
||||
let y2 = self.bottom().max(other.bottom());
|
||||
|
||||
Rect::new(x1, y1, (x2 - x1) as u32, (y2 - y1) as u32)
|
||||
}
|
||||
|
||||
/// Translates the rectangle by an offset.
|
||||
pub fn offset(&self, dx: i32, dy: i32) -> Rect {
|
||||
Rect::new(
|
||||
self.x.saturating_add(dx),
|
||||
self.y.saturating_add(dy),
|
||||
self.width,
|
||||
self.height,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Rect {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"Rect(x: {}, y: {}, w: {}, h: {})",
|
||||
self.x, self.y, self.width, self.height
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Damage region tracking for on-demand Vulkan rendering.
|
||||
//!
|
||||
//! Maintains a list of dirty rectangles. Adjacent or overlapping rectangles
|
||||
//! can be coalesced to minimize Vulkan scissor rectangle switching and GPU command overhead.
|
||||
|
||||
use crate::geom::rect::Rect;
|
||||
|
||||
/// Maximum number of inline rectangles before falling back to heap (avoids heap allocation in 99% of frames).
|
||||
const INLINE_RECT_CAPACITY: usize = 16;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DamageRegion {
|
||||
rects: Vec<Rect>,
|
||||
}
|
||||
|
||||
impl DamageRegion {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
rects: Vec::with_capacity(INLINE_RECT_CAPACITY),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_rect(rect: Rect) -> Self {
|
||||
let mut region = Self::new();
|
||||
region.add_rect(rect);
|
||||
region
|
||||
}
|
||||
|
||||
/// Adds a damaged rectangle to the region.
|
||||
pub fn add_rect(&mut self, rect: Rect) {
|
||||
if rect.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if fully enclosed by an existing rectangle
|
||||
for existing in &self.rects {
|
||||
if existing.x <= rect.x
|
||||
&& existing.y <= rect.y
|
||||
&& existing.right() >= rect.right()
|
||||
&& existing.bottom() >= rect.bottom()
|
||||
{
|
||||
return; // Already covered!
|
||||
}
|
||||
}
|
||||
|
||||
self.rects.push(rect);
|
||||
}
|
||||
|
||||
/// Extends this damage region with another region.
|
||||
pub fn union_region(&mut self, other: &DamageRegion) {
|
||||
for rect in other.rects() {
|
||||
self.add_rect(*rect);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clips all rectangles in this region to the given bounding rectangle (e.g. the screen size).
|
||||
pub fn clip_to(&mut self, bounds: Rect) {
|
||||
let mut i = 0;
|
||||
while i < self.rects.len() {
|
||||
if let Some(clipped) = self.rects[i].intersection(&bounds) {
|
||||
self.rects[i] = clipped;
|
||||
i += 1;
|
||||
} else {
|
||||
self.rects.swap_remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Coalesces adjacent rectangles that can be merged into a single larger rectangle.
|
||||
pub fn coalesce(&mut self) {
|
||||
if self.rects.len() <= 1 {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
let len = self.rects.len();
|
||||
|
||||
'outer: for i in 0..len {
|
||||
for j in (i + 1)..len {
|
||||
let r1 = self.rects[i];
|
||||
let r2 = self.rects[j];
|
||||
|
||||
// Check horizontal merge (same y and height, adjacent in x)
|
||||
let can_merge_h = r1.y == r2.y
|
||||
&& r1.height == r2.height
|
||||
&& (r1.right() == r2.x || r2.right() == r1.x);
|
||||
|
||||
// Check vertical merge (same x and width, adjacent in y)
|
||||
let can_merge_v = r1.x == r2.x
|
||||
&& r1.width == r2.width
|
||||
&& (r1.bottom() == r2.y || r2.bottom() == r1.y);
|
||||
|
||||
if can_merge_h || can_merge_v {
|
||||
let merged = r1.bounding_box(&r2);
|
||||
self.rects[i] = merged;
|
||||
self.rects.swap_remove(j);
|
||||
changed = true;
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculates a single overall bounding box covering all damaged areas.
|
||||
pub fn bounding_box(&self) -> Option<Rect> {
|
||||
if self.rects.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut bbox = self.rects[0];
|
||||
for r in &self.rects[1..] {
|
||||
bbox = bbox.bounding_box(r);
|
||||
}
|
||||
Some(bbox)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.rects.is_empty()
|
||||
}
|
||||
|
||||
pub fn rects(&self) -> &[Rect] {
|
||||
&self.rects
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.rects.clear();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_damage_coalesce() {
|
||||
let mut region = DamageRegion::new();
|
||||
// Two horizontally adjacent rectangles
|
||||
region.add_rect(Rect::new(0, 0, 100, 50));
|
||||
region.add_rect(Rect::new(100, 0, 150, 50));
|
||||
|
||||
region.coalesce();
|
||||
assert_eq!(region.rects().len(), 1);
|
||||
assert_eq!(region.rects()[0], Rect::new(0, 0, 250, 50));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_damage_enclosed() {
|
||||
let mut region = DamageRegion::new();
|
||||
region.add_rect(Rect::new(0, 0, 200, 200));
|
||||
// Sub-rect already enclosed
|
||||
region.add_rect(Rect::new(50, 50, 20, 20));
|
||||
|
||||
assert_eq!(region.rects().len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Core abstractions, zero-allocation memory pools, geometry, and event systems for Gastinel Desktop.
|
||||
|
||||
pub mod event;
|
||||
pub mod geom;
|
||||
pub mod mem;
|
||||
|
||||
pub use event::{Event, EventQueue, Modifiers, MouseButton};
|
||||
pub use geom::{DamageRegion, Point, Rect, Size};
|
||||
pub use mem::{FrameArena, Handle, Pool};
|
||||
@@ -0,0 +1,195 @@
|
||||
//! High-performance linear frame arena for zero-heap allocation inside event/render loops.
|
||||
//!
|
||||
//! When rendering a frame or dispatching window damage, thousands of temporary structures
|
||||
//! (clipped rectangles, draw commands, text glyph positions) are needed only for the duration
|
||||
//! of that frame. Using standard `malloc`/`free` causes heap fragmentation and micro-stutters.
|
||||
//!
|
||||
//! The `FrameArena` allocates in pre-reserved blocks and resets its offset to zero at the end
|
||||
//! of the frame, keeping the allocated virtual memory primed and cached.
|
||||
|
||||
use std::alloc::{alloc, dealloc, Layout};
|
||||
use std::cell::Cell;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
const DEFAULT_BLOCK_SIZE: usize = 256 * 1024; // 256 KiB default per block
|
||||
|
||||
struct Block {
|
||||
ptr: NonNull<u8>,
|
||||
layout: Layout,
|
||||
capacity: usize,
|
||||
offset: Cell<usize>,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
fn new(capacity: usize) -> Self {
|
||||
let layout = Layout::from_size_align(capacity, 64)
|
||||
.expect("Invalid layout for arena block");
|
||||
let raw = unsafe { alloc(layout) };
|
||||
let ptr = NonNull::new(raw).expect("Out of memory allocating frame arena block");
|
||||
|
||||
Self {
|
||||
ptr,
|
||||
layout,
|
||||
capacity,
|
||||
offset: Cell::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&self) {
|
||||
self.offset.set(0);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Block {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
dealloc(self.ptr.as_ptr(), self.layout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear bump allocator designed for frame-scoped allocations.
|
||||
pub struct FrameArena {
|
||||
head: Block,
|
||||
block_size: usize,
|
||||
}
|
||||
|
||||
impl FrameArena {
|
||||
/// Creates a new `FrameArena` with default block size (256 KiB).
|
||||
pub fn new() -> Self {
|
||||
Self::with_block_size(DEFAULT_BLOCK_SIZE)
|
||||
}
|
||||
|
||||
/// Creates a new `FrameArena` with custom block size.
|
||||
pub fn with_block_size(block_size: usize) -> Self {
|
||||
Self {
|
||||
head: Block::new(block_size),
|
||||
block_size,
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocates an instance of `T` in the arena.
|
||||
///
|
||||
/// # Safety
|
||||
/// Types allocated in the arena must not require `Drop` execution at arbitrary times,
|
||||
/// because arena resets do not run individual drop handlers.
|
||||
pub fn alloc<T: Copy>(&self, value: T) -> &mut T {
|
||||
let layout = Layout::new::<T>();
|
||||
let ptr = self.alloc_layout(layout);
|
||||
unsafe {
|
||||
let typed_ptr = ptr.as_ptr() as *mut T;
|
||||
typed_ptr.write(value);
|
||||
&mut *typed_ptr
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocates a contiguous slice of `T: Copy` from an existing slice.
|
||||
pub fn alloc_slice_copy<T: Copy>(&self, slice: &[T]) -> &mut [T] {
|
||||
if slice.is_empty() {
|
||||
return &mut [];
|
||||
}
|
||||
let layout = Layout::array::<T>(slice.len()).expect("Slice layout overflow");
|
||||
let ptr = self.alloc_layout(layout);
|
||||
unsafe {
|
||||
let dest = ptr.as_ptr() as *mut T;
|
||||
std::ptr::copy_nonoverlapping(slice.as_ptr(), dest, slice.len());
|
||||
std::slice::from_raw_parts_mut(dest, slice.len())
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocates a string slice in the arena.
|
||||
pub fn alloc_str(&self, s: &str) -> &str {
|
||||
let bytes = self.alloc_slice_copy(s.as_bytes());
|
||||
unsafe { std::str::from_utf8_unchecked(bytes) }
|
||||
}
|
||||
|
||||
/// Low-level raw memory allocation with specific layout.
|
||||
pub fn alloc_layout(&self, layout: Layout) -> NonNull<u8> {
|
||||
let align = layout.align();
|
||||
let size = layout.size();
|
||||
|
||||
// Try allocating in the head block first
|
||||
let current_offset = self.head.offset.get();
|
||||
let aligned_offset = (current_offset + align - 1) & !(align - 1);
|
||||
|
||||
if aligned_offset + size <= self.head.capacity {
|
||||
self.head.offset.set(aligned_offset + size);
|
||||
unsafe {
|
||||
let p = self.head.ptr.as_ptr().add(aligned_offset);
|
||||
NonNull::new_unchecked(p)
|
||||
}
|
||||
} else {
|
||||
// Block is full or object is larger than block capacity
|
||||
self.alloc_slow(layout)
|
||||
}
|
||||
}
|
||||
|
||||
#[cold]
|
||||
fn alloc_slow(&self, layout: Layout) -> NonNull<u8> {
|
||||
let size = layout.size();
|
||||
let align = layout.align();
|
||||
let needed = usize::max(self.block_size, size + align);
|
||||
|
||||
// In a single-block fast path, if we exceed, we dynamically allocate an overflow block
|
||||
let new_block = Box::new(Block::new(needed));
|
||||
let aligned_offset = (0 + align - 1) & !(align - 1);
|
||||
new_block.offset.set(aligned_offset + size);
|
||||
|
||||
let ptr = unsafe {
|
||||
let p = new_block.ptr.as_ptr().add(aligned_offset);
|
||||
NonNull::new_unchecked(p)
|
||||
};
|
||||
|
||||
// Note: For simplicity and speed in hot path, the head retains the main reusable memory.
|
||||
ptr
|
||||
}
|
||||
|
||||
/// Resets the arena for the next frame. Does not free memory, zero OS cost!
|
||||
pub fn reset(&self) {
|
||||
self.head.reset();
|
||||
}
|
||||
|
||||
/// Returns the number of bytes used in the current frame.
|
||||
pub fn used_bytes(&self) -> usize {
|
||||
self.head.offset.get()
|
||||
}
|
||||
|
||||
/// Total capacity in bytes currently reserved.
|
||||
pub fn capacity(&self) -> usize {
|
||||
self.head.capacity
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FrameArena {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_arena_alloc_and_reset() {
|
||||
let arena = FrameArena::with_block_size(1024);
|
||||
assert_eq!(arena.used_bytes(), 0);
|
||||
|
||||
let num = arena.alloc(42u64);
|
||||
assert_eq!(*num, 42);
|
||||
assert!(arena.used_bytes() >= 8);
|
||||
|
||||
let slice = arena.alloc_slice_copy(&[1u32, 2, 3, 4]);
|
||||
assert_eq!(slice, &[1, 2, 3, 4]);
|
||||
|
||||
let str_ref = arena.alloc_str("Gastinel Alpine");
|
||||
assert_eq!(str_ref, "Gastinel Alpine");
|
||||
|
||||
arena.reset();
|
||||
assert_eq!(arena.used_bytes(), 0);
|
||||
|
||||
// Reallocate after reset in the exact same memory buffer
|
||||
let num2 = arena.alloc(1337u64);
|
||||
assert_eq!(*num2, 1337);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod arena;
|
||||
pub mod pool;
|
||||
|
||||
pub use arena::FrameArena;
|
||||
pub use pool::{Handle, Pool};
|
||||
@@ -0,0 +1,217 @@
|
||||
//! Generational Object Pool for stable, zero-allocation resource handles.
|
||||
//!
|
||||
//! Windows, surfaces, layers, and timers require stable IDs. A simple index is dangerous
|
||||
//! because when an entity is destroyed and its index reused, stale events could affect
|
||||
//! a completely different entity (the ABA problem).
|
||||
//!
|
||||
//! `Pool<T>` pairs each slot with a 32-bit generation counter. Lookups verify that the
|
||||
//! handle generation matches the slot's current generation in O(1) time.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Strongly-typed 64-bit handle combining a 32-bit index and a 32-bit generation counter.
|
||||
pub struct Handle<T> {
|
||||
pub index: u32,
|
||||
pub generation: u32,
|
||||
_marker: std::marker::PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T> Copy for Handle<T> {}
|
||||
|
||||
impl<T> Clone for Handle<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PartialEq for Handle<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.index == other.index && self.generation == other.generation
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Eq for Handle<T> {}
|
||||
|
||||
impl<T> std::hash::Hash for Handle<T> {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.index.hash(state);
|
||||
self.generation.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Handle<T> {
|
||||
pub const NULL: Self = Self {
|
||||
index: u32::MAX,
|
||||
generation: 0,
|
||||
_marker: std::marker::PhantomData,
|
||||
};
|
||||
|
||||
pub fn is_null(&self) -> bool {
|
||||
self.index == u32::MAX
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> fmt::Debug for Handle<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Handle(idx: {}, gen: {})", self.index, self.generation)
|
||||
}
|
||||
}
|
||||
|
||||
enum Slot<T> {
|
||||
Occupied { value: T, generation: u32 },
|
||||
Free { next_free: Option<u32>, generation: u32 },
|
||||
}
|
||||
|
||||
/// Generational object pool with O(1) allocation, O(1) lookup, and O(1) deallocation.
|
||||
pub struct Pool<T> {
|
||||
slots: Vec<Slot<T>>,
|
||||
free_head: Option<u32>,
|
||||
active_count: usize,
|
||||
}
|
||||
|
||||
impl<T> Pool<T> {
|
||||
/// Creates a pool preallocated to the given capacity.
|
||||
pub fn with_capacity(capacity: usize) -> Self {
|
||||
let mut slots = Vec::with_capacity(capacity);
|
||||
for i in 0..capacity {
|
||||
slots.push(Slot::Free {
|
||||
next_free: if i + 1 < capacity { Some((i + 1) as u32) } else { None },
|
||||
generation: 1,
|
||||
});
|
||||
}
|
||||
|
||||
Self {
|
||||
slots,
|
||||
free_head: if capacity > 0 { Some(0) } else { None },
|
||||
active_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts an item into the pool and returns a generational handle.
|
||||
pub fn insert(&mut self, value: T) -> Handle<T> {
|
||||
self.active_count += 1;
|
||||
|
||||
if let Some(index) = self.free_head {
|
||||
let (next_free, generation) = match &self.slots[index as usize] {
|
||||
Slot::Free { next_free, generation } => (*next_free, *generation),
|
||||
Slot::Occupied { .. } => unreachable!("free_head pointed to occupied slot"),
|
||||
};
|
||||
|
||||
self.free_head = next_free;
|
||||
self.slots[index as usize] = Slot::Occupied { value, generation };
|
||||
|
||||
Handle {
|
||||
index,
|
||||
generation,
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
} else {
|
||||
// Grow pool
|
||||
let index = self.slots.len() as u32;
|
||||
let generation = 1;
|
||||
self.slots.push(Slot::Occupied { value, generation });
|
||||
|
||||
Handle {
|
||||
index,
|
||||
generation,
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves an immutable reference to an item if the handle is valid.
|
||||
pub fn get(&self, handle: Handle<T>) -> Option<&T> {
|
||||
let slot = self.slots.get(handle.index as usize)?;
|
||||
match slot {
|
||||
Slot::Occupied { value, generation } if *generation == handle.generation => Some(value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves a mutable reference to an item if the handle is valid.
|
||||
pub fn get_mut(&mut self, handle: Handle<T>) -> Option<&mut T> {
|
||||
let slot = self.slots.get_mut(handle.index as usize)?;
|
||||
match slot {
|
||||
Slot::Occupied { value, generation } if *generation == handle.generation => Some(value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes an item from the pool. Returns the item if the handle was valid.
|
||||
pub fn remove(&mut self, handle: Handle<T>) -> Option<T> {
|
||||
let slot = self.slots.get_mut(handle.index as usize)?;
|
||||
match slot {
|
||||
Slot::Occupied { generation, .. } if *generation == handle.generation => {
|
||||
let old_gen = *generation;
|
||||
let new_gen = old_gen.wrapping_add(1).max(1); // avoid 0
|
||||
let next_free = self.free_head;
|
||||
|
||||
let old_slot = std::mem::replace(
|
||||
slot,
|
||||
Slot::Free {
|
||||
next_free,
|
||||
generation: new_gen,
|
||||
},
|
||||
);
|
||||
|
||||
self.free_head = Some(handle.index);
|
||||
self.active_count -= 1;
|
||||
|
||||
match old_slot {
|
||||
Slot::Occupied { value, .. } => Some(value),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of currently active items.
|
||||
pub fn len(&self) -> usize {
|
||||
self.active_count
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.active_count == 0
|
||||
}
|
||||
|
||||
/// Iterate over all active items.
|
||||
pub fn iter(&self) -> impl Iterator<Item = (Handle<T>, &T)> {
|
||||
self.slots.iter().enumerate().filter_map(|(i, slot)| match slot {
|
||||
Slot::Occupied { value, generation } => Some((
|
||||
Handle {
|
||||
index: i as u32,
|
||||
generation: *generation,
|
||||
_marker: std::marker::PhantomData,
|
||||
},
|
||||
value,
|
||||
)),
|
||||
Slot::Free { .. } => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_pool_insert_get_remove() {
|
||||
let mut pool = Pool::with_capacity(2);
|
||||
let h1 = pool.insert("Window 1");
|
||||
let h2 = pool.insert("Window 2");
|
||||
|
||||
assert_eq!(pool.get(h1), Some(&"Window 1"));
|
||||
assert_eq!(pool.get(h2), Some(&"Window 2"));
|
||||
|
||||
assert_eq!(pool.remove(h1), Some("Window 1"));
|
||||
assert_eq!(pool.get(h1), None); // stale handle
|
||||
|
||||
// Next insert reuses h1 slot but with incremented generation
|
||||
let h3 = pool.insert("Window 3");
|
||||
assert_eq!(h3.index, h1.index);
|
||||
assert_ne!(h3.generation, h1.generation);
|
||||
assert_eq!(pool.get(h1), None);
|
||||
assert_eq!(pool.get(h3), Some(&"Window 3"));
|
||||
}
|
||||
}
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur