1#![forbid(unsafe_code)]
10#![deny(missing_docs)]
11
12use core::fmt;
13use std::sync::Arc;
14
15pub const TAG_DEDUCED_TIMESTAMP: u8 = 1;
17pub const TAG_TRANSMITTED_TIMESTAMP: u8 = 2;
19
20pub const DEDUCED_TIMESTAMP: f64 = -1.0;
24
25pub const IRREGULAR_RATE: f64 = 0.0;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32#[repr(u8)]
33pub enum Format {
34 Undefined = 0,
36 Float32 = 1,
38 Double64 = 2,
40 String = 3,
42 Int32 = 4,
44 Int16 = 5,
46 Int8 = 6,
48 Int64 = 7,
50}
51
52impl Format {
53 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 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 pub fn is_float(self) -> bool {
83 matches!(self, Format::Float32 | Format::Double64)
84 }
85}
86
87#[derive(Debug, Clone, PartialEq)]
89pub enum Value {
90 F32(f32),
92 F64(f64),
94 Str(Vec<u8>),
96 I32(i32),
98 I16(i16),
100 I8(i8),
102 I64(i64),
104}
105
106#[derive(Debug, Clone, PartialEq)]
108pub struct Sample {
109 pub timestamp: f64,
111 pub values: Vec<Value>,
113}
114
115#[derive(Debug, Clone, PartialEq)]
123pub enum PackedValues {
124 Numeric {
126 format: Format,
128 bytes: Arc<[u8]>,
130 },
131 Strings(Arc<[Vec<u8>]>),
133}
134
135#[derive(Debug, Clone, PartialEq)]
137pub struct PackedSample {
138 pub timestamp: f64,
140 pub values: PackedValues,
142}
143
144impl PackedSample {
145 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 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 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 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 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 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 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 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 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 pub fn with_timestamp(&self, timestamp: f64) -> Self {
289 PackedSample {
290 timestamp,
291 values: self.values.clone(),
292 }
293 }
294
295 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 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 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 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 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 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
518pub enum ByteOrder {
519 Little,
521 Big,
523}
524
525impl ByteOrder {
526 pub fn wire_value(self) -> i32 {
528 match self {
529 ByteOrder::Little => 1234,
530 ByteOrder::Big => 4321,
531 }
532 }
533
534 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 pub const fn native() -> Self {
549 if cfg!(target_endian = "little") {
550 ByteOrder::Little
551 } else {
552 ByteOrder::Big
553 }
554 }
555}
556
557#[derive(Debug, Clone, Copy)]
559pub struct Codec {
560 pub format: Format,
562 pub channels: usize,
564 pub order: ByteOrder,
566 pub suppress_subnormals: bool,
568}
569
570impl Codec {
571 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 pub fn with_suppress_subnormals(mut self, on: bool) -> Self {
583 self.suppress_subnormals = on;
584 self
585 }
586
587 fn swaps(&self) -> bool {
591 self.order != ByteOrder::native() && self.format.width().map_or(true, |w| w > 1)
592 }
593}
594
595#[derive(Debug, Clone, PartialEq, Eq)]
597pub enum Error {
598 Truncated,
600 BadTag(u8),
602 BadLengthWidth(u8),
607 LengthTooLarge,
609 UndefinedFormat,
611 FormatMismatch,
613 ChannelCountMismatch {
615 expected: usize,
617 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
643macro_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 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 if s.timestamp == DEDUCED_TIMESTAMP {
676 out.push(TAG_DEDUCED_TIMESTAMP);
677 } else {
678 out.push(TAG_TRANSMITTED_TIMESTAMP);
679 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 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 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 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
777fn 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
794struct 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 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 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 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 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
1009fn 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
1025pub const TEST_PATTERN_TIMESTAMP: f64 = 123456.789;
1033
1034pub const TEST_PATTERN_OFFSETS: [i64; 2] = [4, 2];
1036
1037pub fn test_pattern(format: Format, channels: usize, offset: i64) -> Sample {
1042 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 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 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#[derive(Debug, Clone)]
1113pub struct TimestampDeducer {
1114 last: f64,
1115 srate: f64,
1116}
1117
1118impl TimestampDeducer {
1119 pub fn new(srate: f64) -> Self {
1123 TimestampDeducer { last: 0.0, srate }
1124 }
1125
1126 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 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 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 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}