Skip to main content

nativeview_codec/
transport.rs

1//! Framework- and runtime-agnostic binary byte transport (`ByteTransport`), error model
2//! (`TransportError`), and zero-waste stack-first request encoding helpers (`StackWriter`,
3//! `with_stack_writer`, `try_with_stack_writer`, and canonical float stack encoders).
4//!
5//! Lives in `nativeview-codec` (`#![forbid(unsafe_code)]`, zero runtime/engine/ABI dependencies) so
6//! capability modules, RPC clients, and host adapters can share one clean transport abstraction
7//! without coupling to `nativeview-abi` or `nativeview-host-services`.
8
9use core::fmt;
10use std::sync::Arc;
11
12use crate::{
13    canonical_f32_bits, canonical_f64_bits, ByteSink, ByteWriter, CodecError, SliceWriter,
14};
15
16/// Transport-layer error decoupled from any specific FFI status table or runtime crate.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum TransportError {
19    /// Service or method is not supported on the active transport or platform.
20    Unsupported,
21    /// Caller lacks permission for the requested capability or operation.
22    PermissionDenied,
23    /// Caller supplied invalid arguments or a malformed payload.
24    Invalid(String),
25    /// Requested resource, handle, or key was not found.
26    NotFound,
27    /// Operation was cancelled (user dismissal, surface teardown, or hot reload).
28    Cancelled,
29    /// Underlying I/O or link-layer failure.
30    Io(String),
31    /// Payload exceeded the configured or negotiated buffer capacity.
32    BufferOverflow { needed: usize, capacity: usize },
33    /// Binary codec serialization or deserialization failed.
34    Codec(CodecError),
35    /// Transport-specific non-zero status code (for raw foreign/C-ABI errors).
36    Status(i32),
37    /// Internal transport or peer failure.
38    Internal(String),
39}
40
41impl From<CodecError> for TransportError {
42    #[inline]
43    fn from(err: CodecError) -> Self {
44        Self::Codec(err)
45    }
46}
47
48impl From<std::io::Error> for TransportError {
49    #[inline]
50    fn from(err: std::io::Error) -> Self {
51        Self::Io(err.to_string())
52    }
53}
54
55impl fmt::Display for TransportError {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            Self::Unsupported => f.write_str("transport operation unsupported"),
59            Self::PermissionDenied => f.write_str("transport permission denied"),
60            Self::Invalid(msg) => write!(f, "invalid transport argument: {msg}"),
61            Self::NotFound => f.write_str("transport resource not found"),
62            Self::Cancelled => f.write_str("transport operation cancelled"),
63            Self::Io(msg) => write!(f, "transport I/O error: {msg}"),
64            Self::BufferOverflow { needed, capacity } => {
65                write!(
66                    f,
67                    "transport buffer overflow: needed {needed}B, capacity {capacity}B"
68                )
69            }
70            Self::Codec(err) => write!(f, "transport codec error: {err}"),
71            Self::Status(code) => write!(f, "transport status error ({code})"),
72            Self::Internal(msg) => write!(f, "internal transport error: {msg}"),
73        }
74    }
75}
76
77impl std::error::Error for TransportError {
78    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
79        match self {
80            Self::Codec(err) => Some(err),
81            _ => None,
82        }
83    }
84}
85
86/// Callback invoked once when an asynchronous [`ByteTransport::call_async`] completes.
87pub type TransportDoneFn = Box<dyn FnOnce(Result<&[u8], TransportError>) + Send>;
88
89/// Pluggable binary request/reply transport with zero-copy synchronous reply delivery and
90/// callback-driven asynchronous completion.
91///
92/// Implementations may bridge in-process registries, direct C-ABI callback sinks, IPC sockets,
93/// WebWorkers, or deterministic unit-test harnesses without coupling callers to any concrete host.
94pub trait ByteTransport: Send + Sync {
95    /// Synchronously invokes `(service_id, method_id)` with `req`, delivering reply bytes to
96    /// `on_reply` while the transport's stack or borrowed reply buffer is still live (enabling
97    /// zero-allocation reply decoding on the fast path).
98    fn call_sync(
99        &self,
100        service_id: u32,
101        method_id: u32,
102        req: &[u8],
103        on_reply: &mut dyn FnMut(&[u8]),
104    ) -> Result<(), TransportError>;
105
106    /// Initiates an asynchronous invocation of `(service_id, method_id)` with `req`, delivering
107    /// the borrowed reply slice or [`TransportError`] to `on_done` exactly once on completion.
108    fn call_async(
109        &self,
110        service_id: u32,
111        method_id: u32,
112        req: &[u8],
113        on_done: TransportDoneFn,
114    );
115
116    /// Initiates an asynchronous invocation and optionally returns a transport-scoped cancellation
117    /// handle that may later be passed to [`Self::cancel_async`].
118    fn call_async_cancellable(
119        &self,
120        service_id: u32,
121        method_id: u32,
122        req: &[u8],
123        on_done: TransportDoneFn,
124    ) -> Option<u64> {
125        self.call_async(service_id, method_id, req, on_done);
126        None
127    }
128
129    /// Best-effort cancellation of an in-flight asynchronous call started by
130    /// [`Self::call_async_cancellable`].
131    fn cancel_async(&self, _call_id: u64) {}
132}
133
134impl<T: ByteTransport + ?Sized> ByteTransport for &T {
135    #[inline]
136    fn call_sync(
137        &self,
138        service_id: u32,
139        method_id: u32,
140        req: &[u8],
141        on_reply: &mut dyn FnMut(&[u8]),
142    ) -> Result<(), TransportError> {
143        (**self).call_sync(service_id, method_id, req, on_reply)
144    }
145
146    #[inline]
147    fn call_async(&self, service_id: u32, method_id: u32, req: &[u8], on_done: TransportDoneFn) {
148        (**self).call_async(service_id, method_id, req, on_done);
149    }
150
151    #[inline]
152    fn call_async_cancellable(
153        &self,
154        service_id: u32,
155        method_id: u32,
156        req: &[u8],
157        on_done: TransportDoneFn,
158    ) -> Option<u64> {
159        (**self).call_async_cancellable(service_id, method_id, req, on_done)
160    }
161
162    #[inline]
163    fn cancel_async(&self, call_id: u64) {
164        (**self).cancel_async(call_id);
165    }
166}
167
168impl<T: ByteTransport + ?Sized> ByteTransport for Box<T> {
169    #[inline]
170    fn call_sync(
171        &self,
172        service_id: u32,
173        method_id: u32,
174        req: &[u8],
175        on_reply: &mut dyn FnMut(&[u8]),
176    ) -> Result<(), TransportError> {
177        (**self).call_sync(service_id, method_id, req, on_reply)
178    }
179
180    #[inline]
181    fn call_async(&self, service_id: u32, method_id: u32, req: &[u8], on_done: TransportDoneFn) {
182        (**self).call_async(service_id, method_id, req, on_done);
183    }
184
185    #[inline]
186    fn call_async_cancellable(
187        &self,
188        service_id: u32,
189        method_id: u32,
190        req: &[u8],
191        on_done: TransportDoneFn,
192    ) -> Option<u64> {
193        (**self).call_async_cancellable(service_id, method_id, req, on_done)
194    }
195
196    #[inline]
197    fn cancel_async(&self, call_id: u64) {
198        (**self).cancel_async(call_id);
199    }
200}
201
202impl<T: ByteTransport + ?Sized> ByteTransport for Arc<T> {
203    #[inline]
204    fn call_sync(
205        &self,
206        service_id: u32,
207        method_id: u32,
208        req: &[u8],
209        on_reply: &mut dyn FnMut(&[u8]),
210    ) -> Result<(), TransportError> {
211        (**self).call_sync(service_id, method_id, req, on_reply)
212    }
213
214    #[inline]
215    fn call_async(&self, service_id: u32, method_id: u32, req: &[u8], on_done: TransportDoneFn) {
216        (**self).call_async(service_id, method_id, req, on_done);
217    }
218
219    #[inline]
220    fn call_async_cancellable(
221        &self,
222        service_id: u32,
223        method_id: u32,
224        req: &[u8],
225        on_done: TransportDoneFn,
226    ) -> Option<u64> {
227        (**self).call_async_cancellable(service_id, method_id, req, on_done)
228    }
229
230    #[inline]
231    fn cancel_async(&self, call_id: u64) {
232        (**self).cancel_async(call_id);
233    }
234}
235
236/// Zero-allocation helper calling [`ByteTransport::call_sync`] and decoding the borrowed reply
237/// slice in place without copying into an intermediate `Vec<u8>`.
238///
239/// Enforces single-reply delivery: if a buggy transport invokes `on_reply` more than once, returns
240/// `Err(TransportError::Internal(_))`.
241#[inline]
242pub fn call_sync_decode<T, F>(
243    transport: &(impl ByteTransport + ?Sized),
244    service_id: u32,
245    method_id: u32,
246    req: &[u8],
247    decode: F,
248) -> Result<T, TransportError>
249where
250    F: FnOnce(&[u8]) -> Result<T, TransportError>,
251{
252    let mut decode = Some(decode);
253    let mut decoded: Option<Result<T, TransportError>> = None;
254    let mut duplicate = false;
255    transport.call_sync(service_id, method_id, req, &mut |reply| {
256        if let Some(f) = decode.take() {
257            decoded = Some(f(reply));
258        } else {
259            duplicate = true;
260        }
261    })?;
262    if duplicate {
263        return Err(TransportError::Internal(
264            "ByteTransport::call_sync invoked on_reply more than once".into(),
265        ));
266    }
267    match decoded {
268        Some(res) => res,
269        None => match decode.take() {
270            Some(f) => f(&[]),
271            None => Err(TransportError::Internal(
272                "ByteTransport::call_sync decoder missing".into(),
273            )),
274        },
275    }
276}
277
278/// Stack-first binary writer backed by [`SliceWriter`] on the fast path, spilling seamlessly into
279/// a heap [`ByteWriter`] (`Vec<u8>`) only when the encoded payload exceeds the stack buffer.
280#[derive(Debug)]
281pub enum StackWriter<'a> {
282    Stack(SliceWriter<'a>),
283    Heap(ByteWriter),
284}
285
286impl StackWriter<'static> {
287    /// Creates a heap-backed writer pre-allocated with `cap` bytes (reusable across `reset()` calls).
288    #[must_use]
289    #[inline]
290    pub fn with_capacity(cap: usize) -> Self {
291        Self::Heap(ByteWriter::with_capacity(cap))
292    }
293}
294
295impl<'a> StackWriter<'a> {
296    #[must_use]
297    #[inline]
298    pub fn new(buf: &'a mut [u8]) -> Self {
299        Self::Stack(SliceWriter::new(buf))
300    }
301
302    #[must_use]
303    #[inline]
304    pub fn is_spilled(&self) -> bool {
305        matches!(self, Self::Heap(_))
306    }
307
308    #[must_use]
309    #[inline]
310    pub fn len(&self) -> usize {
311        match self {
312            Self::Stack(sw) => sw.pos(),
313            Self::Heap(bw) => bw.len(),
314        }
315    }
316
317    #[must_use]
318    #[inline]
319    pub fn is_empty(&self) -> bool {
320        self.len() == 0
321    }
322
323    #[must_use]
324    #[inline]
325    pub fn as_slice(&self) -> &[u8] {
326        match self {
327            Self::Stack(sw) => sw.written(),
328            Self::Heap(bw) => bw.as_slice(),
329        }
330    }
331
332    /// Rewinds the writer to length `0`, retaining any existing stack slice or spilled heap capacity.
333    #[inline]
334    pub fn reset(&mut self) {
335        match self {
336            Self::Stack(sw) => sw.reset(),
337            Self::Heap(bw) => bw.clear(),
338        }
339    }
340
341    /// Overwrites an already-written 4-byte little-endian `u32` at `offset..offset + 4`.
342    #[inline]
343    pub fn patch_u32(&mut self, offset: usize, v: u32) -> Result<(), CodecError> {
344        match self {
345            Self::Stack(sw) => sw.patch_u32(offset, v),
346            Self::Heap(bw) => bw.patch_u32(offset, v),
347        }
348    }
349
350    #[must_use]
351    #[inline]
352    pub fn into_vec(self) -> Vec<u8> {
353        match self {
354            Self::Stack(sw) => sw.written().to_vec(),
355            Self::Heap(bw) => bw.into_bytes(),
356        }
357    }
358
359    #[cold]
360    #[inline(never)]
361    fn spill_with_additional(&mut self, additional: usize) -> Result<&mut ByteWriter, CodecError> {
362        let written = match self {
363            Self::Stack(sw) => sw.written(),
364            Self::Heap(bw) => return Ok(bw),
365        };
366        let cur_len = written.len();
367        let max_additional = (isize::MAX as usize).saturating_sub(cur_len);
368        if additional > max_additional {
369            return Err(CodecError::LenOverflow {
370                len: additional,
371                max: max_additional,
372            });
373        }
374        let min_cap = cur_len.saturating_add(additional);
375        let desired_cap = min_cap
376            .max(cur_len.saturating_mul(2))
377            .max(64)
378            .min(isize::MAX as usize);
379        let mut vec = Vec::new();
380        if vec.try_reserve(desired_cap).is_err() && vec.try_reserve_exact(min_cap).is_err() {
381            return Err(CodecError::LenOverflow {
382                len: min_cap,
383                max: max_additional,
384            });
385        }
386        vec.extend_from_slice(written);
387        *self = Self::Heap(ByteWriter::from_vec(vec));
388        match self {
389            Self::Heap(bw) => Ok(bw),
390            Self::Stack(_) => Err(CodecError::LenOverflow {
391                len: min_cap,
392                max: max_additional,
393            }),
394        }
395    }
396
397    crate::writer::delegate_slice_sink!();
398}
399
400impl ByteSink for StackWriter<'_> {
401    #[inline]
402    fn put_raw(&mut self, bytes: &[u8]) -> Result<(), CodecError> {
403        match self {
404            Self::Stack(sw) => {
405                if bytes.len() <= sw.remaining() {
406                    sw.put_raw(bytes)
407                } else {
408                    let bw = self.spill_with_additional(bytes.len())?;
409                    bw.write_raw(bytes);
410                    Ok(())
411                }
412            }
413            Self::Heap(bw) => {
414                bw.write_raw(bytes);
415                Ok(())
416            }
417        }
418    }
419
420    #[inline]
421    fn put_zeroes(&mut self, count: usize) -> Result<(), CodecError> {
422        match self {
423            Self::Stack(sw) => {
424                if count <= sw.remaining() {
425                    sw.put_zeroes(count)
426                } else {
427                    let bw = self.spill_with_additional(count)?;
428                    bw.write_zeroes(count)
429                }
430            }
431            Self::Heap(bw) => bw.write_zeroes(count),
432        }
433    }
434}
435
436/// Encodes a multi-field binary payload into a stack `[u8; N]` buffer via [`SliceWriter`] with
437/// **0 heap allocations** on the fast path, spilling seamlessly to `Vec<u8>` only on overflow,
438/// and passes the encoded slice to `use_bytes`.
439///
440/// Keep `N` small (`<= 256..512` bytes) to avoid bloating stack frames on deep or async call
441/// paths; larger payloads spill cleanly to heap with amortized growth.
442#[inline]
443pub fn with_stack_writer<const N: usize, R>(
444    encode: impl FnOnce(&mut StackWriter<'_>) -> Result<(), CodecError>,
445    use_bytes: impl FnOnce(&[u8]) -> R,
446) -> Result<R, CodecError> {
447    let mut stack = [0u8; N];
448    let mut writer = StackWriter::new(&mut stack);
449    encode(&mut writer)?;
450    Ok(use_bytes(writer.as_slice()))
451}
452
453/// Fallible companion to [`with_stack_writer`] flattening `CodecError` into a caller error type
454/// `E` (such as [`TransportError`]) so callers can use a single `?`.
455///
456/// Keep `N` small (`<= 256..512` bytes) to keep caller stack frames compact.
457#[inline]
458pub fn try_with_stack_writer<const N: usize, R, E: From<CodecError>>(
459    encode: impl FnOnce(&mut StackWriter<'_>) -> Result<(), CodecError>,
460    use_bytes: impl FnOnce(&[u8]) -> Result<R, E>,
461) -> Result<R, E> {
462    let mut stack = [0u8; N];
463    let mut writer = StackWriter::new(&mut stack);
464    encode(&mut writer)?;
465    use_bytes(writer.as_slice())
466}
467
468/// Canonicalizes `v` (`-0.0` -> `+0.0`, NaN -> canonical quiet NaN) into 4 little-endian bytes.
469#[must_use]
470#[inline(always)]
471pub const fn encode_f32_stack(v: f32) -> [u8; 4] {
472    canonical_f32_bits(v).to_le_bytes()
473}
474
475/// Canonicalizes `v` (`-0.0` -> `+0.0`, NaN -> canonical quiet NaN) into 8 little-endian bytes.
476#[must_use]
477#[inline(always)]
478pub const fn encode_f64_stack(v: f64) -> [u8; 8] {
479    canonical_f64_bits(v).to_le_bytes()
480}
481
482/// Encodes an optional raw UTF-8 string using NV's zero-framing `OptRawStr` layout
483/// (`[0]` for `None`, `[1, utf8...]` for `Some`) in a single allocation.
484#[must_use]
485#[inline]
486pub fn encode_opt_raw_str(text: Option<&str>) -> Vec<u8> {
487    match text {
488        None => vec![0u8],
489        Some(s) => {
490            let mut out = Vec::with_capacity(1 + s.len());
491            out.push(1u8);
492            out.extend_from_slice(s.as_bytes());
493            out
494        }
495    }
496}
497
498/// Decodes an optional raw UTF-8 string from NV's zero-framing `OptRawStr` layout, preserving
499/// exact [`CodecError`] diagnostics (`Truncated`, `TrailingBytes`, `InvalidUtf8`, `BadBool`).
500#[inline]
501pub fn decode_opt_raw_str(bytes: &[u8]) -> Result<Option<String>, CodecError> {
502    match bytes.split_first() {
503        None => Err(CodecError::Truncated {
504            needed: 1,
505            remaining: 0,
506        }),
507        Some((0, &[])) => Ok(None),
508        Some((0, rest)) => Err(CodecError::TrailingBytes(rest.len())),
509        Some((1, rest)) => core::str::from_utf8(rest)
510            .map(|s| Some(String::from(s)))
511            .map_err(|_| CodecError::InvalidUtf8),
512        Some((&b, _)) => Err(CodecError::BadBool(b)),
513    }
514}