Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions crates/grida-canvas/src/cache/atlas/atlas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
use super::packing::{ShelfPacker, Slot, SlotId};
use crate::node::schema::NodeId;
use skia_safe::{Canvas, Image, Rect, Surface};
use std::collections::HashMap;
use crate::cache::fast_hash::{new_node_id_map, NodeIdHashMap};

/// A single atlas page.
///
Expand All @@ -26,9 +26,9 @@ pub struct AtlasPage {
/// Shelf packer managing slot allocation.
packer: ShelfPacker,
/// Map from slot ID to the node that occupies it.
slot_to_node: HashMap<SlotId, NodeId>,
slot_to_node: NodeIdHashMap<SlotId, NodeId>,
/// Map from node ID to its allocated slot.
node_to_slot: HashMap<NodeId, Slot>,
node_to_slot: NodeIdHashMap<NodeId, Slot>,
/// Whether the surface has been modified since the last snapshot.
dirty: bool,
/// Page index (for multi-page atlas sets).
Expand Down Expand Up @@ -70,8 +70,8 @@ impl AtlasPage {
surface,
image: None,
packer: ShelfPacker::new(w, h),
slot_to_node: HashMap::new(),
node_to_slot: HashMap::new(),
slot_to_node: new_node_id_map(),
node_to_slot: new_node_id_map(),
dirty: false,
page_index,
}
Expand Down
6 changes: 3 additions & 3 deletions crates/grida-canvas/src/cache/atlas/atlas_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use super::atlas::{AtlasAllocation, AtlasPage};
use crate::node::schema::NodeId;
use skia_safe::{Image, Surface};
use std::collections::HashMap;
use crate::cache::fast_hash::{new_node_id_map, NodeIdHashMap};

/// Configuration for an atlas set.
#[derive(Debug, Clone, Copy)]
Expand Down Expand Up @@ -54,7 +54,7 @@ pub struct AtlasSet {
config: AtlasSetConfig,
pages: Vec<AtlasPage>,
/// Map from node ID to the page index it's allocated on.
node_page: HashMap<NodeId, u32>,
node_page: NodeIdHashMap<NodeId, u32>,
}

impl AtlasSet {
Expand All @@ -65,7 +65,7 @@ impl AtlasSet {
Self {
config,
pages: Vec::new(),
node_page: HashMap::new(),
node_page: new_node_id_map(),
}
}

Expand Down
6 changes: 3 additions & 3 deletions crates/grida-canvas/src/cache/compositor/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::cg::prelude::LayerBlendMode;
use crate::node::schema::NodeId;
use math2::rect::Rectangle;
use skia_safe::Image;
use std::collections::HashMap;
use crate::cache::fast_hash::{new_node_id_map, NodeIdHashMap};
use std::rc::Rc;

/// Where a promoted node's cached pixels live.
Expand Down Expand Up @@ -108,7 +108,7 @@ pub struct LayerImageCacheStats {
#[derive(Debug, Clone)]
pub struct LayerImageCache {
/// Promoted node entries, keyed by node ID.
images: HashMap<NodeId, LayerImage>,
images: NodeIdHashMap<NodeId, LayerImage>,
/// Maximum memory budget in bytes (default: 128 MB).
/// Only individual (non-atlas) images count against this budget.
memory_budget: usize,
Expand All @@ -131,7 +131,7 @@ impl LayerImageCache {
/// Create a new layer image cache with the given memory budget.
pub fn new(memory_budget: usize) -> Self {
Self {
images: HashMap::new(),
images: new_node_id_map(),
memory_budget,
memory_used: 0,
frame_counter: 0,
Expand Down
76 changes: 76 additions & 0 deletions crates/grida-canvas/src/cache/fast_hash.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//! Fast hasher for u64-keyed HashMaps in the rendering hot path.
//!
//! The default `HashMap` uses SipHash-1-3, which provides DoS resistance
//! at ~25ns per hash. For trusted-input rendering caches keyed by `NodeId`
//! (u64), we can use a much faster multiplicative hash (~3ns) since there
//! is no untrusted input to defend against.
//!
//! This is the same approach as `rustc-hash` (FxHash): multiply by a large
//! odd constant to scatter bits, then use the result directly as the hash.

use std::collections::HashMap;
use std::hash::{BuildHasher, Hasher};

/// A fast hasher for integer keys.
///
/// Uses a single multiply to distribute bits. Suitable for u64 keys
/// (NodeId) and (u64, u64) tuple keys used in the picture/geometry/
/// compositor caches.
#[derive(Default)]
pub struct NodeIdHasher {
hash: u64,
}

impl Hasher for NodeIdHasher {
#[inline]
fn write(&mut self, bytes: &[u8]) {
// For arbitrary byte sequences, use a simple FNV-like combine.
for &b in bytes {
self.hash = self.hash.wrapping_mul(0x100000001b3).wrapping_add(b as u64);
}
}

#[inline]
fn write_u64(&mut self, i: u64) {
// FxHash: XOR-fold then multiply by a large odd constant.
// This is the primary fast path for NodeId (u64) keys.
self.hash = self.hash ^ i;
self.hash = self.hash.wrapping_mul(0x517cc1b727220a95);
}

#[inline]
fn finish(&self) -> u64 {
self.hash
}
}

/// BuildHasher that produces `NodeIdHasher` instances.
#[derive(Clone, Default)]
pub struct NodeIdBuildHasher;

impl BuildHasher for NodeIdBuildHasher {
type Hasher = NodeIdHasher;

#[inline]
fn build_hasher(&self) -> NodeIdHasher {
NodeIdHasher::default()
}
}

/// A HashMap using the fast NodeId hasher.
///
/// Use this for caches keyed by `NodeId` (u64) or `(NodeId, u64)` tuples
/// where keys come from trusted internal sources (no DoS risk).
pub type NodeIdHashMap<K, V> = HashMap<K, V, NodeIdBuildHasher>;

/// Create a new empty NodeIdHashMap.
#[inline]
pub fn new_node_id_map<K, V>() -> NodeIdHashMap<K, V> {
HashMap::with_hasher(NodeIdBuildHasher)
}

/// Create a new NodeIdHashMap with the specified capacity.
#[inline]
pub fn new_node_id_map_with_capacity<K, V>(capacity: usize) -> NodeIdHashMap<K, V> {
HashMap::with_capacity_and_hasher(capacity, NodeIdBuildHasher)
}
6 changes: 3 additions & 3 deletions crates/grida-canvas/src/cache/geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::runtime::font_repository::FontRepository;
use math2::rect;
use math2::rect::Rectangle;
use math2::transform::AffineTransform;
use std::collections::HashMap;
use crate::cache::fast_hash::{new_node_id_map, NodeIdHashMap};

/// Geometry data used for layout, culling, and rendering.
///
Expand Down Expand Up @@ -52,13 +52,13 @@ struct GeometryBuildContext {

#[derive(Debug, Clone)]
pub struct GeometryCache {
entries: HashMap<NodeId, GeometryEntry>,
entries: NodeIdHashMap<NodeId, GeometryEntry>,
}

impl GeometryCache {
pub fn new() -> Self {
Self {
entries: HashMap::new(),
entries: new_node_id_map(),
}
}

Expand Down
1 change: 1 addition & 0 deletions crates/grida-canvas/src/cache/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod atlas;
pub mod compositor;
pub mod fast_hash;
pub mod geometry;
pub mod mipmap;
pub mod paragraph;
Expand Down
10 changes: 5 additions & 5 deletions crates/grida-canvas/src/cache/picture.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::cache::fast_hash::{new_node_id_map, NodeIdHashMap};
use crate::node::schema::NodeId;
use skia_safe::Picture;
use std::collections::HashMap;

/// Configuration for how the scene should be cached.
///
Expand All @@ -22,17 +22,17 @@ impl Default for PictureCacheStrategy {
pub struct PictureCache {
strategy: PictureCacheStrategy,
/// Fast-path store for the default render variant (variant key = 0).
default_store: HashMap<NodeId, Picture>,
default_store: NodeIdHashMap<NodeId, Picture>,
/// Store for non-default render variants (variant key != 0).
variant_store: HashMap<(NodeId, u64), Picture>,
variant_store: NodeIdHashMap<(NodeId, u64), Picture>,
}

impl PictureCache {
pub fn new() -> Self {
Self {
strategy: PictureCacheStrategy::default(),
default_store: HashMap::new(),
variant_store: HashMap::new(),
default_store: new_node_id_map(),
variant_store: new_node_id_map(),
}
}

Expand Down
6 changes: 3 additions & 3 deletions crates/grida-canvas/src/cache/vector_path.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::cache::fast_hash::{new_node_id_map, NodeIdHashMap};
use crate::node::schema::NodeId;
use skia_safe::Path;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::rc::Rc;

Expand All @@ -13,13 +13,13 @@ pub struct VectorPathCacheEntry {

#[derive(Default, Clone, Debug)]
pub struct VectorPathCache {
entries: HashMap<NodeId, VectorPathCacheEntry>,
entries: NodeIdHashMap<NodeId, VectorPathCacheEntry>,
}

impl VectorPathCache {
pub fn new() -> Self {
Self {
entries: HashMap::new(),
entries: new_node_id_map(),
}
}

Expand Down
6 changes: 3 additions & 3 deletions crates/grida-canvas/src/painter/painter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ use skia_safe::{
canvas::SaveLayerRec, textlayout, Matrix, Paint as SkPaint, Path, PathBuilder, Point, Rect,
Shader,
};
use crate::cache::fast_hash::NodeIdHashMap;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

/// Pre-extracted blit data for a single promoted (compositor-cached) node.
Expand Down Expand Up @@ -58,7 +58,7 @@ pub struct Painter<'a> {
/// Pre-extracted blit data for promoted (compositor-cached) nodes.
/// When present, promoted nodes are blitted inline at their correct
/// z-position instead of being skipped.
promoted_blits: Option<&'a HashMap<NodeId, PromotedBlit>>,
promoted_blits: Option<&'a NodeIdHashMap<NodeId, PromotedBlit>>,
}

impl<'a> Painter<'a> {
Expand Down Expand Up @@ -113,7 +113,7 @@ impl<'a> Painter<'a> {
/// Set the promoted blit map. Nodes in this map will be blitted from
/// their pre-extracted compositor cache data at the correct z-position
/// in the render command tree, instead of being re-drawn live.
pub fn with_promoted_blits(mut self, blits: &'a HashMap<NodeId, PromotedBlit>) -> Self {
pub fn with_promoted_blits(mut self, blits: &'a NodeIdHashMap<NodeId, PromotedBlit>) -> Self {
self.promoted_blits = Some(blits);
self
}
Expand Down
6 changes: 3 additions & 3 deletions crates/grida-canvas/src/runtime/scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,10 @@ impl Renderer {
&mut self,
plan: &FramePlan,
) -> (
std::collections::HashMap<NodeId, crate::painter::PromotedBlit>,
crate::cache::fast_hash::NodeIdHashMap<NodeId, crate::painter::PromotedBlit>,
usize,
) {
let mut blits = std::collections::HashMap::new();
let mut blits = crate::cache::fast_hash::new_node_id_map();
let mut cache_hits = 0usize;

for id in &plan.promoted {
Expand Down Expand Up @@ -469,7 +469,7 @@ impl Renderer {
&mut self,
canvas: &Canvas,
plan: &FramePlan,
promoted_blits: Option<&std::collections::HashMap<NodeId, crate::painter::PromotedBlit>>,
promoted_blits: Option<&crate::cache::fast_hash::NodeIdHashMap<NodeId, crate::painter::PromotedBlit>>,
) -> usize {
// Select effect quality based on frame stability.
// Unstable (interactive) frames use reduced effects for performance.
Expand Down
2 changes: 1 addition & 1 deletion crates/grida-canvas/tests/compositor_effects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,7 @@ fn z_order_promoted_child_visible_above_container() {
let offscreen_image = offscreen.image_snapshot();

// Step 2: Build the promoted_blits map
let mut promoted_blits: HashMap<NodeId, PromotedBlit> = HashMap::new();
let mut promoted_blits: cg::cache::fast_hash::NodeIdHashMap<NodeId, PromotedBlit> = cg::cache::fast_hash::new_node_id_map();
let src_rect = Rect::new(
0.0,
0.0,
Expand Down
Loading