Skip to main content

logicaffeine_data/
wire.rs

1//! Shared wire-codec core — the exact byte format of the peer/transport codec
2//! (`logicaffeine_compile::concurrency::marshal`), factored out so that TWO value models
3//! encode and decode through ONE definition:
4//!
5//!   * the interpreter's `RuntimeValue` (host side), and
6//!   * AOT-generated Rust `enum`/`struct` types (native side).
7//!
8//! Because both go through this module, the wire bytes are byte-identical by construction —
9//! not a parallel re-implementation that can drift. This is what lets a compile-once native
10//! partial evaluator receive a program as data over the *real* fast codec, at native speed.
11//!
12//! The tag bytes and field layout MUST stay in lockstep with `marshal.rs`; the
13//! `wire_bytes_match_peer_codec` test in `logicaffeine_compile` proves it.
14
15// ── Tag bytes (subset used by algebraic ASTs; identical values to marshal.rs) ──────────────
16/// `Nothing` / unit.
17pub const T_NOTHING: u8 = 0;
18/// Boolean `false`.
19pub const T_FALSE: u8 = 1;
20/// Boolean `true`.
21pub const T_TRUE: u8 = 2;
22/// A signed integer, zig-zag + LEB128 varint.
23pub const T_INT: u8 = 3;
24/// An IEEE-754 double, 8 little-endian bytes.
25pub const T_FLOAT: u8 = 4;
26/// A UTF-8 string: varint byte-length, then the bytes.
27pub const T_TEXT: u8 = 6;
28/// A heterogeneous list: varint element count, then each element (tagged).
29pub const T_LIST: u8 = 13;
30/// An inductive/enum value: `type_name` string, `constructor` string, varint arg count, args.
31pub const T_INDUCTIVE: u8 = 18;
32
33// ── Primitive stream helpers (byte-for-byte identical to marshal.rs) ───────────────────────
34
35/// LEB128 unsigned varint.
36#[inline]
37pub fn write_uvarint(mut x: u64, out: &mut Vec<u8>) {
38    while x >= 0x80 {
39        out.push((x as u8) | 0x80);
40        x >>= 7;
41    }
42    out.push(x as u8);
43}
44
45/// Inverse of [`write_uvarint`]; `None` on truncation or overlong (>64-bit) input.
46#[inline]
47pub fn read_uvarint(buf: &[u8], pos: &mut usize) -> Option<u64> {
48    let mut result = 0u64;
49    let mut shift = 0u32;
50    loop {
51        let b = *buf.get(*pos)?;
52        *pos += 1;
53        if shift >= 64 {
54            return None;
55        }
56        result |= u64::from(b & 0x7f) << shift;
57        if b & 0x80 == 0 {
58            return Some(result);
59        }
60        shift += 7;
61    }
62}
63
64/// Map a signed integer onto an unsigned one so small magnitudes stay short.
65#[inline]
66pub fn zigzag(x: i64) -> u64 {
67    ((x << 1) ^ (x >> 63)) as u64
68}
69
70/// Inverse of [`zigzag`].
71#[inline]
72pub fn unzigzag(x: u64) -> i64 {
73    ((x >> 1) as i64) ^ -((x & 1) as i64)
74}
75
76/// A length-prefixed UTF-8 string, UNtagged (used for inductive `type_name`/`constructor`).
77#[inline]
78pub fn write_str(s: &str, out: &mut Vec<u8>) {
79    write_uvarint(s.len() as u64, out);
80    out.extend_from_slice(s.as_bytes());
81}
82
83/// Inverse of [`write_str`]; `None` on truncation or invalid UTF-8.
84#[inline]
85pub fn read_str(buf: &[u8], pos: &mut usize) -> Option<String> {
86    let n = read_uvarint(buf, pos)? as usize;
87    let bytes = buf.get(*pos..pos.checked_add(n)?)?;
88    *pos += n;
89    String::from_utf8(bytes.to_vec()).ok()
90}
91
92/// Read the tag byte at `pos` and advance; `None` if it is not `expected`.
93#[inline]
94pub fn expect_tag(buf: &[u8], pos: &mut usize, expected: u8) -> Option<()> {
95    let t = *buf.get(*pos)?;
96    if t != expected {
97        return None;
98    }
99    *pos += 1;
100    Some(())
101}
102
103// ── Inductive header (the seam codegen emits into) ─────────────────────────────────────────
104
105/// Write the header of an inductive value: `T_INDUCTIVE`, its `type_name`, its `constructor`,
106/// and the argument count. The args themselves follow, each written via [`WireEncode`].
107#[inline]
108pub fn write_inductive_header(out: &mut Vec<u8>, type_name: &str, constructor: &str, nargs: u64) {
109    out.push(T_INDUCTIVE);
110    write_str(type_name, out);
111    write_str(constructor, out);
112    write_uvarint(nargs, out);
113}
114
115/// Read an inductive header, returning `(type_name, constructor, nargs)`. The caller dispatches
116/// on `constructor` and reads `nargs` arguments via [`WireDecode`].
117#[inline]
118pub fn read_inductive_header(buf: &[u8], pos: &mut usize) -> Option<(String, String, u64)> {
119    expect_tag(buf, pos, T_INDUCTIVE)?;
120    let type_name = read_str(buf, pos)?;
121    let constructor = read_str(buf, pos)?;
122    let nargs = read_uvarint(buf, pos)?;
123    Some((type_name, constructor, nargs))
124}
125
126// ── The two traits (codegen emits impls for generated types; RuntimeValue impls them host-side) ─
127
128/// A value that serializes into the shared wire format.
129pub trait WireEncode {
130    /// Append `self`'s tagged wire bytes to `out`.
131    fn wire_encode(&self, out: &mut Vec<u8>);
132}
133
134/// A value that reconstructs from the shared wire format.
135pub trait WireDecode: Sized {
136    /// Read one value starting at `*pos`, advancing `pos`. `None` on any malformed input.
137    fn wire_decode(buf: &[u8], pos: &mut usize) -> Option<Self>;
138}
139
140impl WireEncode for i64 {
141    fn wire_encode(&self, out: &mut Vec<u8>) {
142        out.push(T_INT);
143        write_uvarint(zigzag(*self), out);
144    }
145}
146impl WireDecode for i64 {
147    fn wire_decode(buf: &[u8], pos: &mut usize) -> Option<Self> {
148        expect_tag(buf, pos, T_INT)?;
149        Some(unzigzag(read_uvarint(buf, pos)?))
150    }
151}
152
153impl WireEncode for bool {
154    fn wire_encode(&self, out: &mut Vec<u8>) {
155        out.push(if *self { T_TRUE } else { T_FALSE });
156    }
157}
158impl WireDecode for bool {
159    fn wire_decode(buf: &[u8], pos: &mut usize) -> Option<Self> {
160        let t = *buf.get(*pos)?;
161        *pos += 1;
162        match t {
163            T_TRUE => Some(true),
164            T_FALSE => Some(false),
165            _ => None,
166        }
167    }
168}
169
170/// The bits every NaN is written as: the canonical quiet NaN. A NaN's sign and payload differ by host
171/// (x86 arithmetic makes `0xFFF8…`, other hosts and WASM differ), and the wire is the one place a
172/// program can read a float's bits, so every encoder writes a NaN as this and nothing else.
173pub const CANONICAL_NAN_BITS: u64 = 0x7FF8_0000_0000_0000;
174
175/// The bits the wire carries for `x`: its own, or the canonical NaN's.
176#[inline]
177pub fn canonical_f64_bits(x: f64) -> u64 {
178    if x.is_nan() {
179        CANONICAL_NAN_BITS
180    } else {
181        x.to_bits()
182    }
183}
184
185/// `x`, or the canonical NaN when `x` is a NaN.
186#[inline]
187pub fn canonical_f64(x: f64) -> f64 {
188    f64::from_bits(canonical_f64_bits(x))
189}
190
191/// Append `x`'s wire bytes (little-endian, NaN canonical).
192#[inline]
193pub fn put_f64(out: &mut Vec<u8>, x: f64) {
194    out.extend_from_slice(&canonical_f64_bits(x).to_le_bytes());
195}
196
197/// Append a float column's wire bytes (little-endian, every NaN canonical) in one pass: each element is
198/// loaded, tested and stored once, the memory traffic of a copy. On an AVX2 host the pass runs four
199/// elements per instruction (an unordered compare and a blend).
200pub fn put_f64s(out: &mut Vec<u8>, v: &[f64]) {
201    let start = out.len();
202    out.reserve(v.len() * 8);
203    let dst = out.spare_capacity_mut().as_mut_ptr().cast::<u64>();
204    #[cfg(target_arch = "x86_64")]
205    {
206        if std::is_x86_feature_detected!("avx2") {
207            // SAFETY: AVX2 is present; `reserve` made room for `v.len()` words past `start`.
208            unsafe { put_f64s_avx2(dst, v) };
209        } else {
210            // SAFETY: `reserve` made room for `v.len()` words past `start`.
211            unsafe { put_f64s_into(dst, v) };
212        }
213    }
214    #[cfg(not(target_arch = "x86_64"))]
215    // SAFETY: `reserve` made room for `v.len()` words past `start`.
216    unsafe {
217        put_f64s_into(dst, v)
218    };
219    // SAFETY: every byte in `start..start + 8·v.len()` was written above.
220    unsafe { out.set_len(start + v.len() * 8) };
221}
222
223/// Write `v`'s wire words to `dst`, each once and unaligned.
224///
225/// # Safety
226/// `dst` must be valid for `v.len()` unaligned 8-byte writes.
227#[inline(always)]
228unsafe fn put_f64s_into(dst: *mut u64, v: &[f64]) {
229    for (i, &x) in v.iter().enumerate() {
230        // SAFETY: the caller's contract covers word `i < v.len()`.
231        unsafe { dst.add(i).write_unaligned(canonical_f64_bits(x).to_le()) };
232    }
233}
234
235/// [`put_f64s_into`] compiled for AVX2.
236///
237/// # Safety
238/// The host has AVX2, and `dst` is valid for `v.len()` unaligned 8-byte writes.
239#[cfg(target_arch = "x86_64")]
240#[target_feature(enable = "avx2")]
241unsafe fn put_f64s_avx2(dst: *mut u64, v: &[f64]) {
242    // SAFETY: forwarded from the caller.
243    unsafe { put_f64s_into(dst, v) }
244}
245
246impl WireEncode for f64 {
247    fn wire_encode(&self, out: &mut Vec<u8>) {
248        out.push(T_FLOAT);
249        put_f64(out, *self);
250    }
251}
252impl WireDecode for f64 {
253    fn wire_decode(buf: &[u8], pos: &mut usize) -> Option<Self> {
254        expect_tag(buf, pos, T_FLOAT)?;
255        let b: [u8; 8] = buf.get(*pos..pos.checked_add(8)?)?.try_into().ok()?;
256        *pos += 8;
257        Some(f64::from_le_bytes(b))
258    }
259}
260
261impl WireEncode for String {
262    fn wire_encode(&self, out: &mut Vec<u8>) {
263        out.push(T_TEXT);
264        write_str(self, out);
265    }
266}
267impl WireDecode for String {
268    fn wire_decode(buf: &[u8], pos: &mut usize) -> Option<Self> {
269        expect_tag(buf, pos, T_TEXT)?;
270        read_str(buf, pos)
271    }
272}
273
274impl<T: WireEncode + ?Sized> WireEncode for Box<T> {
275    fn wire_encode(&self, out: &mut Vec<u8>) {
276        (**self).wire_encode(out);
277    }
278}
279impl<T: WireDecode> WireDecode for Box<T> {
280    fn wire_decode(buf: &[u8], pos: &mut usize) -> Option<Self> {
281        Some(Box::new(T::wire_decode(buf, pos)?))
282    }
283}
284
285impl<T: WireEncode> WireEncode for Vec<T> {
286    fn wire_encode(&self, out: &mut Vec<u8>) {
287        out.push(T_LIST);
288        write_uvarint(self.len() as u64, out);
289        for e in self {
290            e.wire_encode(out);
291        }
292    }
293}
294impl<T: WireDecode> WireDecode for Vec<T> {
295    fn wire_decode(buf: &[u8], pos: &mut usize) -> Option<Self> {
296        expect_tag(buf, pos, T_LIST)?;
297        let n = read_uvarint(buf, pos)? as usize;
298        let mut xs = Vec::with_capacity(n.min(1024));
299        for _ in 0..n {
300            xs.push(T::wire_decode(buf, pos)?);
301        }
302        Some(xs)
303    }
304}
305
306// A `Seq of T` field codegens as `LogosSeq<T>` (the interpreter/AOT sequence type), so the
307// generated `wire_encode`/`wire_decode` need it too — same `T_LIST` bytes as `Vec<T>`.
308impl<T: WireEncode> WireEncode for crate::types::LogosSeq<T> {
309    fn wire_encode(&self, out: &mut Vec<u8>) {
310        let inner = self.0.borrow();
311        out.push(T_LIST);
312        write_uvarint(inner.len() as u64, out);
313        for e in inner.iter() {
314            e.wire_encode(out);
315        }
316    }
317}
318impl<T: WireDecode> WireDecode for crate::types::LogosSeq<T> {
319    fn wire_decode(buf: &[u8], pos: &mut usize) -> Option<Self> {
320        expect_tag(buf, pos, T_LIST)?;
321        let n = read_uvarint(buf, pos)? as usize;
322        let mut v = Vec::with_capacity(n.min(1024));
323        for _ in 0..n {
324            v.push(T::wire_decode(buf, pos)?);
325        }
326        Some(crate::types::LogosSeq::from_vec(v))
327    }
328}
329
330#[cfg(test)]
331#[path = "../../logicaffeine_tests/unit/logicaffeine_data/wire/tests.rs"]
332mod tests;