1mod field;
5#[cfg(test)]
6mod packing_tests;
7#[cfg(test)]
8mod value_tests;
9#[cfg(test)]
10mod wire_tests;
11
12use std::sync::atomic::{AtomicU8, Ordering};
13use std::sync::{Arc, RwLock};
14
15use nativeview_abi::table::{table_flags, Storage, TableDesc, TableKey, Word, MAX_TABLE_SLOTS};
16
17use crate::row::{RowRef, RowWriter};
18
19pub use field::{Prop, Res, ResProp, ScalarField, Str, StrProp, TableField};
20
21pub const MAX_STATIC_TABLE_SLOTS: usize = 96;
25
26#[repr(transparent)]
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
29pub struct TableSlot(pub u8);
30
31impl TableSlot {
32 pub const NONE: Self = Self(nativeview_abi::NV_PRIMARY_SLOT_NONE);
34
35 #[inline(always)]
36 pub const fn is_none(self) -> bool {
37 self.0 == nativeview_abi::NV_PRIMARY_SLOT_NONE
38 }
39
40 #[inline(always)]
41 pub const fn bit(self) -> u128 {
42 if self.0 >= MAX_TABLE_SLOTS as u8 {
43 0
44 } else {
45 1u128 << self.0
46 }
47 }
48}
49
50pub unsafe trait NvTable: 'static {
62 const DESC: TableDesc;
63 type Ref<'a>: Copy;
65 type Mut<'a>;
67
68 #[doc(hidden)]
70 fn from_row_ref<'a>(row: RowRef<'a>) -> Self::Ref<'a>;
71
72 #[doc(hidden)]
74 fn from_row_writer<'a>(writer: RowWriter<'a>) -> Self::Mut<'a>;
75
76 fn slot() -> TableSlot;
78}
79
80pub trait TableValue: Default {
85 type Table: NvTable;
87
88 fn write(&self, tx: &mut crate::Transaction<'_>, node: crate::NodeId);
90}
91
92pub unsafe trait HasEvents: NvTable + Sized {
102 type Event: nativeview_abi::EventEnum;
103 const LISTENERS: Prop<Self, nativeview_abi::EventSet<Self::Event>>;
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
109pub(crate) struct OwnedTableDesc {
110 pub(crate) key: TableKey,
111 pub(crate) name: Box<str>,
112 pub(crate) schema_hash: u64,
113 pub(crate) storage: Storage,
114 pub(crate) flags: u16,
115 pub(crate) realization_priority: u8,
116 pub(crate) defaults: Box<[Word]>,
117 pub(crate) word_effects: Box<[u8]>,
118 pub(crate) str_words: u32,
119 pub(crate) resource_words: u32,
120}
121
122pub(crate) struct TableDescSpec<'a> {
124 pub(crate) schema_hash: u64,
125 pub(crate) storage: Storage,
126 pub(crate) flags: u16,
127 pub(crate) realization_priority: u8,
128 pub(crate) defaults: &'a [Word],
129 pub(crate) word_effects: &'a [u8],
130 pub(crate) str_words: u32,
131 pub(crate) resource_words: u32,
132 pub(crate) resource_kinds: Option<&'a [(u8, nativeview_abi::Key64)]>,
135}
136
137impl OwnedTableDesc {
138 #[inline(always)]
139 pub(crate) fn effects(&self) -> u8 {
140 self.word_effects.iter().fold(0, |a, &e| a | e)
141 }
142
143 pub(crate) fn matches_spec(&self, spec: &TableDescSpec<'_>) -> bool {
144 self.schema_hash == spec.schema_hash
145 && self.storage == spec.storage
146 && (self.flags & !table_flags::HOST_SLOT) == (spec.flags & !table_flags::HOST_SLOT)
147 && self.realization_priority == spec.realization_priority
148 && self.defaults.as_ref() == spec.defaults
149 && self.word_effects.as_ref() == spec.word_effects
150 && self.str_words == spec.str_words
151 && self.resource_words == spec.resource_words
152 }
153}
154
155#[derive(Debug, Clone)]
158pub(crate) enum TableMeta {
159 Static(&'static TableDesc),
160 Dynamic(Arc<OwnedTableDesc>),
161}
162
163impl TableMeta {
164 #[inline(always)]
165 pub(crate) fn key(&self) -> TableKey {
166 match self {
167 Self::Static(d) => d.key,
168 Self::Dynamic(d) => d.key,
169 }
170 }
171
172 #[inline(always)]
173 pub(crate) fn name(&self) -> &str {
174 match self {
175 Self::Static(d) => d.name,
176 Self::Dynamic(d) => &d.name,
177 }
178 }
179
180 #[inline(always)]
181 pub(crate) fn schema_hash(&self) -> u64 {
182 match self {
183 Self::Static(d) => d.schema_hash,
184 Self::Dynamic(d) => d.schema_hash,
185 }
186 }
187
188 #[inline(always)]
189 pub(crate) fn storage(&self) -> Storage {
190 match self {
191 Self::Static(d) => d.storage,
192 Self::Dynamic(d) => d.storage,
193 }
194 }
195
196 #[inline(always)]
197 pub(crate) fn flags(&self) -> u16 {
198 match self {
199 Self::Static(d) => d.flags,
200 Self::Dynamic(d) => d.flags,
201 }
202 }
203
204 #[inline(always)]
205 pub(crate) fn realization_priority(&self) -> u8 {
206 match self {
207 Self::Static(d) => d.realization_priority,
208 Self::Dynamic(d) => d.realization_priority,
209 }
210 }
211
212 #[inline(always)]
213 pub(crate) fn words(&self) -> usize {
214 self.defaults().len()
215 }
216
217 #[inline(always)]
218 pub(crate) fn defaults(&self) -> &[Word] {
219 match self {
220 Self::Static(d) => d.defaults,
221 Self::Dynamic(d) => &d.defaults,
222 }
223 }
224
225 #[inline(always)]
226 pub(crate) fn word_effects(&self) -> &[u8] {
227 match self {
228 Self::Static(d) => d.word_effects,
229 Self::Dynamic(d) => &d.word_effects,
230 }
231 }
232
233 #[inline(always)]
234 pub(crate) fn str_words(&self) -> u32 {
235 match self {
236 Self::Static(d) => d.str_words,
237 Self::Dynamic(d) => d.str_words,
238 }
239 }
240
241 #[inline(always)]
242 pub(crate) fn resource_words(&self) -> u32 {
243 match self {
244 Self::Static(d) => d.resource_words,
245 Self::Dynamic(d) => d.resource_words,
246 }
247 }
248
249 #[inline(always)]
250 pub(crate) fn resource_kind(&self, word: usize) -> Option<nativeview_abi::Key64> {
251 match self {
252 Self::Static(d) => d.resource_kind(word),
253 Self::Dynamic(_) => None,
254 }
255 }
256
257 #[inline(always)]
258 pub(crate) fn effects(&self) -> u8 {
259 match self {
260 Self::Static(d) => d.effects(),
261 Self::Dynamic(d) => d.effects(),
262 }
263 }
264
265 #[inline(always)]
266 pub(crate) fn inherited(&self) -> bool {
267 match self {
268 Self::Static(d) => d.inherited,
269 Self::Dynamic(d) => (d.flags & table_flags::INHERITED) != 0,
270 }
271 }
272
273 #[inline(always)]
274 pub(crate) fn events_word(&self) -> u8 {
275 match self {
276 Self::Static(d) => d.events_word,
277 Self::Dynamic(d) => {
278 if (d.flags & table_flags::HAS_EVENTS) != 0 {
279 0
280 } else {
281 nativeview_abi::table::NO_VAL_WORD
282 }
283 }
284 }
285 }
286
287 #[inline(always)]
288 pub(crate) fn as_static(&self) -> Option<&'static TableDesc> {
289 match self {
290 Self::Static(d) => Some(*d),
291 Self::Dynamic(_) => None,
292 }
293 }
294}
295
296static REGISTRY: RwLock<Vec<&'static TableDesc>> = RwLock::new(Vec::new());
301
302#[derive(Debug, Clone, PartialEq, Eq)]
304pub enum RegistryError {
305 Full,
307 SchemaMismatch { name: &'static str, key: TableKey },
309}
310
311fn resource_kinds_match(a: &[(u8, nativeview_abi::Key64)], b: &[(u8, nativeview_abi::Key64)]) -> bool {
312 if a.len() != b.len() {
313 return false;
314 }
315 if a == b {
316 return true;
317 }
318 a.iter().all(|entry| {
319 a.iter().filter(|x| *x == entry).count() == b.iter().filter(|x| *x == entry).count()
320 })
321}
322
323pub(crate) fn static_desc_matches(existing: &TableDesc, spec: &TableDescSpec<'_>) -> bool {
324 let resource_kinds_ok = spec
325 .resource_kinds
326 .is_none_or(|rk| resource_kinds_match(existing.resource_kinds, rk));
327 existing.schema_hash == spec.schema_hash
328 && existing.storage == spec.storage
329 && (existing.flags & !table_flags::HOST_SLOT) == (spec.flags & !table_flags::HOST_SLOT)
330 && existing.realization_priority == spec.realization_priority
331 && existing.defaults == spec.defaults
332 && existing.word_effects == spec.word_effects
333 && existing.str_words == spec.str_words
334 && existing.resource_words == spec.resource_words
335 && resource_kinds_ok
336}
337
338fn register_locked(desc: &'static TableDesc) -> Result<TableSlot, RegistryError> {
339 let has_events = (desc.flags & table_flags::HAS_EVENTS) != 0;
340 let events_word_ok = if has_events {
341 desc.events_word == 0
342 } else {
343 desc.events_word == nativeview_abi::table::NO_VAL_WORD
344 };
345 if desc.inherited != ((desc.flags & table_flags::INHERITED) != 0)
346 || !events_word_ok
347 || !validate_desc_invariants(
348 desc.words(),
349 desc.flags,
350 desc.str_words,
351 desc.resource_words,
352 desc.defaults,
353 desc.word_effects,
354 )
355 {
356 return Err(RegistryError::SchemaMismatch {
357 name: desc.name,
358 key: desc.key,
359 });
360 }
361 let mut reg = REGISTRY.write().unwrap_or_else(|e| e.into_inner());
362 if let Some(i) = reg.iter().position(|d| d.key == desc.key) {
363 let spec = TableDescSpec {
364 schema_hash: desc.schema_hash,
365 storage: desc.storage,
366 flags: desc.flags,
367 realization_priority: desc.realization_priority,
368 defaults: desc.defaults,
369 word_effects: desc.word_effects,
370 str_words: desc.str_words,
371 resource_words: desc.resource_words,
372 resource_kinds: Some(desc.resource_kinds),
373 };
374 if !static_desc_matches(reg[i], &spec) {
375 return Err(RegistryError::SchemaMismatch {
376 name: desc.name,
377 key: desc.key,
378 });
379 }
380 return Ok(TableSlot(i as u8));
381 }
382 if reg.len() >= MAX_STATIC_TABLE_SLOTS {
383 return Err(RegistryError::Full);
384 }
385 reg.push(desc);
386 Ok(TableSlot((reg.len() - 1) as u8))
387}
388
389#[doc(hidden)]
391#[cold]
392pub fn register_static(desc: &'static TableDesc, cell: &AtomicU8) -> TableSlot {
393 let slot = register_locked(desc)
394 .expect("NvTable static registration must succeed (unique key and <= 96 tables)");
395 cell.store(slot.0, Ordering::Release);
396 slot
397}
398
399pub(crate) fn validate_desc_invariants(
401 words: usize,
402 flags: u16,
403 str_words: u32,
404 resource_words: u32,
405 defaults: &[Word],
406 word_effects: &[u8],
407) -> bool {
408 if words == 0 || words > nativeview_abi::table::MAX_TABLE_WORDS {
409 return false;
410 }
411 if defaults.len() != words || word_effects.len() != words {
412 return false;
413 }
414 if (flags & table_flags::INHERITED) != 0 && (flags & table_flags::HAS_EVENTS) != 0 {
415 return false;
416 }
417 if (flags & table_flags::INHERITED) != 0
418 && (words < 2
419 || defaults[0] != 0
420 || word_effects[0] != 0
421 || ((str_words | resource_words) & 1) != 0)
422 {
423 return false;
424 }
425 if (flags & table_flags::HAS_EVENTS) != 0
426 && (defaults[0] != 0 || ((str_words | resource_words) & 1) != 0)
427 {
428 return false;
429 }
430 let valid_mask = if words == 32 { u32::MAX } else { (1u32 << words) - 1 };
431 if (str_words & !valid_mask) != 0 || (resource_words & !valid_mask) != 0 {
432 return false;
433 }
434 if (str_words & (1u32 << (words - 1))) != 0 {
436 return false;
437 }
438 if (str_words & (str_words << 1)) != 0 {
440 return false;
441 }
442 if ((str_words | (str_words << 1)) & resource_words) != 0 {
444 return false;
445 }
446 let mut sm = str_words;
448 while sm != 0 {
449 let w = sm.trailing_zeros() as usize;
450 sm &= sm - 1;
451 if defaults[w] != 0 || defaults[w + 1] != 0 {
452 return false;
453 }
454 }
455 let mut rm = resource_words;
456 while rm != 0 {
457 let w = rm.trailing_zeros() as usize;
458 rm &= rm - 1;
459 if defaults[w] != 0 {
460 return false;
461 }
462 }
463 true
464}
465
466pub(crate) fn lookup_static(key: TableKey) -> Option<(TableSlot, &'static TableDesc)> {
468 let reg = REGISTRY.read().unwrap_or_else(|e| e.into_inner());
469 reg.iter()
470 .position(|d| d.key == key)
471 .map(|i| (TableSlot(i as u8), reg[i]))
472}
473
474pub(crate) fn try_desc(slot: TableSlot) -> Option<&'static TableDesc> {
476 REGISTRY
477 .read()
478 .unwrap_or_else(|e| e.into_inner())
479 .get(slot.0 as usize)
480 .copied()
481}
482
483pub fn slot_of(key: TableKey) -> Option<TableSlot> {
485 let reg = REGISTRY.read().unwrap_or_else(|e| e.into_inner());
486 reg.iter()
487 .position(|d| d.key == key)
488 .map(|i| TableSlot(i as u8))
489}
490
491pub fn desc(slot: TableSlot) -> &'static TableDesc {
493 REGISTRY.read().unwrap_or_else(|e| e.into_inner())[slot.0 as usize]
494}
495
496pub(crate) fn hash_table_schema_pairs(pairs: impl IntoIterator<Item = (u64, u64)>) -> u64 {
500 let mut pairs: Vec<(u64, u64)> = pairs.into_iter().collect();
501 pairs.sort_unstable();
502 pairs.dedup();
503 let mut hasher = nativeview_abi::Xxh64Hasher::new(0x4E56_4554_424C_5331); for (key, hash) in pairs {
505 hasher.update(&key.to_le_bytes());
506 hasher.update(&hash.to_le_bytes());
507 }
508 hasher.digest()
509}
510
511pub fn tables_schema_hash(descs: &[&'static TableDesc]) -> u64 {
515 hash_table_schema_pairs(descs.iter().map(|d| (d.key.0, d.schema_hash)))
516}