Skip to main content

vibescript_abi/
memory.rs

1//! Zero-heap memory layout types: `NQuin48`, typed `BorrowedSliceView`,
2//! caller-buffered `CallerOutputSlice`, and generational `ResourceHandle`.
3
4use crate::lifecycle::VibeTrap;
5
6/// Canonical 48-byte, 16-byte aligned Super-Quin representation (`[u64; 6]`).
7///
8/// Layout matches `qualia_core_db::NQuin` bit-for-bit:
9/// `[subject, predicate, object, context, metadata, parity]`, where
10/// `parity == subject ^ predicate ^ object ^ context ^ metadata`.
11#[repr(C, align(16))]
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub struct NQuin48(pub [u64; 6]);
14
15const _: () = {
16    assert!(core::mem::size_of::<NQuin48>() == 48);
17    assert!(core::mem::align_of::<NQuin48>() == 16);
18};
19
20impl NQuin48 {
21    /// Constructs a parity-sealed `NQuin48` from its five semantic fields.
22    #[inline]
23    pub const fn from_parts(
24        subject: u64,
25        predicate: u64,
26        object: u64,
27        context: u64,
28        metadata: u64,
29    ) -> Self {
30        let parity = subject ^ predicate ^ object ^ context ^ metadata;
31        Self([subject, predicate, object, context, metadata, parity])
32    }
33
34    /// Subject field (`[0]`).
35    #[inline]
36    pub const fn subject(&self) -> u64 {
37        self.0[0]
38    }
39
40    /// Predicate field (`[1]`).
41    #[inline]
42    pub const fn predicate(&self) -> u64 {
43        self.0[1]
44    }
45
46    /// Object field (`[2]`).
47    #[inline]
48    pub const fn object(&self) -> u64 {
49        self.0[2]
50    }
51
52    /// Context field (`[3]`).
53    #[inline]
54    pub const fn context(&self) -> u64 {
55        self.0[3]
56    }
57
58    /// Metadata field (`[4]`).
59    #[inline]
60    pub const fn metadata(&self) -> u64 {
61        self.0[4]
62    }
63
64    /// Parity field (`[5]`).
65    #[inline]
66    pub const fn parity(&self) -> u64 {
67        self.0[5]
68    }
69
70    /// Expected XOR parity (`subject ^ predicate ^ object ^ context ^ metadata`).
71    #[inline]
72    pub const fn computed_parity(&self) -> u64 {
73        self.0[0] ^ self.0[1] ^ self.0[2] ^ self.0[3] ^ self.0[4]
74    }
75
76    /// Returns `true` when `parity == subject ^ predicate ^ object ^ context ^ metadata`.
77    #[inline]
78    pub const fn verify_parity(&self) -> bool {
79        self.0[5] == self.computed_parity()
80    }
81}
82
83/// Element type tag for safe borrowed slice views and caller-owned output buffers.
84#[repr(u8)]
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86pub enum PrimitiveKind {
87    U8 = 1,
88    I32 = 2,
89    U32 = 3,
90    I64 = 4,
91    U64 = 5,
92    F32 = 6,
93    F64 = 7,
94    Bool = 8,
95    NQuin48 = 9,
96    ResourceHandle = 10,
97    Utf8Bytes = 11,
98}
99
100impl PrimitiveKind {
101    /// Exact byte size of a single element of this kind.
102    #[inline]
103    pub const fn elem_size(self) -> usize {
104        match self {
105            Self::U8 | Self::Bool | Self::Utf8Bytes => 1,
106            Self::I32 | Self::U32 | Self::F32 => 4,
107            Self::I64 | Self::U64 | Self::F64 => 8,
108            Self::ResourceHandle => 24,
109            Self::NQuin48 => 48,
110        }
111    }
112
113    /// Required byte alignment when casting directly to a typed Rust slice.
114    #[inline]
115    pub const fn elem_align(self) -> usize {
116        match self {
117            Self::U8 | Self::Bool | Self::Utf8Bytes => 1,
118            Self::I32 | Self::U32 | Self::F32 => 4,
119            Self::I64 | Self::U64 | Self::F64 | Self::ResourceHandle => 8,
120            Self::NQuin48 => 16,
121        }
122    }
123}
124
125/// Generational, provider-scoped opaque handle to a host or domain resource.
126///
127/// Prevents raw pointer forging, cross-provider handle reuse, and use-after-close
128/// stale slot bugs.
129#[repr(C)]
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
131pub struct ResourceHandle {
132    /// `q_hash` of the owning provider's canonical IRI.
133    pub owner_provider_hash: u64,
134    /// Domain-defined resource kind tag.
135    pub kind: u16,
136    /// Access flags (e.g. read-only vs mutable).
137    pub flags: u16,
138    /// Slot generation counter; must match the table's live slot generation.
139    pub generation: u32,
140    /// Arena/table slot index.
141    pub slot: u32,
142    /// Reserved field (must be 0).
143    pub reserved: u32,
144}
145
146const _: () = {
147    assert!(core::mem::size_of::<ResourceHandle>() == 24);
148    assert!(core::mem::align_of::<ResourceHandle>() == 8);
149};
150
151impl ResourceHandle {
152    /// Creates a new `ResourceHandle`.
153    #[inline]
154    pub const fn new(
155        owner_provider_hash: u64,
156        kind: u16,
157        flags: u16,
158        generation: u32,
159        slot: u32,
160    ) -> Self {
161        Self {
162            owner_provider_hash,
163            kind,
164            flags,
165            generation,
166            slot,
167            reserved: 0,
168        }
169    }
170
171    /// Validates that this handle belongs to `expected_owner`, has `expected_kind`,
172    /// and matches `expected_generation`.
173    #[inline]
174    pub const fn validate(
175        &self,
176        expected_owner: u64,
177        expected_kind: u16,
178        expected_generation: u32,
179    ) -> Result<(), VibeTrap> {
180        if self.owner_provider_hash != expected_owner || self.kind != expected_kind {
181            return Err(VibeTrap::InvalidResourceHandleOwner);
182        }
183        if self.generation == 0 || self.generation != expected_generation {
184            return Err(VibeTrap::StaleResourceHandleGeneration);
185        }
186        Ok(())
187    }
188}
189
190/// Checked immutable view over a caller-supplied input buffer.
191#[derive(Debug, Clone, Copy)]
192pub struct BorrowedSliceView<'a> {
193    bytes: &'a [u8],
194    kind: PrimitiveKind,
195    elem_count: usize,
196}
197
198impl<'a> BorrowedSliceView<'a> {
199    /// Constructs a validated `BorrowedSliceView` from raw bytes and an element count.
200    ///
201    /// When `kind == PrimitiveKind::NQuin48`, verifies the 5-word XOR parity on every record.
202    #[inline]
203    pub fn from_raw_bytes(
204        bytes: &'a [u8],
205        kind: PrimitiveKind,
206        elem_count: usize,
207    ) -> Result<Self, VibeTrap> {
208        let expected_bytes = elem_count
209            .checked_mul(kind.elem_size())
210            .ok_or(VibeTrap::SliceBoundsOverflow)?;
211        if bytes.len() != expected_bytes {
212            return Err(VibeTrap::SliceLengthMismatch);
213        }
214        if kind == PrimitiveKind::NQuin48 {
215            let mut idx = 0;
216            while idx < elem_count {
217                let off = idx * 48;
218                let mut words = [0u64; 6];
219                let mut w = 0;
220                while w < 6 {
221                    let w_off = off + w * 8;
222                    words[w] = u64::from_le_bytes([
223                        bytes[w_off],
224                        bytes[w_off + 1],
225                        bytes[w_off + 2],
226                        bytes[w_off + 3],
227                        bytes[w_off + 4],
228                        bytes[w_off + 5],
229                        bytes[w_off + 6],
230                        bytes[w_off + 7],
231                    ]);
232                    w += 1;
233                }
234                if !NQuin48(words).verify_parity() {
235                    return Err(VibeTrap::InvalidQuinParity);
236                }
237                idx += 1;
238            }
239        }
240        Ok(Self {
241            bytes,
242            kind,
243            elem_count,
244        })
245    }
246
247    /// Constructs a validated `BorrowedSliceView` requiring pointer alignment `kind.elem_align()`.
248    #[inline]
249    pub fn from_aligned_bytes(
250        bytes: &'a [u8],
251        kind: PrimitiveKind,
252        elem_count: usize,
253    ) -> Result<Self, VibeTrap> {
254        let align = kind.elem_align();
255        if !bytes.is_empty() && (bytes.as_ptr() as usize) % align != 0 {
256            return Err(VibeTrap::SliceBoundsOverflow);
257        }
258        Self::from_raw_bytes(bytes, kind, elem_count)
259    }
260
261    /// Constructs a `BorrowedSliceView` from a slice of parity-verified `NQuin48` records.
262    #[inline]
263    pub fn from_nquins(quins: &'a [NQuin48]) -> Result<Self, VibeTrap> {
264        let mut i = 0;
265        while i < quins.len() {
266            if !quins[i].verify_parity() {
267                return Err(VibeTrap::InvalidQuinParity);
268            }
269            i += 1;
270        }
271        let byte_len = quins
272            .len()
273            .checked_mul(core::mem::size_of::<NQuin48>())
274            .ok_or(VibeTrap::SliceBoundsOverflow)?;
275        // SAFETY: `NQuin48` is `#[repr(C, align(16))]` of `[u64; 6]` with no padding bytes.
276        let bytes = unsafe { core::slice::from_raw_parts(quins.as_ptr() as *const u8, byte_len) };
277        Ok(Self {
278            bytes,
279            kind: PrimitiveKind::NQuin48,
280            elem_count: quins.len(),
281        })
282    }
283
284    /// Element kind.
285    #[inline]
286    pub const fn kind(&self) -> PrimitiveKind {
287        self.kind
288    }
289
290    /// Alias for `kind()`.
291    #[inline]
292    pub const fn primitive(&self) -> PrimitiveKind {
293        self.kind
294    }
295
296    /// Number of typed elements.
297    #[inline]
298    pub const fn elem_count(&self) -> usize {
299        self.elem_count
300    }
301
302    /// Alias for `elem_count()`.
303    #[inline]
304    pub const fn len(&self) -> usize {
305        self.elem_count
306    }
307
308    /// Returns `true` when `elem_count == 0`.
309    #[inline]
310    pub const fn is_empty(&self) -> bool {
311        self.elem_count == 0
312    }
313
314    /// Underlying byte slice.
315    #[inline]
316    pub const fn as_bytes(&self) -> &'a [u8] {
317        self.bytes
318    }
319
320    /// Reads the `index`-th `f64` (little-endian) without requiring 8-byte pointer alignment.
321    #[inline]
322    pub fn read_f64_le(&self, index: usize) -> Result<f64, VibeTrap> {
323        if self.kind != PrimitiveKind::F64 {
324            return Err(VibeTrap::TypeMismatch);
325        }
326        if index >= self.elem_count {
327            return Err(VibeTrap::SliceBoundsOverflow);
328        }
329        let offset = index * 8;
330        let mut buf = [0u8; 8];
331        buf.copy_from_slice(&self.bytes[offset..offset + 8]);
332        Ok(f64::from_le_bytes(buf))
333    }
334
335    /// Reads the `index`-th `f32` (little-endian).
336    #[inline]
337    pub fn read_f32_le(&self, index: usize) -> Result<f32, VibeTrap> {
338        if self.kind != PrimitiveKind::F32 {
339            return Err(VibeTrap::TypeMismatch);
340        }
341        if index >= self.elem_count {
342            return Err(VibeTrap::SliceBoundsOverflow);
343        }
344        let offset = index * 4;
345        let mut buf = [0u8; 4];
346        buf.copy_from_slice(&self.bytes[offset..offset + 4]);
347        Ok(f32::from_le_bytes(buf))
348    }
349
350    /// Reads the `index`-th `u64` (little-endian).
351    #[inline]
352    pub fn read_u64_le(&self, index: usize) -> Result<u64, VibeTrap> {
353        if self.kind != PrimitiveKind::U64 {
354            return Err(VibeTrap::TypeMismatch);
355        }
356        if index >= self.elem_count {
357            return Err(VibeTrap::SliceBoundsOverflow);
358        }
359        let offset = index * 8;
360        let mut buf = [0u8; 8];
361        buf.copy_from_slice(&self.bytes[offset..offset + 8]);
362        Ok(u64::from_le_bytes(buf))
363    }
364
365    /// Reads the `index`-th `i64` (little-endian).
366    #[inline]
367    pub fn read_i64_le(&self, index: usize) -> Result<i64, VibeTrap> {
368        if self.kind != PrimitiveKind::I64 {
369            return Err(VibeTrap::TypeMismatch);
370        }
371        if index >= self.elem_count {
372            return Err(VibeTrap::SliceBoundsOverflow);
373        }
374        let offset = index * 8;
375        let mut buf = [0u8; 8];
376        buf.copy_from_slice(&self.bytes[offset..offset + 8]);
377        Ok(i64::from_le_bytes(buf))
378    }
379
380    /// Reads the `index`-th `u32` (little-endian).
381    #[inline]
382    pub fn read_u32_le(&self, index: usize) -> Result<u32, VibeTrap> {
383        if self.kind != PrimitiveKind::U32 {
384            return Err(VibeTrap::TypeMismatch);
385        }
386        if index >= self.elem_count {
387            return Err(VibeTrap::SliceBoundsOverflow);
388        }
389        let offset = index * 4;
390        let mut buf = [0u8; 4];
391        buf.copy_from_slice(&self.bytes[offset..offset + 4]);
392        Ok(u32::from_le_bytes(buf))
393    }
394
395    /// Reads the `index`-th `i32` (little-endian).
396    #[inline]
397    pub fn read_i32_le(&self, index: usize) -> Result<i32, VibeTrap> {
398        if self.kind != PrimitiveKind::I32 {
399            return Err(VibeTrap::TypeMismatch);
400        }
401        if index >= self.elem_count {
402            return Err(VibeTrap::SliceBoundsOverflow);
403        }
404        let offset = index * 4;
405        let mut buf = [0u8; 4];
406        buf.copy_from_slice(&self.bytes[offset..offset + 4]);
407        Ok(i32::from_le_bytes(buf))
408    }
409
410    /// Reads the `index`-th `u8`.
411    #[inline]
412    pub fn read_u8(&self, index: usize) -> Result<u8, VibeTrap> {
413        if self.kind != PrimitiveKind::U8 {
414            return Err(VibeTrap::TypeMismatch);
415        }
416        if index >= self.elem_count {
417            return Err(VibeTrap::SliceBoundsOverflow);
418        }
419        Ok(self.bytes[index])
420    }
421
422    /// Reads the `index`-th `bool`.
423    #[inline]
424    pub fn read_bool(&self, index: usize) -> Result<bool, VibeTrap> {
425        if self.kind != PrimitiveKind::Bool {
426            return Err(VibeTrap::TypeMismatch);
427        }
428        if index >= self.elem_count {
429            return Err(VibeTrap::SliceBoundsOverflow);
430        }
431        Ok(self.bytes[index] != 0)
432    }
433
434    /// Reads the `index`-th parity-verified `NQuin48` (little-endian).
435    #[inline]
436    pub fn read_nquin(&self, index: usize) -> Result<NQuin48, VibeTrap> {
437        if self.kind != PrimitiveKind::NQuin48 {
438            return Err(VibeTrap::TypeMismatch);
439        }
440        if index >= self.elem_count {
441            return Err(VibeTrap::SliceBoundsOverflow);
442        }
443        let offset = index * 48;
444        let mut words = [0u64; 6];
445        let mut w = 0;
446        while w < 6 {
447            let w_off = offset + w * 8;
448            words[w] = u64::from_le_bytes([
449                self.bytes[w_off],
450                self.bytes[w_off + 1],
451                self.bytes[w_off + 2],
452                self.bytes[w_off + 3],
453                self.bytes[w_off + 4],
454                self.bytes[w_off + 5],
455                self.bytes[w_off + 6],
456                self.bytes[w_off + 7],
457            ]);
458            w += 1;
459        }
460        let quin = NQuin48(words);
461        if !quin.verify_parity() {
462            return Err(VibeTrap::InvalidQuinParity);
463        }
464        Ok(quin)
465    }
466
467    /// Reads the `index`-th `ResourceHandle` (little-endian 24-byte `#[repr(C)]` layout).
468    #[inline]
469    pub fn read_resource_handle(&self, index: usize) -> Result<ResourceHandle, VibeTrap> {
470        if self.kind != PrimitiveKind::ResourceHandle {
471            return Err(VibeTrap::TypeMismatch);
472        }
473        if index >= self.elem_count {
474            return Err(VibeTrap::SliceBoundsOverflow);
475        }
476        let offset = index * 24;
477        let owner_provider_hash = u64::from_le_bytes([
478            self.bytes[offset],
479            self.bytes[offset + 1],
480            self.bytes[offset + 2],
481            self.bytes[offset + 3],
482            self.bytes[offset + 4],
483            self.bytes[offset + 5],
484            self.bytes[offset + 6],
485            self.bytes[offset + 7],
486        ]);
487        let kind = u16::from_le_bytes([self.bytes[offset + 8], self.bytes[offset + 9]]);
488        let flags = u16::from_le_bytes([self.bytes[offset + 10], self.bytes[offset + 11]]);
489        let generation = u32::from_le_bytes([
490            self.bytes[offset + 12],
491            self.bytes[offset + 13],
492            self.bytes[offset + 14],
493            self.bytes[offset + 15],
494        ]);
495        let slot = u32::from_le_bytes([
496            self.bytes[offset + 16],
497            self.bytes[offset + 17],
498            self.bytes[offset + 18],
499            self.bytes[offset + 19],
500        ]);
501        let reserved = u32::from_le_bytes([
502            self.bytes[offset + 20],
503            self.bytes[offset + 21],
504            self.bytes[offset + 22],
505            self.bytes[offset + 23],
506        ]);
507        Ok(ResourceHandle {
508            owner_provider_hash,
509            kind,
510            flags,
511            generation,
512            slot,
513            reserved,
514        })
515    }
516
517    /// Returns the raw byte slice backing a `PrimitiveKind::Utf8Bytes` view after validating UTF-8.
518    #[inline]
519    pub fn read_utf8_bytes(&self) -> Result<&'a [u8], VibeTrap> {
520        if self.kind != PrimitiveKind::Utf8Bytes {
521            return Err(VibeTrap::TypeMismatch);
522        }
523        if core::str::from_utf8(self.bytes).is_err() {
524            return Err(VibeTrap::TypeMismatch);
525        }
526        Ok(self.bytes)
527    }
528
529    /// Returns the UTF-8 string slice backing a `PrimitiveKind::Utf8Bytes` view.
530    #[inline]
531    pub fn read_utf8_str(&self) -> Result<&'a str, VibeTrap> {
532        if self.kind != PrimitiveKind::Utf8Bytes {
533            return Err(VibeTrap::TypeMismatch);
534        }
535        core::str::from_utf8(self.bytes).map_err(|_| VibeTrap::TypeMismatch)
536    }
537}
538
539/// Caller-supplied mutable output buffer with pre-dispatch capacity checks and explicit written count.
540#[derive(Debug)]
541pub struct CallerOutputSlice<'a> {
542    bytes: &'a mut [u8],
543    kind: PrimitiveKind,
544    capacity_elems: usize,
545    written_elems: usize,
546}
547
548impl<'a> CallerOutputSlice<'a> {
549    /// Wraps a caller-owned mutable byte buffer for elements of `kind`.
550    #[inline]
551    pub fn new(bytes: &'a mut [u8], kind: PrimitiveKind) -> Result<Self, VibeTrap> {
552        let elem_size = kind.elem_size();
553        if bytes.len() % elem_size != 0 {
554            return Err(VibeTrap::SliceLengthMismatch);
555        }
556        let capacity_elems = bytes.len() / elem_size;
557        Ok(Self {
558            bytes,
559            kind,
560            capacity_elems,
561            written_elems: 0,
562        })
563    }
564
565    /// Expected element kind.
566    #[inline]
567    pub const fn kind(&self) -> PrimitiveKind {
568        self.kind
569    }
570
571    /// Alias for `kind()`.
572    #[inline]
573    pub const fn primitive(&self) -> PrimitiveKind {
574        self.kind
575    }
576
577    /// Total capacity in elements.
578    #[inline]
579    pub const fn capacity_elems(&self) -> usize {
580        self.capacity_elems
581    }
582
583    /// Total capacity in bytes.
584    #[inline]
585    pub const fn capacity_bytes(&self) -> usize {
586        self.bytes.len()
587    }
588
589    /// Number of elements written so far.
590    #[inline]
591    pub const fn written_elems(&self) -> usize {
592        self.written_elems
593    }
594
595    /// Number of bytes written so far.
596    #[inline]
597    pub const fn written_bytes(&self) -> usize {
598        self.written_elems * self.kind.elem_size()
599    }
600
601    /// Verifies that the output buffer can hold at least `required_elems` before execution begins.
602    #[inline]
603    pub const fn ensure_elem_capacity(&self, required_elems: usize) -> Result<(), VibeTrap> {
604        if required_elems > self.capacity_elems {
605            return Err(VibeTrap::OutputBufferTooSmall);
606        }
607        Ok(())
608    }
609
610    /// Appends one `f64` (little-endian) into the output buffer.
611    #[inline]
612    pub fn push_f64_le(&mut self, value: f64) -> Result<(), VibeTrap> {
613        if self.kind != PrimitiveKind::F64 {
614            return Err(VibeTrap::TypeMismatch);
615        }
616        if self.written_elems >= self.capacity_elems {
617            return Err(VibeTrap::OutputBufferTooSmall);
618        }
619        let offset = self.written_elems * 8;
620        self.bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
621        self.written_elems += 1;
622        Ok(())
623    }
624
625    /// Appends one `f32` (little-endian) into the output buffer.
626    #[inline]
627    pub fn push_f32_le(&mut self, value: f32) -> Result<(), VibeTrap> {
628        if self.kind != PrimitiveKind::F32 {
629            return Err(VibeTrap::TypeMismatch);
630        }
631        if self.written_elems >= self.capacity_elems {
632            return Err(VibeTrap::OutputBufferTooSmall);
633        }
634        let offset = self.written_elems * 4;
635        self.bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
636        self.written_elems += 1;
637        Ok(())
638    }
639
640    /// Appends one `u64` (little-endian) into the output buffer.
641    #[inline]
642    pub fn push_u64_le(&mut self, value: u64) -> Result<(), VibeTrap> {
643        if self.kind != PrimitiveKind::U64 {
644            return Err(VibeTrap::TypeMismatch);
645        }
646        if self.written_elems >= self.capacity_elems {
647            return Err(VibeTrap::OutputBufferTooSmall);
648        }
649        let offset = self.written_elems * 8;
650        self.bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
651        self.written_elems += 1;
652        Ok(())
653    }
654
655    /// Appends one `i64` (little-endian) into the output buffer.
656    #[inline]
657    pub fn push_i64_le(&mut self, value: i64) -> Result<(), VibeTrap> {
658        if self.kind != PrimitiveKind::I64 {
659            return Err(VibeTrap::TypeMismatch);
660        }
661        if self.written_elems >= self.capacity_elems {
662            return Err(VibeTrap::OutputBufferTooSmall);
663        }
664        let offset = self.written_elems * 8;
665        self.bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
666        self.written_elems += 1;
667        Ok(())
668    }
669
670    /// Appends one `u32` (little-endian) into the output buffer.
671    #[inline]
672    pub fn push_u32_le(&mut self, value: u32) -> Result<(), VibeTrap> {
673        if self.kind != PrimitiveKind::U32 {
674            return Err(VibeTrap::TypeMismatch);
675        }
676        if self.written_elems >= self.capacity_elems {
677            return Err(VibeTrap::OutputBufferTooSmall);
678        }
679        let offset = self.written_elems * 4;
680        self.bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
681        self.written_elems += 1;
682        Ok(())
683    }
684
685    /// Appends one `i32` (little-endian) into the output buffer.
686    #[inline]
687    pub fn push_i32_le(&mut self, value: i32) -> Result<(), VibeTrap> {
688        if self.kind != PrimitiveKind::I32 {
689            return Err(VibeTrap::TypeMismatch);
690        }
691        if self.written_elems >= self.capacity_elems {
692            return Err(VibeTrap::OutputBufferTooSmall);
693        }
694        let offset = self.written_elems * 4;
695        self.bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
696        self.written_elems += 1;
697        Ok(())
698    }
699
700    /// Appends one `u8` into the output buffer.
701    #[inline]
702    pub fn push_u8(&mut self, value: u8) -> Result<(), VibeTrap> {
703        if self.kind != PrimitiveKind::U8 {
704            return Err(VibeTrap::TypeMismatch);
705        }
706        if self.written_elems >= self.capacity_elems {
707            return Err(VibeTrap::OutputBufferTooSmall);
708        }
709        self.bytes[self.written_elems] = value;
710        self.written_elems += 1;
711        Ok(())
712    }
713
714    /// Appends one `bool` into the output buffer.
715    #[inline]
716    pub fn push_bool(&mut self, value: bool) -> Result<(), VibeTrap> {
717        if self.kind != PrimitiveKind::Bool {
718            return Err(VibeTrap::TypeMismatch);
719        }
720        if self.written_elems >= self.capacity_elems {
721            return Err(VibeTrap::OutputBufferTooSmall);
722        }
723        self.bytes[self.written_elems] = if value { 1 } else { 0 };
724        self.written_elems += 1;
725        Ok(())
726    }
727
728    /// Writes `elem_count` elements directly from `raw_bytes` into the output buffer.
729    #[inline]
730    pub fn write_all(&mut self, raw_bytes: &[u8], elem_count: usize) -> Result<(), VibeTrap> {
731        let expected_bytes = elem_count
732            .checked_mul(self.kind.elem_size())
733            .ok_or(VibeTrap::SliceBoundsOverflow)?;
734        if raw_bytes.len() != expected_bytes {
735            return Err(VibeTrap::SliceLengthMismatch);
736        }
737        if self.written_elems.saturating_add(elem_count) > self.capacity_elems {
738            return Err(VibeTrap::OutputBufferTooSmall);
739        }
740        let offset = self.written_bytes();
741        self.bytes[offset..offset + expected_bytes].copy_from_slice(raw_bytes);
742        self.written_elems += elem_count;
743        Ok(())
744    }
745
746    /// Appends one parity-verified `NQuin48` into the output buffer.
747    #[inline]
748    pub fn push_nquin(&mut self, quin: &NQuin48) -> Result<(), VibeTrap> {
749        if self.kind != PrimitiveKind::NQuin48 {
750            return Err(VibeTrap::TypeMismatch);
751        }
752        if !quin.verify_parity() {
753            return Err(VibeTrap::InvalidQuinParity);
754        }
755        if self.written_elems >= self.capacity_elems {
756            return Err(VibeTrap::OutputBufferTooSmall);
757        }
758        let offset = self.written_elems * 48;
759        let mut word = 0;
760        while word < 6 {
761            let w_off = offset + word * 8;
762            self.bytes[w_off..w_off + 8].copy_from_slice(&quin.0[word].to_le_bytes());
763            word += 1;
764        }
765        self.written_elems += 1;
766        Ok(())
767    }
768
769    /// Appends one `ResourceHandle` (little-endian 24-byte `#[repr(C)]` layout) into the output buffer.
770    #[inline]
771    pub fn push_resource_handle(&mut self, handle: &ResourceHandle) -> Result<(), VibeTrap> {
772        if self.kind != PrimitiveKind::ResourceHandle {
773            return Err(VibeTrap::TypeMismatch);
774        }
775        if self.written_elems >= self.capacity_elems {
776            return Err(VibeTrap::OutputBufferTooSmall);
777        }
778        let offset = self.written_elems * 24;
779        self.bytes[offset..offset + 8].copy_from_slice(&handle.owner_provider_hash.to_le_bytes());
780        self.bytes[offset + 8..offset + 10].copy_from_slice(&handle.kind.to_le_bytes());
781        self.bytes[offset + 10..offset + 12].copy_from_slice(&handle.flags.to_le_bytes());
782        self.bytes[offset + 12..offset + 16].copy_from_slice(&handle.generation.to_le_bytes());
783        self.bytes[offset + 16..offset + 20].copy_from_slice(&handle.slot.to_le_bytes());
784        self.bytes[offset + 20..offset + 24].copy_from_slice(&handle.reserved.to_le_bytes());
785        self.written_elems += 1;
786        Ok(())
787    }
788
789    /// Appends UTF-8 bytes into a `PrimitiveKind::Utf8Bytes` output buffer after validating UTF-8.
790    #[inline]
791    pub fn push_utf8_bytes(&mut self, bytes: &[u8]) -> Result<(), VibeTrap> {
792        if self.kind != PrimitiveKind::Utf8Bytes {
793            return Err(VibeTrap::TypeMismatch);
794        }
795        if core::str::from_utf8(bytes).is_err() {
796            return Err(VibeTrap::TypeMismatch);
797        }
798        if self.written_elems.saturating_add(bytes.len()) > self.capacity_elems {
799            return Err(VibeTrap::OutputBufferTooSmall);
800        }
801        let offset = self.written_bytes();
802        self.bytes[offset..offset + bytes.len()].copy_from_slice(bytes);
803        self.written_elems += bytes.len();
804        Ok(())
805    }
806
807    /// Appends a UTF-8 string slice into a `PrimitiveKind::Utf8Bytes` output buffer.
808    #[inline]
809    pub fn push_utf8_str(&mut self, s: &str) -> Result<(), VibeTrap> {
810        self.push_utf8_bytes(s.as_bytes())
811    }
812
813    /// Returns the written prefix of the output buffer as an immutable byte slice.
814    #[inline]
815    pub fn written_byte_slice(&self) -> &[u8] {
816        &self.bytes[..self.written_bytes()]
817    }
818}