Skip to main content

labstream_wire/
lib.rs

1//! The LSL sample codec for protocol 1.10.
2//!
3//! This crate holds no input and no output. It takes bytes and returns bytes.
4//! Every rule here comes from `SPEC.md`, which cites the pinned oracle.
5//!
6//! The codec is the one part of LSL that a test can compare byte for byte. A
7//! fixed sample with a fixed byte order always produces the same bytes.
8
9#![forbid(unsafe_code)]
10#![deny(missing_docs)]
11
12use core::fmt;
13use std::sync::Arc;
14
15/// Tag that starts a sample with no timestamp bytes. SPEC.md 7.1.
16pub const TAG_DEDUCED_TIMESTAMP: u8 = 1;
17/// Tag that starts a sample with an `f64` timestamp. SPEC.md 7.1.
18pub const TAG_TRANSMITTED_TIMESTAMP: u8 = 2;
19
20/// The timestamp value that means "deduce this on the reading side".
21///
22/// liblsl uses `-1.0` (`include/lsl/common.h:48`).
23pub const DEDUCED_TIMESTAMP: f64 = -1.0;
24
25/// The nominal rate that means "this stream has no fixed rate".
26///
27/// liblsl uses `0.0` (`include/lsl/common.h:39`).
28pub const IRREGULAR_RATE: f64 = 0.0;
29
30/// A channel format. The values match `include/lsl/common.h:64-84`.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32#[repr(u8)]
33pub enum Format {
34    /// No format. A stream never carries this.
35    Undefined = 0,
36    /// 32-bit float.
37    Float32 = 1,
38    /// 64-bit float.
39    Double64 = 2,
40    /// A length-prefixed byte string.
41    String = 3,
42    /// 32-bit signed integer.
43    Int32 = 4,
44    /// 16-bit signed integer.
45    Int16 = 5,
46    /// 8-bit signed integer.
47    Int8 = 6,
48    /// 64-bit signed integer.
49    Int64 = 7,
50}
51
52impl Format {
53    /// Build a format from its wire value.
54    pub fn from_u8(v: u8) -> Option<Self> {
55        Some(match v {
56            0 => Format::Undefined,
57            1 => Format::Float32,
58            2 => Format::Double64,
59            3 => Format::String,
60            4 => Format::Int32,
61            5 => Format::Int16,
62            6 => Format::Int8,
63            7 => Format::Int64,
64            _ => return None,
65        })
66    }
67
68    /// The width of one value in bytes. A string has no fixed width.
69    pub fn width(self) -> Option<usize> {
70        Some(match self {
71            Format::Undefined | Format::String => return None,
72            Format::Float32 | Format::Int32 => 4,
73            Format::Double64 | Format::Int64 => 8,
74            Format::Int16 => 2,
75            Format::Int8 => 1,
76        })
77    }
78
79    /// True when the format holds a floating point value.
80    ///
81    /// liblsl calls this table `format_float` (`src/sample.h:32`).
82    pub fn is_float(self) -> bool {
83        matches!(self, Format::Float32 | Format::Double64)
84    }
85}
86
87/// One channel value.
88#[derive(Debug, Clone, PartialEq)]
89pub enum Value {
90    /// A 32-bit float.
91    F32(f32),
92    /// A 64-bit float.
93    F64(f64),
94    /// A byte string. LSL does not require valid UTF-8.
95    Str(Vec<u8>),
96    /// A 32-bit signed integer.
97    I32(i32),
98    /// A 16-bit signed integer.
99    I16(i16),
100    /// An 8-bit signed integer.
101    I8(i8),
102    /// A 64-bit signed integer.
103    I64(i64),
104}
105
106/// One sample: a timestamp and one value per channel.
107#[derive(Debug, Clone, PartialEq)]
108pub struct Sample {
109    /// The timestamp. `DEDUCED_TIMESTAMP` means the reader derives it.
110    pub timestamp: f64,
111    /// One value per channel. Every value carries the same format.
112    pub values: Vec<Value>,
113}
114
115/// Compact, reference-counted channel values for one sample.
116///
117/// For all fixed-width numeric formats, `Numeric` holds the native-endian
118/// channel bytes contiguously in an `Arc<[u8]>` (e.g., 256 bytes for 64 `f32`
119/// channels instead of 2048 bytes for `Vec<Value>`). Cloning a
120/// [`PackedSample`] across multiple consumer queues and the `resume` history
121/// copies only the `Arc` pointer.
122#[derive(Debug, Clone, PartialEq)]
123pub enum PackedValues {
124    /// Contiguous native-endian channel bytes for a fixed-width format.
125    Numeric {
126        /// Channel format (never `String` or `Undefined`).
127        format: Format,
128        /// Contiguous native-endian bytes (`channels * format.width()`).
129        bytes: Arc<[u8]>,
130    },
131    /// Channel byte strings for `Format::String`.
132    Strings(Arc<[Vec<u8>]>),
133}
134
135/// One sample with reference-counted flat payload (`docs/roadmap.md`, step 8).
136#[derive(Debug, Clone, PartialEq)]
137pub struct PackedSample {
138    /// The timestamp. `DEDUCED_TIMESTAMP` means the reader derives it.
139    pub timestamp: f64,
140    /// Shared payload for all channels.
141    pub values: PackedValues,
142}
143
144impl PackedSample {
145    /// Build a packed numeric sample from pre-packed native-endian bytes.
146    pub fn from_raw_bytes(timestamp: f64, format: Format, bytes: Arc<[u8]>) -> Self {
147        PackedSample {
148            timestamp,
149            values: PackedValues::Numeric { format, bytes },
150        }
151    }
152
153    /// Build a packed `Float32` sample directly from a flat slice.
154    pub fn from_f32(timestamp: f64, values: &[f32]) -> Self {
155        let mut bytes = Vec::with_capacity(values.len() * 4);
156        for &v in values {
157            bytes.extend_from_slice(&v.to_ne_bytes());
158        }
159        Self::from_raw_bytes(timestamp, Format::Float32, Arc::from(bytes))
160    }
161
162    /// Build a packed `Double64` sample directly from a flat slice.
163    pub fn from_f64(timestamp: f64, values: &[f64]) -> Self {
164        let mut bytes = Vec::with_capacity(values.len() * 8);
165        for &v in values {
166            bytes.extend_from_slice(&v.to_ne_bytes());
167        }
168        Self::from_raw_bytes(timestamp, Format::Double64, Arc::from(bytes))
169    }
170
171    /// Build a packed `Int32` sample directly from a flat slice.
172    pub fn from_i32(timestamp: f64, values: &[i32]) -> Self {
173        let mut bytes = Vec::with_capacity(values.len() * 4);
174        for &v in values {
175            bytes.extend_from_slice(&v.to_ne_bytes());
176        }
177        Self::from_raw_bytes(timestamp, Format::Int32, Arc::from(bytes))
178    }
179
180    /// Build a packed `Int16` sample directly from a flat slice.
181    pub fn from_i16(timestamp: f64, values: &[i16]) -> Self {
182        let mut bytes = Vec::with_capacity(values.len() * 2);
183        for &v in values {
184            bytes.extend_from_slice(&v.to_ne_bytes());
185        }
186        Self::from_raw_bytes(timestamp, Format::Int16, Arc::from(bytes))
187    }
188
189    /// Build a packed `Int8` sample directly from a flat slice.
190    pub fn from_i8(timestamp: f64, values: &[i8]) -> Self {
191        let bytes: Vec<u8> = values.iter().map(|&v| v as u8).collect();
192        Self::from_raw_bytes(timestamp, Format::Int8, Arc::from(bytes))
193    }
194
195    /// Build a packed `Int64` sample directly from a flat slice.
196    pub fn from_i64(timestamp: f64, values: &[i64]) -> Self {
197        let mut bytes = Vec::with_capacity(values.len() * 8);
198        for &v in values {
199            bytes.extend_from_slice(&v.to_ne_bytes());
200        }
201        Self::from_raw_bytes(timestamp, Format::Int64, Arc::from(bytes))
202    }
203
204    /// Build a packed `String` sample from channel byte vectors.
205    pub fn from_strings(timestamp: f64, values: Vec<Vec<u8>>) -> Self {
206        PackedSample {
207            timestamp,
208            values: PackedValues::Strings(Arc::from(values)),
209        }
210    }
211
212    /// Convert a [`Sample`] into a [`PackedSample`].
213    pub fn from_sample(s: &Sample) -> Self {
214        let Some(first) = s.values.first() else {
215            return PackedSample::from_strings(s.timestamp, Vec::new());
216        };
217        match first {
218            Value::F32(_) => {
219                let mut bytes = Vec::with_capacity(s.values.len() * 4);
220                for v in &s.values {
221                    if let Value::F32(x) = v {
222                        bytes.extend_from_slice(&x.to_ne_bytes());
223                    }
224                }
225                Self::from_raw_bytes(s.timestamp, Format::Float32, Arc::from(bytes))
226            }
227            Value::F64(_) => {
228                let mut bytes = Vec::with_capacity(s.values.len() * 8);
229                for v in &s.values {
230                    if let Value::F64(x) = v {
231                        bytes.extend_from_slice(&x.to_ne_bytes());
232                    }
233                }
234                Self::from_raw_bytes(s.timestamp, Format::Double64, Arc::from(bytes))
235            }
236            Value::I32(_) => {
237                let mut bytes = Vec::with_capacity(s.values.len() * 4);
238                for v in &s.values {
239                    if let Value::I32(x) = v {
240                        bytes.extend_from_slice(&x.to_ne_bytes());
241                    }
242                }
243                Self::from_raw_bytes(s.timestamp, Format::Int32, Arc::from(bytes))
244            }
245            Value::I16(_) => {
246                let mut bytes = Vec::with_capacity(s.values.len() * 2);
247                for v in &s.values {
248                    if let Value::I16(x) = v {
249                        bytes.extend_from_slice(&x.to_ne_bytes());
250                    }
251                }
252                Self::from_raw_bytes(s.timestamp, Format::Int16, Arc::from(bytes))
253            }
254            Value::I8(_) => {
255                let mut bytes = Vec::with_capacity(s.values.len());
256                for v in &s.values {
257                    if let Value::I8(x) = v {
258                        bytes.push(*x as u8);
259                    }
260                }
261                Self::from_raw_bytes(s.timestamp, Format::Int8, Arc::from(bytes))
262            }
263            Value::I64(_) => {
264                let mut bytes = Vec::with_capacity(s.values.len() * 8);
265                for v in &s.values {
266                    if let Value::I64(x) = v {
267                        bytes.extend_from_slice(&x.to_ne_bytes());
268                    }
269                }
270                Self::from_raw_bytes(s.timestamp, Format::Int64, Arc::from(bytes))
271            }
272            Value::Str(_) => {
273                let strings: Vec<Vec<u8>> = s
274                    .values
275                    .iter()
276                    .map(|v| match v {
277                        Value::Str(b) => b.clone(),
278                        other => format!("{other:?}").into_bytes(),
279                    })
280                    .collect();
281                Self::from_strings(s.timestamp, strings)
282            }
283        }
284    }
285
286    /// Return a copy of this sample with a different timestamp, sharing the
287    /// underlying `Arc` payload with zero byte copies.
288    pub fn with_timestamp(&self, timestamp: f64) -> Self {
289        PackedSample {
290            timestamp,
291            values: self.values.clone(),
292        }
293    }
294
295    /// Number of channels held in this sample.
296    pub fn channel_count(&self) -> usize {
297        match &self.values {
298            PackedValues::Numeric { format, bytes } => {
299                format.width().map_or(0, |w| bytes.len() / w)
300            }
301            PackedValues::Strings(list) => list.len(),
302        }
303    }
304
305    /// Payload size in bytes, for bounded history accounting.
306    pub fn payload_bytes(&self) -> usize {
307        match &self.values {
308            PackedValues::Numeric { bytes, .. } => bytes.len(),
309            PackedValues::Strings(list) => list
310                .iter()
311                .map(|b| core::mem::size_of::<Vec<u8>>() + b.len())
312                .sum(),
313        }
314    }
315
316    /// Raw native-endian bytes when this sample holds numeric values in `expected` format.
317    pub fn as_numeric_bytes(&self, expected: Format) -> Option<&[u8]> {
318        match &self.values {
319            PackedValues::Numeric { format, bytes } if *format == expected => Some(bytes),
320            _ => None,
321        }
322    }
323
324    /// Append channel values into `dst` as `f32`, converting if the format differs.
325    pub fn push_into_f32(&self, dst: &mut Vec<f32>) {
326        if let Some(bytes) = self.as_numeric_bytes(Format::Float32) {
327            dst.reserve(bytes.len() / 4);
328            for c in bytes.chunks_exact(4) {
329                dst.push(f32::from_ne_bytes([c[0], c[1], c[2], c[3]]));
330            }
331            return;
332        }
333        for v in self.to_sample().values {
334            dst.push(match v {
335                Value::F32(x) => x,
336                Value::F64(x) => x as f32,
337                Value::I32(x) => x as f32,
338                Value::I16(x) => x as f32,
339                Value::I8(x) => x as f32,
340                Value::I64(x) => x as f32,
341                Value::Str(_) => 0.0,
342            });
343        }
344    }
345
346    /// Append channel values into `dst` as `f64`, converting if the format differs.
347    pub fn push_into_f64(&self, dst: &mut Vec<f64>) {
348        if let Some(bytes) = self.as_numeric_bytes(Format::Double64) {
349            dst.reserve(bytes.len() / 8);
350            for c in bytes.chunks_exact(8) {
351                dst.push(f64::from_ne_bytes([
352                    c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7],
353                ]));
354            }
355            return;
356        }
357        for v in self.to_sample().values {
358            dst.push(match v {
359                Value::F32(x) => x as f64,
360                Value::F64(x) => x,
361                Value::I32(x) => x as f64,
362                Value::I16(x) => x as f64,
363                Value::I8(x) => x as f64,
364                Value::I64(x) => x as f64,
365                Value::Str(_) => 0.0,
366            });
367        }
368    }
369
370    /// Append channel values into `dst` as `i32`, converting if the format differs.
371    pub fn push_into_i32(&self, dst: &mut Vec<i32>) {
372        if let Some(bytes) = self.as_numeric_bytes(Format::Int32) {
373            dst.reserve(bytes.len() / 4);
374            for c in bytes.chunks_exact(4) {
375                dst.push(i32::from_ne_bytes([c[0], c[1], c[2], c[3]]));
376            }
377            return;
378        }
379        for v in self.to_sample().values {
380            dst.push(match v {
381                Value::F32(x) => x as i32,
382                Value::F64(x) => x as i32,
383                Value::I32(x) => x,
384                Value::I16(x) => x as i32,
385                Value::I8(x) => x as i32,
386                Value::I64(x) => x as i32,
387                Value::Str(_) => 0,
388            });
389        }
390    }
391
392    /// Append channel values into `dst` as `i16`, converting if the format differs.
393    pub fn push_into_i16(&self, dst: &mut Vec<i16>) {
394        if let Some(bytes) = self.as_numeric_bytes(Format::Int16) {
395            dst.reserve(bytes.len() / 2);
396            for c in bytes.chunks_exact(2) {
397                dst.push(i16::from_ne_bytes([c[0], c[1]]));
398            }
399            return;
400        }
401        for v in self.to_sample().values {
402            dst.push(match v {
403                Value::F32(x) => x as i16,
404                Value::F64(x) => x as i16,
405                Value::I32(x) => x as i16,
406                Value::I16(x) => x,
407                Value::I8(x) => x as i16,
408                Value::I64(x) => x as i16,
409                Value::Str(_) => 0,
410            });
411        }
412    }
413
414    /// Append channel values into `dst` as `i8`, converting if the format differs.
415    pub fn push_into_i8(&self, dst: &mut Vec<i8>) {
416        if let Some(bytes) = self.as_numeric_bytes(Format::Int8) {
417            dst.reserve(bytes.len());
418            for &b in bytes {
419                dst.push(b as i8);
420            }
421            return;
422        }
423        for v in self.to_sample().values {
424            dst.push(match v {
425                Value::F32(x) => x as i8,
426                Value::F64(x) => x as i8,
427                Value::I32(x) => x as i8,
428                Value::I16(x) => x as i8,
429                Value::I8(x) => x,
430                Value::I64(x) => x as i8,
431                Value::Str(_) => 0,
432            });
433        }
434    }
435
436    /// Append channel values into `dst` as `i64`, converting if the format differs.
437    pub fn push_into_i64(&self, dst: &mut Vec<i64>) {
438        if let Some(bytes) = self.as_numeric_bytes(Format::Int64) {
439            dst.reserve(bytes.len() / 8);
440            for c in bytes.chunks_exact(8) {
441                dst.push(i64::from_ne_bytes([
442                    c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7],
443                ]));
444            }
445            return;
446        }
447        for v in self.to_sample().values {
448            dst.push(match v {
449                Value::F32(x) => x as i64,
450                Value::F64(x) => x as i64,
451                Value::I32(x) => x as i64,
452                Value::I16(x) => x as i64,
453                Value::I8(x) => x as i64,
454                Value::I64(x) => x,
455                Value::Str(_) => 0,
456            });
457        }
458    }
459
460    /// Expand this packed sample back into a [`Sample`] holding `Vec<Value>`.
461    pub fn to_sample(&self) -> Sample {
462        let values = match &self.values {
463            PackedValues::Numeric { format, bytes } => match format {
464                Format::Float32 => bytes
465                    .chunks_exact(4)
466                    .map(|c| Value::F32(f32::from_ne_bytes([c[0], c[1], c[2], c[3]])))
467                    .collect(),
468                Format::Double64 => bytes
469                    .chunks_exact(8)
470                    .map(|c| {
471                        Value::F64(f64::from_ne_bytes([
472                            c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7],
473                        ]))
474                    })
475                    .collect(),
476                Format::Int32 => bytes
477                    .chunks_exact(4)
478                    .map(|c| Value::I32(i32::from_ne_bytes([c[0], c[1], c[2], c[3]])))
479                    .collect(),
480                Format::Int16 => bytes
481                    .chunks_exact(2)
482                    .map(|c| Value::I16(i16::from_ne_bytes([c[0], c[1]])))
483                    .collect(),
484                Format::Int8 => bytes.iter().map(|&b| Value::I8(b as i8)).collect(),
485                Format::Int64 => bytes
486                    .chunks_exact(8)
487                    .map(|c| {
488                        Value::I64(i64::from_ne_bytes([
489                            c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7],
490                        ]))
491                    })
492                    .collect(),
493                Format::String | Format::Undefined => Vec::new(),
494            },
495            PackedValues::Strings(list) => list.iter().map(|b| Value::Str(b.clone())).collect(),
496        };
497        Sample {
498            timestamp: self.timestamp,
499            values,
500        }
501    }
502}
503
504impl From<&Sample> for PackedSample {
505    fn from(s: &Sample) -> Self {
506        PackedSample::from_sample(s)
507    }
508}
509
510impl From<Sample> for PackedSample {
511    fn from(s: Sample) -> Self {
512        PackedSample::from_sample(&s)
513    }
514}
515
516/// The byte order that a connection selected.
517#[derive(Debug, Clone, Copy, PartialEq, Eq)]
518pub enum ByteOrder {
519    /// Least significant byte first. liblsl writes `1234`.
520    Little,
521    /// Most significant byte first. liblsl writes `4321`.
522    Big,
523}
524
525impl ByteOrder {
526    /// The value that liblsl writes in the `Byte-Order` header. SPEC.md 4.6.
527    pub fn wire_value(self) -> i32 {
528        match self {
529            ByteOrder::Little => 1234,
530            ByteOrder::Big => 4321,
531        }
532    }
533
534    /// Read a byte order from a `Byte-Order` header value.
535    ///
536    /// A value of `0` means the native order of the reader. That case exists
537    /// for liblsl 1.13 and earlier (`src/data_receiver.cpp:231`).
538    pub fn from_wire(v: i32) -> Option<Self> {
539        match v {
540            1234 => Some(ByteOrder::Little),
541            4321 => Some(ByteOrder::Big),
542            0 => Some(ByteOrder::native()),
543            _ => None,
544        }
545    }
546
547    /// The byte order of this machine.
548    pub const fn native() -> Self {
549        if cfg!(target_endian = "little") {
550            ByteOrder::Little
551        } else {
552            ByteOrder::Big
553        }
554    }
555}
556
557/// Everything a codec call needs to know about the connection.
558#[derive(Debug, Clone, Copy)]
559pub struct Codec {
560    /// The format of every channel in the stream.
561    pub format: Format,
562    /// The number of channels in one sample.
563    pub channels: usize,
564    /// The byte order that the connection selected.
565    pub order: ByteOrder,
566    /// True when the reader clears subnormal values. SPEC.md 7.4.
567    pub suppress_subnormals: bool,
568}
569
570impl Codec {
571    /// Build a codec for a stream.
572    pub fn new(format: Format, channels: usize, order: ByteOrder) -> Self {
573        Codec {
574            format,
575            channels,
576            order,
577            suppress_subnormals: false,
578        }
579    }
580
581    /// Return a copy that clears subnormal values on read.
582    pub fn with_suppress_subnormals(mut self, on: bool) -> Self {
583        self.suppress_subnormals = on;
584        self
585    }
586
587    /// True when a value needs a byte swap.
588    ///
589    /// A value of one byte never needs one (`src/sample.cpp:219`).
590    fn swaps(&self) -> bool {
591        self.order != ByteOrder::native() && self.format.width().map_or(true, |w| w > 1)
592    }
593}
594
595/// A decode error.
596#[derive(Debug, Clone, PartialEq, Eq)]
597pub enum Error {
598    /// The buffer ended before the value did.
599    Truncated,
600    /// The tag byte was neither 1 nor 2.
601    BadTag(u8),
602    /// The width byte of a string length was not 1, 2, 4, or 8.
603    ///
604    /// liblsl reports `Stream contents corrupted (invalid varlen int).`
605    /// (`src/sample.cpp:256`).
606    BadLengthWidth(u8),
607    /// A string length did not fit in this platform's `usize`.
608    LengthTooLarge,
609    /// The codec holds a format that a stream never carries.
610    UndefinedFormat,
611    /// A value did not match the format of the codec.
612    FormatMismatch,
613    /// The sample held a different number of values than the codec expects.
614    ChannelCountMismatch {
615        /// The count that the codec expects.
616        expected: usize,
617        /// The count that the sample holds.
618        actual: usize,
619    },
620}
621
622impl fmt::Display for Error {
623    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
624        match self {
625            Error::Truncated => write!(f, "the buffer ended inside a value"),
626            Error::BadTag(t) => write!(f, "the tag byte {t} is not 1 or 2"),
627            Error::BadLengthWidth(w) => write!(f, "the length width {w} is not 1, 2, 4, or 8"),
628            Error::LengthTooLarge => write!(f, "the string length does not fit in usize"),
629            Error::UndefinedFormat => write!(f, "the format is undefined"),
630            Error::FormatMismatch => write!(f, "a value does not match the codec format"),
631            Error::ChannelCountMismatch { expected, actual } => {
632                write!(
633                    f,
634                    "the sample holds {actual} values and the codec expects {expected}"
635                )
636            }
637        }
638    }
639}
640
641impl std::error::Error for Error {}
642
643// ---------------------------------------------------------------------------
644// encode
645// ---------------------------------------------------------------------------
646
647macro_rules! put {
648    ($out:expr, $v:expr, $swap:expr) => {{
649        let b = if $swap {
650            $v.to_be_bytes()
651        } else {
652            $v.to_le_bytes()
653        };
654        $out.extend_from_slice(&b);
655    }};
656}
657
658impl Codec {
659    /// Write one sample to the end of `out`.
660    ///
661    /// The layout is the tag byte, then an optional timestamp, then one value
662    /// per channel. SPEC.md 7.1.
663    pub fn encode(&self, s: &Sample, out: &mut Vec<u8>) -> Result<(), Error> {
664        if self.format == Format::Undefined {
665            return Err(Error::UndefinedFormat);
666        }
667        if s.values.len() != self.channels {
668            return Err(Error::ChannelCountMismatch {
669                expected: self.channels,
670                actual: s.values.len(),
671            });
672        }
673
674        // A deduced timestamp writes the tag and nothing else.
675        if s.timestamp == DEDUCED_TIMESTAMP {
676            out.push(TAG_DEDUCED_TIMESTAMP);
677        } else {
678            out.push(TAG_TRANSMITTED_TIMESTAMP);
679            // The timestamp always swaps with the connection, because it is
680            // eight bytes wide. The format width does not apply to it.
681            let swap = self.order != ByteOrder::native();
682            put!(out, s.timestamp.to_bits(), swap);
683        }
684
685        let swap = self.swaps();
686        for v in &s.values {
687            match (self.format, v) {
688                (Format::Float32, Value::F32(x)) => put!(out, x.to_bits(), swap),
689                (Format::Double64, Value::F64(x)) => put!(out, x.to_bits(), swap),
690                (Format::Int32, Value::I32(x)) => put!(out, x, swap),
691                (Format::Int16, Value::I16(x)) => put!(out, x, swap),
692                (Format::Int8, Value::I8(x)) => out.push(*x as u8),
693                (Format::Int64, Value::I64(x)) => put!(out, x, swap),
694                (Format::String, Value::Str(b)) => {
695                    encode_string_len(b.len(), swap, out);
696                    out.extend_from_slice(b);
697                }
698                _ => return Err(Error::FormatMismatch),
699            }
700        }
701        Ok(())
702    }
703
704    /// Write one sample and return the bytes.
705    pub fn encode_to_vec(&self, s: &Sample) -> Result<Vec<u8>, Error> {
706        let mut v = Vec::new();
707        self.encode(s, &mut v)?;
708        Ok(v)
709    }
710
711    /// Write one [`PackedSample`] to the end of `out` using a single slice copy
712    /// on native byte order.
713    pub fn encode_packed(&self, s: &PackedSample, out: &mut Vec<u8>) -> Result<(), Error> {
714        self.encode_packed_at(s, s.timestamp, out)
715    }
716
717    /// Write one [`PackedSample`] with an explicit timestamp override, without
718    /// cloning the sample.
719    pub fn encode_packed_at(
720        &self,
721        s: &PackedSample,
722        timestamp: f64,
723        out: &mut Vec<u8>,
724    ) -> Result<(), Error> {
725        if self.format == Format::Undefined {
726            return Err(Error::UndefinedFormat);
727        }
728        let actual = s.channel_count();
729        if actual != self.channels {
730            return Err(Error::ChannelCountMismatch {
731                expected: self.channels,
732                actual,
733            });
734        }
735
736        if timestamp == DEDUCED_TIMESTAMP {
737            out.push(TAG_DEDUCED_TIMESTAMP);
738        } else {
739            out.push(TAG_TRANSMITTED_TIMESTAMP);
740            let swap = self.order != ByteOrder::native();
741            put!(out, timestamp.to_bits(), swap);
742        }
743
744        let swap = self.swaps();
745        match (self.format, &s.values) {
746            (
747                fmt,
748                PackedValues::Numeric {
749                    format: sfmt,
750                    bytes,
751                },
752            ) if fmt == *sfmt => {
753                if !swap {
754                    out.extend_from_slice(bytes);
755                } else {
756                    let w = fmt.width().unwrap_or(1);
757                    for chunk in bytes.chunks_exact(w) {
758                        for &b in chunk.iter().rev() {
759                            out.push(b);
760                        }
761                    }
762                }
763                Ok(())
764            }
765            (Format::String, PackedValues::Strings(list)) => {
766                for b in list.iter() {
767                    encode_string_len(b.len(), swap, out);
768                    out.extend_from_slice(b);
769                }
770                Ok(())
771            }
772            _ => Err(Error::FormatMismatch),
773        }
774    }
775}
776
777/// Write a string length as a width byte and then the length.
778///
779/// The encoder writes the widths 1, 4, and 8 only. It never writes 2. The
780/// decoder still accepts 2. SPEC.md 7.3 explains why that matters.
781fn encode_string_len(len: usize, swap: bool, out: &mut Vec<u8>) {
782    if len <= 0xFF {
783        out.push(1);
784        out.push(len as u8);
785    } else if len <= 0xFFFF_FFFF {
786        out.push(4);
787        put!(out, (len as u32), swap);
788    } else {
789        out.push(8);
790        put!(out, (len as u64), swap);
791    }
792}
793
794// ---------------------------------------------------------------------------
795// decode
796// ---------------------------------------------------------------------------
797
798/// A cursor over a byte slice.
799struct Reader<'a> {
800    buf: &'a [u8],
801    pos: usize,
802}
803
804impl<'a> Reader<'a> {
805    fn new(buf: &'a [u8]) -> Self {
806        Reader { buf, pos: 0 }
807    }
808
809    fn byte(&mut self) -> Result<u8, Error> {
810        let b = *self.buf.get(self.pos).ok_or(Error::Truncated)?;
811        self.pos += 1;
812        Ok(b)
813    }
814
815    fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
816        let end = self.pos.checked_add(n).ok_or(Error::Truncated)?;
817        let s = self.buf.get(self.pos..end).ok_or(Error::Truncated)?;
818        self.pos = end;
819        Ok(s)
820    }
821}
822
823macro_rules! get {
824    ($r:expr, $t:ty, $swap:expr) => {{
825        const N: usize = core::mem::size_of::<$t>();
826        let s = $r.take(N)?;
827        let mut a = [0u8; N];
828        a.copy_from_slice(s);
829        if $swap {
830            <$t>::from_be_bytes(a)
831        } else {
832            <$t>::from_le_bytes(a)
833        }
834    }};
835}
836
837impl Codec {
838    /// Read one sample from the start of `buf`.
839    ///
840    /// Returns the sample and the number of bytes that it used.
841    pub fn decode(&self, buf: &[u8]) -> Result<(Sample, usize), Error> {
842        if self.format == Format::Undefined {
843            return Err(Error::UndefinedFormat);
844        }
845        let mut r = Reader::new(buf);
846
847        let tag = r.byte()?;
848        let timestamp = match tag {
849            TAG_DEDUCED_TIMESTAMP => DEDUCED_TIMESTAMP,
850            TAG_TRANSMITTED_TIMESTAMP => {
851                let swap = self.order != ByteOrder::native();
852                f64::from_bits(get!(r, u64, swap))
853            }
854            other => return Err(Error::BadTag(other)),
855        };
856
857        let swap = self.swaps();
858        let mut values = Vec::with_capacity(self.channels);
859        for _ in 0..self.channels {
860            values.push(match self.format {
861                Format::Float32 => {
862                    let mut bits = get!(r, u32, swap);
863                    // Suppression runs after the byte order conversion.
864                    // SPEC.md 7.4, `src/sample.cpp:267-280`.
865                    if self.suppress_subnormals && bits != 0 && (bits & 0x7fff_ffff) <= 0x007f_ffff
866                    {
867                        bits &= 0x8000_0000;
868                    }
869                    Value::F32(f32::from_bits(bits))
870                }
871                Format::Double64 => {
872                    let mut bits = get!(r, u64, swap);
873                    if self.suppress_subnormals
874                        && bits != 0
875                        && (bits & 0x7fff_ffff_ffff_ffff) <= 0x000f_ffff_ffff_ffff
876                    {
877                        bits &= 0x8000_0000_0000_0000;
878                    }
879                    Value::F64(f64::from_bits(bits))
880                }
881                Format::Int32 => Value::I32(get!(r, i32, swap)),
882                Format::Int16 => Value::I16(get!(r, i16, swap)),
883                Format::Int8 => Value::I8(r.byte()? as i8),
884                Format::Int64 => Value::I64(get!(r, i64, swap)),
885                Format::String => {
886                    let len = decode_string_len(&mut r, swap)?;
887                    Value::Str(r.take(len)?.to_vec())
888                }
889                Format::Undefined => return Err(Error::UndefinedFormat),
890            });
891        }
892
893        Ok((Sample { timestamp, values }, r.pos))
894    }
895
896    /// Read one [`PackedSample`] directly from the start of `buf` without
897    /// allocating a `Vec<Value>`.
898    pub fn decode_packed(&self, buf: &[u8]) -> Result<(PackedSample, usize), Error> {
899        if self.format == Format::Undefined {
900            return Err(Error::UndefinedFormat);
901        }
902        let mut r = Reader::new(buf);
903
904        let tag = r.byte()?;
905        let timestamp = match tag {
906            TAG_DEDUCED_TIMESTAMP => DEDUCED_TIMESTAMP,
907            TAG_TRANSMITTED_TIMESTAMP => {
908                let swap = self.order != ByteOrder::native();
909                f64::from_bits(get!(r, u64, swap))
910            }
911            other => return Err(Error::BadTag(other)),
912        };
913
914        let swap = self.swaps();
915        if let Some(width) = self.format.width() {
916            let total = self.channels.checked_mul(width).ok_or(Error::Truncated)?;
917            let raw = r.take(total)?;
918            let bytes: Arc<[u8]> = if !swap
919                && (!self.suppress_subnormals || !self.format.is_float())
920            {
921                Arc::from(raw)
922            } else {
923                let mut out = Vec::with_capacity(total);
924                match self.format {
925                    Format::Float32 => {
926                        for c in raw.chunks_exact(4) {
927                            let mut bits = if swap {
928                                u32::from_be_bytes([c[0], c[1], c[2], c[3]])
929                            } else {
930                                u32::from_le_bytes([c[0], c[1], c[2], c[3]])
931                            };
932                            if self.suppress_subnormals
933                                && bits != 0
934                                && (bits & 0x7fff_ffff) <= 0x007f_ffff
935                            {
936                                bits &= 0x8000_0000;
937                            }
938                            out.extend_from_slice(&bits.to_ne_bytes());
939                        }
940                    }
941                    Format::Double64 => {
942                        for c in raw.chunks_exact(8) {
943                            let mut bits = if swap {
944                                u64::from_be_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]])
945                            } else {
946                                u64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]])
947                            };
948                            if self.suppress_subnormals
949                                && bits != 0
950                                && (bits & 0x7fff_ffff_ffff_ffff) <= 0x000f_ffff_ffff_ffff
951                            {
952                                bits &= 0x8000_0000_0000_0000;
953                            }
954                            out.extend_from_slice(&bits.to_ne_bytes());
955                        }
956                    }
957                    _ => {
958                        for chunk in raw.chunks_exact(width) {
959                            if swap {
960                                for &b in chunk.iter().rev() {
961                                    out.push(b);
962                                }
963                            } else {
964                                out.extend_from_slice(chunk);
965                            }
966                        }
967                    }
968                }
969                Arc::from(out)
970            };
971            return Ok((
972                PackedSample::from_raw_bytes(timestamp, self.format, bytes),
973                r.pos,
974            ));
975        }
976
977        let mut strings = Vec::with_capacity(self.channels);
978        for _ in 0..self.channels {
979            let len = decode_string_len(&mut r, swap)?;
980            strings.push(r.take(len)?.to_vec());
981        }
982        Ok((PackedSample::from_strings(timestamp, strings), r.pos))
983    }
984
985    /// Read as many whole samples as `buf` holds.
986    ///
987    /// Returns the samples and the number of bytes that they used. Trailing
988    /// bytes that do not form a whole sample stay unread.
989    pub fn decode_all(&self, buf: &[u8]) -> Result<(Vec<Sample>, usize), Error> {
990        let mut out = Vec::new();
991        let mut off = 0;
992        loop {
993            match self.decode(&buf[off..]) {
994                Ok((s, n)) => {
995                    out.push(s);
996                    off += n;
997                    if off >= buf.len() {
998                        break;
999                    }
1000                }
1001                Err(Error::Truncated) => break,
1002                Err(e) => return Err(e),
1003            }
1004        }
1005        Ok((out, off))
1006    }
1007}
1008
1009/// Read a string length: a width byte, then the length in that width.
1010///
1011/// The decoder accepts the width 2. No liblsl outlet writes it.
1012/// SPEC.md 7.3, `src/sample.cpp:251`.
1013fn decode_string_len(r: &mut Reader<'_>, swap: bool) -> Result<usize, Error> {
1014    let width = r.byte()?;
1015    let len: u64 = match width {
1016        1 => r.byte()? as u64,
1017        2 => get!(r, u16, swap) as u64,
1018        4 => get!(r, u32, swap) as u64,
1019        8 => get!(r, u64, swap),
1020        other => return Err(Error::BadLengthWidth(other)),
1021    };
1022    usize::try_from(len).map_err(|_| Error::LengthTooLarge)
1023}
1024
1025// ---------------------------------------------------------------------------
1026// the test pattern
1027// ---------------------------------------------------------------------------
1028
1029/// The timestamp that every test pattern sample carries.
1030///
1031/// `src/sample.cpp:366`.
1032pub const TEST_PATTERN_TIMESTAMP: f64 = 123456.789;
1033
1034/// The two offsets that a feed sends, in order. SPEC.md 6.1.
1035pub const TEST_PATTERN_OFFSETS: [i64; 2] = [4, 2];
1036
1037/// Build the test pattern sample that a feed sends.
1038///
1039/// A feed opens with two of these, at the offsets in `TEST_PATTERN_OFFSETS`.
1040/// An implementation that skips them loses the whole stream. SPEC.md 6.
1041pub fn test_pattern(format: Format, channels: usize, offset: i64) -> Sample {
1042    // The caller offset adds to a base that depends on the format.
1043    // `src/sample.cpp:368-400`.
1044    let base: i64 = match format {
1045        Format::Float32 => 0,
1046        Format::Double64 => 16_777_217,
1047        Format::Int32 => 65_537,
1048        Format::Int16 => 257,
1049        Format::Int8 => 1,
1050        Format::Int64 => 2_147_483_649,
1051        Format::String | Format::Undefined => 0,
1052    };
1053    let off = base + offset;
1054
1055    let values = (0..channels)
1056        .map(|k| {
1057            let k = k as i64;
1058            // A string channel ignores the offset (`src/sample.cpp:375-380`).
1059            if format == Format::String {
1060                let v = (k + 10) * if k % 2 == 0 { 1 } else { -1 };
1061                return Value::Str(v.to_string().into_bytes());
1062            }
1063            // liblsl computes `k + offset` in an unsigned type, takes it
1064            // modulo the type maximum for an integer format, and then applies
1065            // the sign (`src/sample.cpp:356-362`).
1066            let raw = (k as u64).wrapping_add(off as u64);
1067            let sign = k % 2 == 0;
1068            match format {
1069                Format::Float32 => {
1070                    let v = raw as f32;
1071                    Value::F32(if sign { v } else { -v })
1072                }
1073                Format::Double64 => {
1074                    let v = raw as f64;
1075                    Value::F64(if sign { v } else { -v })
1076                }
1077                Format::Int32 => {
1078                    let v = (raw % i32::MAX as u64) as i32;
1079                    Value::I32(if sign { v } else { -v })
1080                }
1081                Format::Int16 => {
1082                    let v = (raw % i16::MAX as u64) as i16;
1083                    Value::I16(if sign { v } else { -v })
1084                }
1085                Format::Int8 => {
1086                    let v = (raw % i8::MAX as u64) as i8;
1087                    Value::I8(if sign { v } else { -v })
1088                }
1089                Format::Int64 => {
1090                    let v = (raw % i64::MAX as u64) as i64;
1091                    Value::I64(if sign { v } else { -v })
1092                }
1093                Format::String | Format::Undefined => unreachable!(),
1094            }
1095        })
1096        .collect();
1097
1098    Sample {
1099        timestamp: TEST_PATTERN_TIMESTAMP,
1100        values,
1101    }
1102}
1103
1104// ---------------------------------------------------------------------------
1105// timestamp reconstruction
1106// ---------------------------------------------------------------------------
1107
1108/// Rebuilds a deduced timestamp from the position in the stream.
1109///
1110/// The accumulator runs for the life of the connection. Every deduced
1111/// timestamp depends on every sample before it. SPEC.md 8.1.
1112#[derive(Debug, Clone)]
1113pub struct TimestampDeducer {
1114    last: f64,
1115    srate: f64,
1116}
1117
1118impl TimestampDeducer {
1119    /// Build a deducer for a stream with the given nominal rate.
1120    ///
1121    /// liblsl starts the accumulator at `0.0` (`src/data_receiver.cpp:310`).
1122    pub fn new(srate: f64) -> Self {
1123        TimestampDeducer { last: 0.0, srate }
1124    }
1125
1126    /// Replace a deduced timestamp with a real one.
1127    pub fn apply(&mut self, timestamp: f64) -> f64 {
1128        let mut t = timestamp;
1129        if t == DEDUCED_TIMESTAMP {
1130            t = self.last;
1131            if self.srate != IRREGULAR_RATE {
1132                t += 1.0 / self.srate;
1133            }
1134        }
1135        self.last = t;
1136        t
1137    }
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142    use super::*;
1143
1144    fn rt(c: &Codec, s: &Sample) -> Sample {
1145        let b = c.encode_to_vec(s).unwrap();
1146        let (got, n) = c.decode(&b).unwrap();
1147        assert_eq!(n, b.len(), "decode did not use every byte");
1148        got
1149    }
1150
1151    #[test]
1152    fn deduced_tag_is_one_byte() {
1153        let c = Codec::new(Format::Float32, 2, ByteOrder::Little);
1154        let s = Sample {
1155            timestamp: DEDUCED_TIMESTAMP,
1156            values: vec![Value::F32(1.0), Value::F32(2.0)],
1157        };
1158        let b = c.encode_to_vec(&s).unwrap();
1159        assert_eq!(b[0], TAG_DEDUCED_TIMESTAMP);
1160        assert_eq!(b.len(), 1 + 8);
1161        assert_eq!(rt(&c, &s), s);
1162    }
1163
1164    #[test]
1165    fn transmitted_tag_carries_eight_bytes() {
1166        let c = Codec::new(Format::Int8, 1, ByteOrder::Little);
1167        let s = Sample {
1168            timestamp: 1.5,
1169            values: vec![Value::I8(-3)],
1170        };
1171        let b = c.encode_to_vec(&s).unwrap();
1172        assert_eq!(b[0], TAG_TRANSMITTED_TIMESTAMP);
1173        assert_eq!(b.len(), 1 + 8 + 1);
1174        assert_eq!(rt(&c, &s), s);
1175    }
1176
1177    #[test]
1178    fn string_width_boundaries() {
1179        let c = Codec::new(Format::String, 1, ByteOrder::Little);
1180        for (len, want_width) in [(0usize, 1u8), (255, 1), (256, 4), (257, 4)] {
1181            let s = Sample {
1182                timestamp: 0.0,
1183                values: vec![Value::Str(vec![b'x'; len])],
1184            };
1185            let b = c.encode_to_vec(&s).unwrap();
1186            assert_eq!(b[9], want_width, "length {len} picked the wrong width");
1187            assert_eq!(rt(&c, &s), s);
1188        }
1189    }
1190
1191    #[test]
1192    fn decoder_accepts_width_two_that_no_encoder_writes() {
1193        // SPEC.md 7.3. liblsl never writes this, and it always reads it.
1194        let c = Codec::new(Format::String, 1, ByteOrder::Little);
1195        let mut b = vec![TAG_TRANSMITTED_TIMESTAMP];
1196        b.extend_from_slice(&0.0f64.to_le_bytes());
1197        b.push(2);
1198        b.extend_from_slice(&3u16.to_le_bytes());
1199        b.extend_from_slice(b"abc");
1200        let (s, n) = c.decode(&b).unwrap();
1201        assert_eq!(n, b.len());
1202        assert_eq!(s.values, vec![Value::Str(b"abc".to_vec())]);
1203    }
1204
1205    #[test]
1206    fn bad_length_width_is_an_error() {
1207        let c = Codec::new(Format::String, 1, ByteOrder::Little);
1208        let mut b = vec![TAG_TRANSMITTED_TIMESTAMP];
1209        b.extend_from_slice(&0.0f64.to_le_bytes());
1210        b.push(3);
1211        assert_eq!(c.decode(&b), Err(Error::BadLengthWidth(3)));
1212    }
1213
1214    #[test]
1215    fn bad_tag_is_an_error() {
1216        let c = Codec::new(Format::Int8, 1, ByteOrder::Little);
1217        assert_eq!(c.decode(&[7, 0]), Err(Error::BadTag(7)));
1218    }
1219
1220    #[test]
1221    fn truncated_input_is_an_error() {
1222        let c = Codec::new(Format::Double64, 4, ByteOrder::Little);
1223        let b = vec![TAG_DEDUCED_TIMESTAMP, 0, 0, 0];
1224        assert_eq!(c.decode(&b), Err(Error::Truncated));
1225    }
1226
1227    #[test]
1228    fn nan_and_infinity_survive_a_round_trip() {
1229        let c = Codec::new(Format::Double64, 4, ByteOrder::Little);
1230        let s = Sample {
1231            timestamp: 0.0,
1232            values: vec![
1233                Value::F64(f64::INFINITY),
1234                Value::F64(f64::NEG_INFINITY),
1235                Value::F64(-0.0),
1236                Value::F64(f64::MIN_POSITIVE / 2.0),
1237            ],
1238        };
1239        let got = rt(&c, &s);
1240        assert_eq!(got, s);
1241        // -0.0 == 0.0 compares true, so compare the bits.
1242        if let (Value::F64(a), Value::F64(b)) = (&got.values[2], &s.values[2]) {
1243            assert_eq!(a.to_bits(), b.to_bits());
1244        }
1245    }
1246
1247    #[test]
1248    fn big_endian_differs_from_little_endian() {
1249        let le = Codec::new(Format::Int32, 1, ByteOrder::Little);
1250        let be = Codec::new(Format::Int32, 1, ByteOrder::Big);
1251        let s = Sample {
1252            timestamp: 0.0,
1253            values: vec![Value::I32(1)],
1254        };
1255        assert_ne!(le.encode_to_vec(&s).unwrap(), be.encode_to_vec(&s).unwrap());
1256        assert_eq!(be.decode(&be.encode_to_vec(&s).unwrap()).unwrap().0, s);
1257    }
1258
1259    #[test]
1260    fn int8_never_swaps() {
1261        let le = Codec::new(Format::Int8, 3, ByteOrder::Little);
1262        let be = Codec::new(Format::Int8, 3, ByteOrder::Big);
1263        let s = Sample {
1264            timestamp: DEDUCED_TIMESTAMP,
1265            values: vec![Value::I8(1), Value::I8(-2), Value::I8(3)],
1266        };
1267        assert_eq!(le.encode_to_vec(&s).unwrap(), be.encode_to_vec(&s).unwrap());
1268    }
1269
1270    #[test]
1271    fn subnormal_suppression_keeps_the_sign() {
1272        let c = Codec::new(Format::Float32, 2, ByteOrder::Little).with_suppress_subnormals(true);
1273        let plain = Codec::new(Format::Float32, 2, ByteOrder::Little);
1274        let s = Sample {
1275            timestamp: 0.0,
1276            values: vec![
1277                Value::F32(f32::from_bits(0x0000_0001)),
1278                Value::F32(f32::from_bits(0x8000_0001)),
1279            ],
1280        };
1281        let b = plain.encode_to_vec(&s).unwrap();
1282        let (got, _) = c.decode(&b).unwrap();
1283        assert_eq!(got.values[0], Value::F32(0.0));
1284        match got.values[1] {
1285            Value::F32(v) => assert_eq!(v.to_bits(), 0x8000_0000),
1286            _ => panic!("wrong format"),
1287        }
1288    }
1289
1290    #[test]
1291    fn channel_count_mismatch_is_an_error() {
1292        let c = Codec::new(Format::Int16, 4, ByteOrder::Little);
1293        let s = Sample {
1294            timestamp: 0.0,
1295            values: vec![Value::I16(1)],
1296        };
1297        assert_eq!(
1298            c.encode(&s, &mut Vec::new()),
1299            Err(Error::ChannelCountMismatch {
1300                expected: 4,
1301                actual: 1
1302            })
1303        );
1304    }
1305
1306    #[test]
1307    fn deducer_adds_one_period() {
1308        let mut d = TimestampDeducer::new(100.0);
1309        assert!((d.apply(DEDUCED_TIMESTAMP) - 0.01).abs() < 1e-12);
1310        assert!((d.apply(DEDUCED_TIMESTAMP) - 0.02).abs() < 1e-12);
1311        assert_eq!(d.apply(5.0), 5.0);
1312        assert!((d.apply(DEDUCED_TIMESTAMP) - 5.01).abs() < 1e-12);
1313    }
1314
1315    #[test]
1316    fn deducer_holds_the_value_for_an_irregular_rate() {
1317        let mut d = TimestampDeducer::new(IRREGULAR_RATE);
1318        assert_eq!(d.apply(DEDUCED_TIMESTAMP), 0.0);
1319        assert_eq!(d.apply(7.0), 7.0);
1320        assert_eq!(d.apply(DEDUCED_TIMESTAMP), 7.0);
1321    }
1322
1323    #[test]
1324    fn test_pattern_matches_the_captured_stream() {
1325        // From captures/feed.json. SPEC.md 6.4.
1326        let s = test_pattern(Format::Float32, 8, 4);
1327        assert_eq!(s.timestamp, TEST_PATTERN_TIMESTAMP);
1328        let want: Vec<f32> = vec![4.0, -5.0, 6.0, -7.0, 8.0, -9.0, 10.0, -11.0];
1329        let got: Vec<f32> = s
1330            .values
1331            .iter()
1332            .map(|v| match v {
1333                Value::F32(x) => *x,
1334                _ => panic!("wrong format"),
1335            })
1336            .collect();
1337        assert_eq!(got, want);
1338    }
1339
1340    #[test]
1341    fn packed_codec_matches_sample_codec_across_formats_and_endianness() {
1342        let cases = [
1343            (Format::Float32, test_pattern(Format::Float32, 8, 4)),
1344            (Format::Double64, test_pattern(Format::Double64, 4, 2)),
1345            (Format::Int32, test_pattern(Format::Int32, 6, 4)),
1346            (Format::Int16, test_pattern(Format::Int16, 6, 2)),
1347            (Format::Int8, test_pattern(Format::Int8, 6, 4)),
1348            (Format::Int64, test_pattern(Format::Int64, 4, 2)),
1349            (Format::String, test_pattern(Format::String, 3, 4)),
1350        ];
1351        for order in [ByteOrder::Little, ByteOrder::Big] {
1352            for suppress in [false, true] {
1353                for (fmt, sample) in &cases {
1354                    let codec = Codec::new(*fmt, sample.values.len(), order)
1355                        .with_suppress_subnormals(suppress);
1356                    let packed = PackedSample::from_sample(sample);
1357                    let mut wire_old = Vec::new();
1358                    let mut wire_new = Vec::new();
1359                    codec.encode(sample, &mut wire_old).unwrap();
1360                    codec.encode_packed(&packed, &mut wire_new).unwrap();
1361                    assert_eq!(wire_new, wire_old, "encode {fmt:?} {order:?}");
1362
1363                    let (dec_old, used_old) = codec.decode(&wire_old).unwrap();
1364                    let (dec_new, used_new) = codec.decode_packed(&wire_old).unwrap();
1365                    assert_eq!(used_new, used_old);
1366                    assert_eq!(dec_new.to_sample(), dec_old, "decode {fmt:?} {order:?}");
1367                }
1368            }
1369        }
1370    }
1371}