nativeview-codec 0.1.0-rc.1

Zero-unsafe, zero-runtime-dependency Tier-2 little-endian binary codec primitives and #[derive(NvCodec)]
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Framework- and runtime-agnostic binary byte transport (`ByteTransport`), error model
//! (`TransportError`), and zero-waste stack-first request encoding helpers (`StackWriter`,
//! `with_stack_writer`, `try_with_stack_writer`, and canonical float stack encoders).
//!
//! Lives in `nativeview-codec` (`#![forbid(unsafe_code)]`, zero runtime/engine/ABI dependencies) so
//! capability modules, RPC clients, and host adapters can share one clean transport abstraction
//! without coupling to `nativeview-abi` or `nativeview-host-services`.

use core::fmt;
use std::sync::Arc;

use crate::{
    canonical_f32_bits, canonical_f64_bits, ByteSink, ByteWriter, CodecError, SliceWriter,
};

/// Transport-layer error decoupled from any specific FFI status table or runtime crate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransportError {
    /// Service or method is not supported on the active transport or platform.
    Unsupported,
    /// Caller lacks permission for the requested capability or operation.
    PermissionDenied,
    /// Caller supplied invalid arguments or a malformed payload.
    Invalid(String),
    /// Requested resource, handle, or key was not found.
    NotFound,
    /// Operation was cancelled (user dismissal, surface teardown, or hot reload).
    Cancelled,
    /// Underlying I/O or link-layer failure.
    Io(String),
    /// Payload exceeded the configured or negotiated buffer capacity.
    BufferOverflow { needed: usize, capacity: usize },
    /// Binary codec serialization or deserialization failed.
    Codec(CodecError),
    /// Transport-specific non-zero status code (for raw foreign/C-ABI errors).
    Status(i32),
    /// Internal transport or peer failure.
    Internal(String),
}

impl From<CodecError> for TransportError {
    #[inline]
    fn from(err: CodecError) -> Self {
        Self::Codec(err)
    }
}

impl From<std::io::Error> for TransportError {
    #[inline]
    fn from(err: std::io::Error) -> Self {
        Self::Io(err.to_string())
    }
}

impl fmt::Display for TransportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unsupported => f.write_str("transport operation unsupported"),
            Self::PermissionDenied => f.write_str("transport permission denied"),
            Self::Invalid(msg) => write!(f, "invalid transport argument: {msg}"),
            Self::NotFound => f.write_str("transport resource not found"),
            Self::Cancelled => f.write_str("transport operation cancelled"),
            Self::Io(msg) => write!(f, "transport I/O error: {msg}"),
            Self::BufferOverflow { needed, capacity } => {
                write!(
                    f,
                    "transport buffer overflow: needed {needed}B, capacity {capacity}B"
                )
            }
            Self::Codec(err) => write!(f, "transport codec error: {err}"),
            Self::Status(code) => write!(f, "transport status error ({code})"),
            Self::Internal(msg) => write!(f, "internal transport error: {msg}"),
        }
    }
}

impl std::error::Error for TransportError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Codec(err) => Some(err),
            _ => None,
        }
    }
}

/// Callback invoked once when an asynchronous [`ByteTransport::call_async`] completes.
pub type TransportDoneFn = Box<dyn FnOnce(Result<&[u8], TransportError>) + Send>;

/// Pluggable binary request/reply transport with zero-copy synchronous reply delivery and
/// callback-driven asynchronous completion.
///
/// Implementations may bridge in-process registries, direct C-ABI callback sinks, IPC sockets,
/// WebWorkers, or deterministic unit-test harnesses without coupling callers to any concrete host.
pub trait ByteTransport: Send + Sync {
    /// Synchronously invokes `(service_id, method_id)` with `req`, delivering reply bytes to
    /// `on_reply` while the transport's stack or borrowed reply buffer is still live (enabling
    /// zero-allocation reply decoding on the fast path).
    fn call_sync(
        &self,
        service_id: u32,
        method_id: u32,
        req: &[u8],
        on_reply: &mut dyn FnMut(&[u8]),
    ) -> Result<(), TransportError>;

    /// Initiates an asynchronous invocation of `(service_id, method_id)` with `req`, delivering
    /// the borrowed reply slice or [`TransportError`] to `on_done` exactly once on completion.
    fn call_async(
        &self,
        service_id: u32,
        method_id: u32,
        req: &[u8],
        on_done: TransportDoneFn,
    );

    /// Initiates an asynchronous invocation and optionally returns a transport-scoped cancellation
    /// handle that may later be passed to [`Self::cancel_async`].
    fn call_async_cancellable(
        &self,
        service_id: u32,
        method_id: u32,
        req: &[u8],
        on_done: TransportDoneFn,
    ) -> Option<u64> {
        self.call_async(service_id, method_id, req, on_done);
        None
    }

    /// Best-effort cancellation of an in-flight asynchronous call started by
    /// [`Self::call_async_cancellable`].
    fn cancel_async(&self, _call_id: u64) {}
}

impl<T: ByteTransport + ?Sized> ByteTransport for &T {
    #[inline]
    fn call_sync(
        &self,
        service_id: u32,
        method_id: u32,
        req: &[u8],
        on_reply: &mut dyn FnMut(&[u8]),
    ) -> Result<(), TransportError> {
        (**self).call_sync(service_id, method_id, req, on_reply)
    }

    #[inline]
    fn call_async(&self, service_id: u32, method_id: u32, req: &[u8], on_done: TransportDoneFn) {
        (**self).call_async(service_id, method_id, req, on_done);
    }

    #[inline]
    fn call_async_cancellable(
        &self,
        service_id: u32,
        method_id: u32,
        req: &[u8],
        on_done: TransportDoneFn,
    ) -> Option<u64> {
        (**self).call_async_cancellable(service_id, method_id, req, on_done)
    }

    #[inline]
    fn cancel_async(&self, call_id: u64) {
        (**self).cancel_async(call_id);
    }
}

impl<T: ByteTransport + ?Sized> ByteTransport for Box<T> {
    #[inline]
    fn call_sync(
        &self,
        service_id: u32,
        method_id: u32,
        req: &[u8],
        on_reply: &mut dyn FnMut(&[u8]),
    ) -> Result<(), TransportError> {
        (**self).call_sync(service_id, method_id, req, on_reply)
    }

    #[inline]
    fn call_async(&self, service_id: u32, method_id: u32, req: &[u8], on_done: TransportDoneFn) {
        (**self).call_async(service_id, method_id, req, on_done);
    }

    #[inline]
    fn call_async_cancellable(
        &self,
        service_id: u32,
        method_id: u32,
        req: &[u8],
        on_done: TransportDoneFn,
    ) -> Option<u64> {
        (**self).call_async_cancellable(service_id, method_id, req, on_done)
    }

    #[inline]
    fn cancel_async(&self, call_id: u64) {
        (**self).cancel_async(call_id);
    }
}

impl<T: ByteTransport + ?Sized> ByteTransport for Arc<T> {
    #[inline]
    fn call_sync(
        &self,
        service_id: u32,
        method_id: u32,
        req: &[u8],
        on_reply: &mut dyn FnMut(&[u8]),
    ) -> Result<(), TransportError> {
        (**self).call_sync(service_id, method_id, req, on_reply)
    }

    #[inline]
    fn call_async(&self, service_id: u32, method_id: u32, req: &[u8], on_done: TransportDoneFn) {
        (**self).call_async(service_id, method_id, req, on_done);
    }

    #[inline]
    fn call_async_cancellable(
        &self,
        service_id: u32,
        method_id: u32,
        req: &[u8],
        on_done: TransportDoneFn,
    ) -> Option<u64> {
        (**self).call_async_cancellable(service_id, method_id, req, on_done)
    }

    #[inline]
    fn cancel_async(&self, call_id: u64) {
        (**self).cancel_async(call_id);
    }
}

/// Zero-allocation helper calling [`ByteTransport::call_sync`] and decoding the borrowed reply
/// slice in place without copying into an intermediate `Vec<u8>`.
///
/// Enforces single-reply delivery: if a buggy transport invokes `on_reply` more than once, returns
/// `Err(TransportError::Internal(_))`.
#[inline]
pub fn call_sync_decode<T, F>(
    transport: &(impl ByteTransport + ?Sized),
    service_id: u32,
    method_id: u32,
    req: &[u8],
    decode: F,
) -> Result<T, TransportError>
where
    F: FnOnce(&[u8]) -> Result<T, TransportError>,
{
    let mut decode = Some(decode);
    let mut decoded: Option<Result<T, TransportError>> = None;
    let mut duplicate = false;
    transport.call_sync(service_id, method_id, req, &mut |reply| {
        if let Some(f) = decode.take() {
            decoded = Some(f(reply));
        } else {
            duplicate = true;
        }
    })?;
    if duplicate {
        return Err(TransportError::Internal(
            "ByteTransport::call_sync invoked on_reply more than once".into(),
        ));
    }
    match decoded {
        Some(res) => res,
        None => match decode.take() {
            Some(f) => f(&[]),
            None => Err(TransportError::Internal(
                "ByteTransport::call_sync decoder missing".into(),
            )),
        },
    }
}

/// Stack-first binary writer backed by [`SliceWriter`] on the fast path, spilling seamlessly into
/// a heap [`ByteWriter`] (`Vec<u8>`) only when the encoded payload exceeds the stack buffer.
#[derive(Debug)]
pub enum StackWriter<'a> {
    Stack(SliceWriter<'a>),
    Heap(ByteWriter),
}

impl StackWriter<'static> {
    /// Creates a heap-backed writer pre-allocated with `cap` bytes (reusable across `reset()` calls).
    #[must_use]
    #[inline]
    pub fn with_capacity(cap: usize) -> Self {
        Self::Heap(ByteWriter::with_capacity(cap))
    }
}

impl<'a> StackWriter<'a> {
    #[must_use]
    #[inline]
    pub fn new(buf: &'a mut [u8]) -> Self {
        Self::Stack(SliceWriter::new(buf))
    }

    #[must_use]
    #[inline]
    pub fn is_spilled(&self) -> bool {
        matches!(self, Self::Heap(_))
    }

    #[must_use]
    #[inline]
    pub fn len(&self) -> usize {
        match self {
            Self::Stack(sw) => sw.pos(),
            Self::Heap(bw) => bw.len(),
        }
    }

    #[must_use]
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[must_use]
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        match self {
            Self::Stack(sw) => sw.written(),
            Self::Heap(bw) => bw.as_slice(),
        }
    }

    /// Rewinds the writer to length `0`, retaining any existing stack slice or spilled heap capacity.
    #[inline]
    pub fn reset(&mut self) {
        match self {
            Self::Stack(sw) => sw.reset(),
            Self::Heap(bw) => bw.clear(),
        }
    }

    /// Overwrites an already-written 4-byte little-endian `u32` at `offset..offset + 4`.
    #[inline]
    pub fn patch_u32(&mut self, offset: usize, v: u32) -> Result<(), CodecError> {
        match self {
            Self::Stack(sw) => sw.patch_u32(offset, v),
            Self::Heap(bw) => bw.patch_u32(offset, v),
        }
    }

    #[must_use]
    #[inline]
    pub fn into_vec(self) -> Vec<u8> {
        match self {
            Self::Stack(sw) => sw.written().to_vec(),
            Self::Heap(bw) => bw.into_bytes(),
        }
    }

    #[cold]
    #[inline(never)]
    fn spill_with_additional(&mut self, additional: usize) -> Result<&mut ByteWriter, CodecError> {
        let written = match self {
            Self::Stack(sw) => sw.written(),
            Self::Heap(bw) => return Ok(bw),
        };
        let cur_len = written.len();
        let max_additional = (isize::MAX as usize).saturating_sub(cur_len);
        if additional > max_additional {
            return Err(CodecError::LenOverflow {
                len: additional,
                max: max_additional,
            });
        }
        let min_cap = cur_len.saturating_add(additional);
        let desired_cap = min_cap
            .max(cur_len.saturating_mul(2))
            .max(64)
            .min(isize::MAX as usize);
        let mut vec = Vec::new();
        if vec.try_reserve(desired_cap).is_err() && vec.try_reserve_exact(min_cap).is_err() {
            return Err(CodecError::LenOverflow {
                len: min_cap,
                max: max_additional,
            });
        }
        vec.extend_from_slice(written);
        *self = Self::Heap(ByteWriter::from_vec(vec));
        match self {
            Self::Heap(bw) => Ok(bw),
            Self::Stack(_) => Err(CodecError::LenOverflow {
                len: min_cap,
                max: max_additional,
            }),
        }
    }

    crate::writer::delegate_slice_sink!();
}

impl ByteSink for StackWriter<'_> {
    #[inline]
    fn put_raw(&mut self, bytes: &[u8]) -> Result<(), CodecError> {
        match self {
            Self::Stack(sw) => {
                if bytes.len() <= sw.remaining() {
                    sw.put_raw(bytes)
                } else {
                    let bw = self.spill_with_additional(bytes.len())?;
                    bw.write_raw(bytes);
                    Ok(())
                }
            }
            Self::Heap(bw) => {
                bw.write_raw(bytes);
                Ok(())
            }
        }
    }

    #[inline]
    fn put_zeroes(&mut self, count: usize) -> Result<(), CodecError> {
        match self {
            Self::Stack(sw) => {
                if count <= sw.remaining() {
                    sw.put_zeroes(count)
                } else {
                    let bw = self.spill_with_additional(count)?;
                    bw.write_zeroes(count)
                }
            }
            Self::Heap(bw) => bw.write_zeroes(count),
        }
    }
}

/// Encodes a multi-field binary payload into a stack `[u8; N]` buffer via [`SliceWriter`] with
/// **0 heap allocations** on the fast path, spilling seamlessly to `Vec<u8>` only on overflow,
/// and passes the encoded slice to `use_bytes`.
///
/// Keep `N` small (`<= 256..512` bytes) to avoid bloating stack frames on deep or async call
/// paths; larger payloads spill cleanly to heap with amortized growth.
#[inline]
pub fn with_stack_writer<const N: usize, R>(
    encode: impl FnOnce(&mut StackWriter<'_>) -> Result<(), CodecError>,
    use_bytes: impl FnOnce(&[u8]) -> R,
) -> Result<R, CodecError> {
    let mut stack = [0u8; N];
    let mut writer = StackWriter::new(&mut stack);
    encode(&mut writer)?;
    Ok(use_bytes(writer.as_slice()))
}

/// Fallible companion to [`with_stack_writer`] flattening `CodecError` into a caller error type
/// `E` (such as [`TransportError`]) so callers can use a single `?`.
///
/// Keep `N` small (`<= 256..512` bytes) to keep caller stack frames compact.
#[inline]
pub fn try_with_stack_writer<const N: usize, R, E: From<CodecError>>(
    encode: impl FnOnce(&mut StackWriter<'_>) -> Result<(), CodecError>,
    use_bytes: impl FnOnce(&[u8]) -> Result<R, E>,
) -> Result<R, E> {
    let mut stack = [0u8; N];
    let mut writer = StackWriter::new(&mut stack);
    encode(&mut writer)?;
    use_bytes(writer.as_slice())
}

/// Canonicalizes `v` (`-0.0` -> `+0.0`, NaN -> canonical quiet NaN) into 4 little-endian bytes.
#[must_use]
#[inline(always)]
pub const fn encode_f32_stack(v: f32) -> [u8; 4] {
    canonical_f32_bits(v).to_le_bytes()
}

/// Canonicalizes `v` (`-0.0` -> `+0.0`, NaN -> canonical quiet NaN) into 8 little-endian bytes.
#[must_use]
#[inline(always)]
pub const fn encode_f64_stack(v: f64) -> [u8; 8] {
    canonical_f64_bits(v).to_le_bytes()
}

/// Encodes an optional raw UTF-8 string using NV's zero-framing `OptRawStr` layout
/// (`[0]` for `None`, `[1, utf8...]` for `Some`) in a single allocation.
#[must_use]
#[inline]
pub fn encode_opt_raw_str(text: Option<&str>) -> Vec<u8> {
    match text {
        None => vec![0u8],
        Some(s) => {
            let mut out = Vec::with_capacity(1 + s.len());
            out.push(1u8);
            out.extend_from_slice(s.as_bytes());
            out
        }
    }
}

/// Decodes an optional raw UTF-8 string from NV's zero-framing `OptRawStr` layout, preserving
/// exact [`CodecError`] diagnostics (`Truncated`, `TrailingBytes`, `InvalidUtf8`, `BadBool`).
#[inline]
pub fn decode_opt_raw_str(bytes: &[u8]) -> Result<Option<String>, CodecError> {
    match bytes.split_first() {
        None => Err(CodecError::Truncated {
            needed: 1,
            remaining: 0,
        }),
        Some((0, &[])) => Ok(None),
        Some((0, rest)) => Err(CodecError::TrailingBytes(rest.len())),
        Some((1, rest)) => core::str::from_utf8(rest)
            .map(|s| Some(String::from(s)))
            .map_err(|_| CodecError::InvalidUtf8),
        Some((&b, _)) => Err(CodecError::BadBool(b)),
    }
}