nativeview_store/resource/
mod.rs1use std::any::TypeId;
10use std::collections::VecDeque;
11use std::sync::OnceLock;
12
13use nativeview_abi::Key64;
14use nativeview_hash::xxh64;
15use rustc_hash::FxHashMap;
16
17use crate::id::ResourceId;
18pub(crate) mod ingress;
19mod wire;
20
21use ingress::ValidatedWords;
22use crate::span_pool::{Span, SpanPool, MAX_SPAN_LEN};
23
24const _: () = assert!(
25 cfg!(target_endian = "little"),
26 "nativeview-store flat u32 ResourceStore requires a little-endian target"
27);
28
29pub const MAX_RESOURCE_WORDS: usize = 16 * 1024 * 1024;
32
33const _: () = assert!(MAX_RESOURCE_WORDS <= (MAX_SPAN_LEN as usize) / 4);
34
35const RES_PENDING_FREE: u16 = 1 << 0;
36const RES_IN_FREE: u16 = 1 << 1;
37const RES_DEFINED_THIS_FRAME: u16 = 1 << 2;
38const RES_CREATED_THIS_FRAME: u16 = 1 << 3;
39const RES_RELEASED_THIS_FRAME: u16 = 1 << 4;
40const RES_OCCUPIED: u16 = 1 << 5;
41const RES_EPHEMERAL: u16 = 1 << 6;
42const RES_CHILDREN_HELD: u16 = 1 << 7;
43
44#[inline(always)]
47pub fn words_as_le_bytes(words: &[u32]) -> &[u8] {
48 unsafe {
51 core::slice::from_raw_parts(words.as_ptr().cast::<u8>(), core::mem::size_of_val(words))
52 }
53}
54
55pub trait FlatResource: 'static {
67 const KIND: Key64;
69
70 type View<'a>;
72
73 fn write_words(&self, out: &mut Vec<u32>) -> bool;
76
77 fn validate(words: &[u32]) -> bool;
79
80 fn view<'a>(words: ValidatedWords<'a, Self>) -> Self::View<'a>;
82
83 #[inline]
86 fn child_resources(_words: &[u32], _visit: &mut dyn FnMut(ResourceId)) {}
87}
88
89pub(crate) struct Entry {
90 kind: Key64,
91 validated_type: OnceLock<TypeId>,
92 span: Span<u32>,
93 children: Span<ResourceId>,
94 refs: u32,
95 hash: u64,
96 generation: u8,
97 flags: u16,
98}
99
100impl Default for Entry {
101 #[inline]
102 fn default() -> Self {
103 Self {
104 kind: Key64(0),
105 validated_type: OnceLock::new(),
106 span: Span::EMPTY,
107 children: Span::EMPTY,
108 refs: 0,
109 hash: 0,
110 generation: 0,
111 flags: 0,
112 }
113 }
114}
115
116pub struct ResourceStore {
118 entries: Vec<Entry>,
119 words: SpanPool<u32>,
120 children: SpanPool<ResourceId>,
121 dedup: FxHashMap<(u64, u64), ResourceId>,
122 free: VecDeque<u32>,
125 pending_free: Vec<u32>,
126 pub(crate) defined: Vec<ResourceId>,
127 pub(crate) released: Vec<ResourceId>,
128 scratch: Vec<u32>,
129 child_scratch: Vec<ResourceId>,
130 old_children_scratch: Vec<ResourceId>,
131 work_stack: Vec<ResourceId>,
132 visit_marks: Vec<u32>,
133 visit_epoch: u32,
134}
135
136impl Default for ResourceStore {
137 fn default() -> Self {
138 Self {
139 entries: vec![Entry::default()],
140 words: SpanPool::default(),
141 children: SpanPool::default(),
142 dedup: FxHashMap::default(),
143 free: VecDeque::new(),
144 pending_free: Vec::new(),
145 defined: Vec::new(),
146 released: Vec::new(),
147 scratch: Vec::new(),
148 child_scratch: Vec::new(),
149 old_children_scratch: Vec::new(),
150 work_stack: Vec::new(),
151 visit_marks: Vec::new(),
152 visit_epoch: 0,
153 }
154 }
155}
156
157impl ResourceStore {
158 #[inline(always)]
160 pub fn word_slab(&self) -> &[u32] {
161 self.words.data()
162 }
163
164 #[inline(always)]
166 pub fn words_live(&self) -> usize {
167 self.words.live()
168 }
169
170 #[inline(always)]
172 pub fn child_edges_live(&self) -> usize {
173 self.children.live()
174 }
175
176 #[inline(always)]
177 pub(crate) fn entry(&self, id: ResourceId) -> Option<&Entry> {
178 let i = id.index();
179 if i == 0 {
180 return None;
181 }
182 let e = self.entries.get(i)?;
183 ((e.flags & RES_OCCUPIED) != 0 && e.generation == id.generation()).then_some(e)
184 }
185
186 #[inline(always)]
187 pub(crate) fn entry_mut(&mut self, id: ResourceId) -> Option<&mut Entry> {
188 let i = id.index();
189 if i == 0 {
190 return None;
191 }
192 let e = self.entries.get_mut(i)?;
193 ((e.flags & RES_OCCUPIED) != 0 && e.generation == id.generation()).then_some(e)
194 }
195
196 fn slot(&mut self) -> Option<ResourceId> {
197 while let Some(i) = self.free.pop_front() {
198 if let Some(e) = self.entries.get_mut(i as usize) {
199 let was_in_free = e.flags & RES_IN_FREE != 0;
200 e.flags &= !RES_IN_FREE;
201 if was_in_free
202 && e.refs == 0
203 && (e.flags & (RES_OCCUPIED | RES_PENDING_FREE)) == 0
204 {
205 return Some(ResourceId::new(i, e.generation));
206 }
207 }
208 }
209 if self.entries.len() > ResourceId::MAX_INDEX as usize {
210 return None;
211 }
212 let next = self.entries.len() as u32;
213 self.entries.push(Entry::default());
214 Some(ResourceId::new(next, 0))
215 }
216
217 fn finish_intern_scratch<R: FlatResource>(&mut self) -> Option<ResourceId> {
218 if self.scratch.len() > MAX_RESOURCE_WORDS || !R::validate(&self.scratch) {
219 return None;
220 }
221 let hash = xxh64(words_as_le_bytes(&self.scratch), R::KIND.0);
222 let tid = TypeId::of::<R>();
223 if let Some(&rid) = self.dedup.get(&(R::KIND.0, hash))
224 && let Some(e) = self.entries.get_mut(rid.index())
225 && (e.flags & (RES_OCCUPIED | RES_EPHEMERAL)) == RES_OCCUPIED
226 && e.generation == rid.generation()
227 && e.refs > 0
228 && e.kind == R::KIND
229 && e.validated_type.get() == Some(&tid)
230 && self.words.get(e.span) == self.scratch.as_slice()
231 {
232 e.refs = e.refs.checked_add(1)?;
233 return Some(rid);
234 }
235
236 let Self {
238 scratch,
239 child_scratch,
240 ..
241 } = self;
242 child_scratch.clear();
243 R::child_resources(scratch, &mut |cid| {
244 if !cid.is_none() {
245 child_scratch.push(cid);
246 }
247 });
248 child_scratch.sort_unstable();
249 child_scratch.dedup();
250 if child_scratch.len() > MAX_SPAN_LEN as usize {
251 return None;
252 }
253 for &cid in &self.child_scratch {
254 if !self.is_live(cid) {
255 return None;
256 }
257 }
258
259 let rid = self.slot()?;
260 for idx in 0..self.child_scratch.len() {
262 let cid = self.child_scratch[idx];
263 self.retain(cid);
264 }
265
266 let span = self.words.replace(Span::EMPTY, &self.scratch);
267 let child_span = self.children.replace(Span::EMPTY, &self.child_scratch);
268 self.entries[rid.index()] = Entry {
269 kind: R::KIND,
270 validated_type: OnceLock::from(tid),
271 span,
272 children: child_span,
273 refs: 1,
274 hash,
275 generation: rid.generation(),
276 flags: RES_OCCUPIED
277 | RES_CHILDREN_HELD
278 | RES_DEFINED_THIS_FRAME
279 | RES_CREATED_THIS_FRAME,
280 };
281 self.dedup.entry((R::KIND.0, hash)).or_insert(rid);
282 self.defined.push(rid);
283 Some(rid)
284 }
285
286 fn finish_ephemeral_scratch<R: FlatResource>(&mut self, old: ResourceId) -> Option<ResourceId> {
287 if self.scratch.len() > MAX_RESOURCE_WORDS || !R::validate(&self.scratch) {
288 return None;
289 }
290 let Self {
291 scratch,
292 child_scratch,
293 ..
294 } = self;
295 child_scratch.clear();
296 R::child_resources(scratch, &mut |cid| {
297 if !cid.is_none() {
298 child_scratch.push(cid);
299 }
300 });
301 child_scratch.sort_unstable();
302 child_scratch.dedup();
303 if child_scratch.len() > MAX_SPAN_LEN as usize {
304 return None;
305 }
306 for &cid in &self.child_scratch {
307 if !self.is_live(cid) {
308 return None;
309 }
310 }
311
312 let tid = TypeId::of::<R>();
313 let can_reuse = self.entry(old).is_some_and(|e| {
314 (e.flags & RES_EPHEMERAL) != 0
315 && e.refs == 1
316 && e.kind == R::KIND
317 && e.validated_type.get() == Some(&tid)
318 });
319
320 if can_reuse {
321 let mut budget = usize::MAX;
322 let creates_cycle = self.reaches_child_scratch_budgeted(old.index(), &mut budget);
323 if !creates_cycle {
324 for idx in 0..self.child_scratch.len() {
326 let cid = self.child_scratch[idx];
327 self.retain(cid);
328 }
329 let old_idx = old.index();
330 let old_span = self.entries[old_idx].span;
331 let old_children = self.entries[old_idx].children;
332 let old_flags = self.entries[old_idx].flags;
333 self.old_children_scratch.clear();
334 self.old_children_scratch
335 .extend_from_slice(self.children.get(old_children));
336
337 let new_span = self.words.replace(old_span, &self.scratch);
338 let new_children = self.children.replace(old_children, &self.child_scratch);
339 let e = &mut self.entries[old_idx];
340 e.span = new_span;
341 e.children = new_children;
342 e.flags |= RES_OCCUPIED | RES_EPHEMERAL | RES_CHILDREN_HELD;
343 if (e.flags & RES_DEFINED_THIS_FRAME) == 0 {
344 e.flags |= RES_DEFINED_THIS_FRAME;
345 self.defined.push(old);
346 }
347 if (old_flags & RES_CHILDREN_HELD) != 0 {
348 for idx in 0..self.old_children_scratch.len() {
349 let cid = self.old_children_scratch[idx];
350 self.release(cid);
351 }
352 }
353 return Some(old);
354 }
355 }
356
357 let rid = self.slot()?;
359 for idx in 0..self.child_scratch.len() {
360 let cid = self.child_scratch[idx];
361 self.retain(cid);
362 }
363 let span = self.words.replace(Span::EMPTY, &self.scratch);
364 let child_span = self.children.replace(Span::EMPTY, &self.child_scratch);
365 self.entries[rid.index()] = Entry {
366 kind: R::KIND,
367 validated_type: OnceLock::from(tid),
368 span,
369 children: child_span,
370 refs: 1,
371 hash: 0,
372 generation: rid.generation(),
373 flags: RES_OCCUPIED
374 | RES_EPHEMERAL
375 | RES_CHILDREN_HELD
376 | RES_DEFINED_THIS_FRAME
377 | RES_CREATED_THIS_FRAME,
378 };
379 self.defined.push(rid);
380 Some(rid)
381 }
382
383 pub fn try_intern_words<R: FlatResource>(&mut self, words: &[u32]) -> Option<ResourceId> {
386 self.scratch.clear();
387 self.scratch.extend_from_slice(words);
388 self.finish_intern_scratch::<R>()
389 }
390
391 pub fn try_intern_with<R: FlatResource>(
394 &mut self,
395 write: impl FnOnce(&mut Vec<u32>) -> bool,
396 ) -> Option<ResourceId> {
397 self.scratch.clear();
398 if !write(&mut self.scratch) {
399 return None;
400 }
401 self.finish_intern_scratch::<R>()
402 }
403
404 pub fn try_intern<R: FlatResource>(&mut self, value: &R) -> Option<ResourceId> {
407 self.try_intern_with::<R>(|out| value.write_words(out))
408 }
409
410 #[inline]
412 pub fn intern<R: FlatResource>(&mut self, value: &R) -> ResourceId {
413 self.try_intern(value).unwrap_or(ResourceId::NONE)
414 }
415
416 pub fn try_set_ephemeral_with<R: FlatResource>(
419 &mut self,
420 old: ResourceId,
421 write: impl FnOnce(&mut Vec<u32>) -> bool,
422 ) -> Option<ResourceId> {
423 self.scratch.clear();
424 if !write(&mut self.scratch) {
425 return None;
426 }
427 self.finish_ephemeral_scratch::<R>(old)
428 }
429
430 pub fn try_set_ephemeral<R: FlatResource>(
433 &mut self,
434 old: ResourceId,
435 value: &R,
436 ) -> Option<ResourceId> {
437 self.try_set_ephemeral_with::<R>(old, |out| value.write_words(out))
438 }
439
440 #[inline]
442 pub fn set_ephemeral<R: FlatResource>(&mut self, old: ResourceId, value: &R) -> ResourceId {
443 self.try_set_ephemeral(old, value).unwrap_or(ResourceId::NONE)
444 }
445
446 pub fn retain(&mut self, id: ResourceId) {
449 let Some(e) = self.entry_mut(id) else {
450 return;
451 };
452 if e.refs > 0 {
453 debug_assert!(e.refs < u32::MAX, "ResourceStore: refcount saturated");
454 e.refs = e.refs.saturating_add(1);
455 return;
456 }
457 self.work_stack.clear();
459 self.work_stack.push(id);
460 while let Some(cur) = self.work_stack.pop() {
461 let Some(entry) = self.entry_mut(cur) else {
462 continue;
463 };
464 let was_zero = entry.refs == 0;
465 debug_assert!(entry.refs < u32::MAX, "ResourceStore: refcount saturated");
466 entry.refs = entry.refs.saturating_add(1);
467 if was_zero && (entry.flags & RES_CHILDREN_HELD) == 0 {
468 entry.flags |= RES_CHILDREN_HELD;
469 let kids = entry.children;
470 if !kids.is_empty() {
471 self.work_stack.extend_from_slice(self.children.get(kids));
472 }
473 }
474 }
475 }
476
477 pub fn release(&mut self, id: ResourceId) {
480 if id.is_none() {
481 return;
482 }
483 self.work_stack.clear();
484 self.work_stack.push(id);
485 while let Some(cur) = self.work_stack.pop() {
486 let idx = cur.index();
487 if idx == 0 {
488 continue;
489 }
490 let Some(e) = self.entries.get_mut(idx) else {
491 continue;
492 };
493 if (e.flags & RES_OCCUPIED) == 0 || e.generation != cur.generation() {
494 continue;
495 }
496 debug_assert!(e.refs > 0, "resource {cur:?} over-released");
497 if e.refs == 0 || e.refs == u32::MAX {
498 continue;
499 }
500 e.refs -= 1;
501 if e.refs == 0 {
502 if (e.flags & RES_EPHEMERAL) == 0
503 && self.dedup.get(&(e.kind.0, e.hash)).copied() == Some(cur)
504 {
505 self.dedup.remove(&(e.kind.0, e.hash));
506 }
507 if (e.flags & RES_PENDING_FREE) == 0 {
508 e.flags |= RES_PENDING_FREE;
509 self.pending_free.push(cur.index() as u32);
510 }
511 if (e.flags & RES_CREATED_THIS_FRAME) == 0
512 && (e.flags & RES_RELEASED_THIS_FRAME) == 0
513 {
514 e.flags |= RES_RELEASED_THIS_FRAME;
515 self.released.push(cur);
516 }
517 if (e.flags & RES_CHILDREN_HELD) != 0 {
518 e.flags &= !RES_CHILDREN_HELD;
519 let kids = e.children;
520 if !kids.is_empty() {
521 self.work_stack.extend_from_slice(self.children.get(kids));
522 }
523 }
524 }
525 }
526 }
527
528 #[inline]
534 pub fn get<R: FlatResource>(&self, id: ResourceId) -> Option<R::View<'_>> {
535 let e = self.entry(id)?;
536 if e.kind != R::KIND {
537 return None;
538 }
539 let words = self.words.get(e.span);
540 let tid = TypeId::of::<R>();
541 if let Some(&cached) = e.validated_type.get() {
542 if cached != tid {
543 return None;
544 }
545 } else {
546 if !self.validate_wire_entry::<R>(e, words) {
547 return None;
548 }
549 if *e.validated_type.get_or_init(|| tid) != tid {
550 return None;
551 }
552 }
553 Some(R::view(ValidatedWords::new_unchecked(words)))
554 }
555
556 #[cold]
557 fn validate_wire_entry<R: FlatResource>(&self, e: &Entry, words: &[u32]) -> bool {
558 if !R::validate(words) {
559 return false;
560 }
561 let tracked = self.children.get(e.children);
562 let mut ok = true;
563 R::child_resources(words, &mut |cid| {
564 if !cid.is_none() && (tracked.binary_search(&cid).is_err() || !self.is_defined(cid)) {
565 ok = false;
566 }
567 });
568 ok
569 }
570
571 #[inline]
573 pub fn raw_words(&self, id: ResourceId) -> Option<&[u32]> {
574 let e = self.entry(id)?;
575 Some(self.words.get(e.span))
576 }
577
578 #[inline]
583 pub fn payload_bytes(&self, id: ResourceId) -> Option<&[u8]> {
584 let e = self.entry(id)?;
585 (e.refs > 0).then(|| words_as_le_bytes(self.words.get(e.span)))
586 }
587
588 #[inline]
590 pub fn children_of(&self, id: ResourceId) -> &[ResourceId] {
591 match self.entry(id) {
592 Some(e) => self.children.get(e.children),
593 None => &[],
594 }
595 }
596
597 pub fn kind(&self, id: ResourceId) -> Option<Key64> {
598 self.entry(id).map(|e| e.kind)
599 }
600
601 #[inline]
602 pub fn is_live(&self, id: ResourceId) -> bool {
603 self.entry(id).is_some_and(|e| e.refs > 0)
604 }
605
606 #[inline]
609 pub fn is_live_of<R: FlatResource>(&self, id: ResourceId) -> bool {
610 self.entry(id).is_some_and(|e| {
611 e.refs > 0
612 && e.kind == R::KIND
613 && e.validated_type.get().is_none_or(|&t| t == TypeId::of::<R>())
614 })
615 }
616
617 #[inline]
619 pub fn is_live_with_kind(&self, id: ResourceId, kind: Key64) -> bool {
620 self.entry(id)
621 .is_some_and(|e| e.refs > 0 && e.kind == kind)
622 }
623
624 pub fn live(&self) -> usize {
626 self.entries
627 .iter()
628 .filter(|e| (e.flags & RES_OCCUPIED) != 0 && e.refs > 0)
629 .count()
630 }
631}