rustradio 0.16.8

Software defined radio library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
// Enable `std::simd` if feature simd is enabled.
#![cfg_attr(feature = "simd", feature(portable_simd))]
// Enable RISC-V arch detection, if on a RISC-V arch.
#![cfg_attr(
    all(
        feature = "simd",
        any(target_arch = "riscv32", target_arch = "riscv64")
    ),
    feature(stdarch_riscv_feature_detection)
)]
#![cfg_attr(coverage_nightly, feature(coverage_attribute))]

/*! This create provides a framework for running SDR (software defined
radio) applications.

It's heavily inspired by [GNURadio][gnuradio], except of course
written in Rust.

In addition to the example applications in this crate, there's also a
[sparslog][sparslog] project using this framework, that decodes IKEA
Sparsnäs electricity meter RF signals.

# Architecture overview

A RustRadio application consists of blocks that are connected by
unidirectional streams. Each block has zero or more input streams, and
zero or more output streams.

The signal flows through the blocks from "sources" (blocks without any
input streams) to "sinks" (blocks without any output streams.

These blocks and streams are called a "graph", like the mathematical
concept of graphs that have nodes and edges.

A block does something to its input(s), and passes the result to its
output(s).

A typical graph will be something like:

```text
  [ Raw radio source ]
           ↓
      [ Filtering ]
           ↓
      [ Resampling ]
           ↓
     [ Demodulation ]
           ↓
     [ Symbol Sync ]
           ↓
[ Packet assembly and save ]
```

Or concretely, for [sparslog][sparslog]:

```text
     [ RtlSdrSource ]
           ↓
  [ RtlSdrDecode to convert from ]
  [ own format to complex I/Q    ]
           ↓
     [ FftFilter ]
           ↓
      [ RationalResampler ]
           ↓
      [ QuadratureDemod ]
           ↓
  [ AddConst for frequency offset ]
           ↓
   [ ZeroCrossing symbol sync ]
           ↓
     [ Custom Sparsnäs decoder ]
     [ block in the binary,    ]
     [ not in the framework    ]
```

# Examples

Here's a simple example that creates a couple of blocks, connects them
with streams, and runs the graph.

```
use rustradio::graph::{Graph, GraphRunner};
use rustradio::blocks::{AddConst, VectorSource, DebugSink};
use rustradio::Complex;
let (src, prev) = VectorSource::new(
    vec![
        Complex::new(10.0, 0.0),
        Complex::new(-20.0, 0.0),
        Complex::new(100.0, -100.0),
    ],
);
let (add, prev) = AddConst::new(prev, Complex::new(1.1, 2.0));
let sink = DebugSink::new(prev);
let mut g = Graph::new();
g.add(Box::new(src));
g.add(Box::new(add));
g.add(Box::new(sink));
g.run()?;
# Ok::<(), anyhow::Error>(())
```

## Features

* `async`: Add support for `AsyncGraph`.
* `audio`: Add support for `AudioSink` (adds dependency).
* `fast-math`: Add a dependency in order to speed up some math.
* `fftw`: GPL code only: Add support to use `libfftw` instead of `rustfft`.
* `pipewire`: Add support for pipewire blocks (adds dependency).
* `rtlsdr`: Enable `RtlSdrSource` block, and adds the `rtlsdr` crate as a
* `simd` (only with `nightly` Rust): Enable some code using `std::simd`.
  dependency at build time, and thus `librtlsdr.so` as a dependency at runtime.
* `soapysdr`: Add dependency on `soapysdr`, for its various SDR support.
* `tokio-unstable`: For async graphs, allow use of tokio unstable API,
* `volk`: Add dependency on the `volk` library, to speed up some inner loops.
* `wasm`: Enable very experimental WASM support.

`tokio-unstable` allows tasks to be named, which helps when running
`tokio-console`. But it does require the user to run `cargo build` with the env
`RUSTFLAGS="--cfg tokio_unstable"` set too.

## Links

* Main repo: <https://github.com/ThomasHabets/rustradio>
* crates.io: <https://crates.io/crates/rustradio>
* This documentation: <https://docs.rs/rustradio/latest/rustradio/>

[sparslog]: https://github.com/ThomasHabets/sparslog
[gnuradio]: https://www.gnuradio.org/
 */
// Enable some normally pedantic clippies.
#![deny(clippy::needless_for_each)]
#![deny(clippy::explicit_iter_loop)]
#![deny(clippy::items_after_statements)]
#![deny(clippy::format_push_string)]
#![deny(clippy::return_self_not_must_use)]
// Macro.
pub use rustradio_macros;

// Blocks.
pub mod add;
pub mod add_const;
pub mod au;
pub mod binary_slicer;
pub mod burst_tagger;
pub mod canary;
pub mod cma;
pub mod complex_to_mag2;
pub mod constant_source;
pub mod convert;
pub mod correlate_access_code;
pub mod data_stream;
pub mod debug_sink;
pub mod delay;
pub mod descrambler;
pub mod fft;
pub mod fft_filter;
pub mod fft_stream;
pub mod file_sink;
pub mod file_source;
pub mod fir;
pub mod hasher;
pub mod hdlc_deframer;
pub mod hdlc_framer;
pub mod hilbert;
pub mod iir_filter;
pub mod il2p_deframer;
pub mod iq_balance;
pub mod kiss;
pub mod morse_encode;
pub mod multiply_const;
pub mod nrzi;
pub mod null_sink;
pub mod pdu_average;
pub mod pdu_to_stream;
pub mod pdu_writer;
pub mod quadrature_demod;
pub mod rational_resampler;
pub mod reader_source;
pub mod rtlsdr_decode;
pub mod rtlsdr_encode;
pub mod sigmf;
pub mod signal_source;
pub mod single_pole_iir_filter;
pub mod skip;
pub mod stream_to_pdu;
pub mod strobe;
pub mod symbol_sync;
pub mod tcp_source;
pub mod tee;
pub mod to_text;
pub mod vco;
pub mod vec_to_stream;
pub mod vector_sink;
pub mod vector_source;
pub mod wpcr;
pub mod writer_sink;
pub mod xor;
pub mod xor_const;
pub mod zero_crossing;

#[cfg(feature = "audio")]
pub mod audio_sink;

#[cfg(feature = "pipewire")]
pub mod pipewire_sink;

#[cfg(feature = "pipewire")]
pub mod pipewire_source;

#[cfg(feature = "rtlsdr")]
pub mod rtlsdr_source;

#[cfg(feature = "soapysdr")]
pub mod soapysdr_sink;

#[cfg(feature = "soapysdr")]
pub mod soapysdr_source;

pub mod block;
pub mod blocks;

#[cfg(not(feature = "wasm"))]
pub mod nowasm;

#[cfg(feature = "wasm")]
pub mod wasm;

pub mod sys {
    #[cfg(not(feature = "wasm"))]
    pub use super::nowasm::export::*;
    #[cfg(feature = "wasm")]
    pub use super::wasm::export::*;
}

pub mod graph;
#[cfg(not(feature = "wasm"))]
pub mod mtgraph;
pub mod stream;
pub mod window;

#[cfg(feature = "async")]
pub mod agraph;

/// Float type used. Usually f32, but not guaranteed.
pub type Float = f32;

/// Complex (I/Q) data.
pub type Complex = num_complex::Complex<Float>;

pub(crate) static NEXT_STREAM_ID: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(1);

/// RustRadio error.
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
    /// File error annotated with a specific path.
    #[error("IO Error on {path:?}: {source:?}")]
    FileIo {
        #[source]
        source: std::io::Error,
        path: std::path::PathBuf,
    },

    /// An error happened with a device such as SDR or audio device.
    #[error("DeviceError: {msg:?}: {source:?}")]
    DeviceError {
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
        msg: Option<String>,
    },

    /// An IO error without a known file associated.
    #[error("IO Error: {0}")]
    Io(#[from] std::io::Error),

    /// An error with only a plain text message.
    #[error("An error occurred: {0}")]
    Plain(String),

    /// A wrapper around another error.
    #[error("{msg:?}: {source:?}")]
    Other {
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
        msg: Option<String>,
    },
}

impl Error {
    /// Create error from message.
    #[must_use]
    pub fn msg<S: Into<String>>(msg: S) -> Self {
        Self::Plain(msg.into())
    }

    /// Wrap an IO error also including the path.
    #[must_use]
    pub fn file_io<P: Into<std::path::PathBuf>>(source: std::io::Error, path: P) -> Self {
        Self::FileIo {
            path: path.into(),
            source,
        }
    }

    /// Wrap another error into an `Error::Other`.
    ///
    /// The underlying error is provided, as well as optional extra context.
    #[must_use]
    pub fn wrap<S: Into<String>>(
        source: impl std::error::Error + Send + Sync + 'static,
        msg: S,
    ) -> Self {
        let msg = msg.into();
        Self::Other {
            source: Box::new(source),
            msg: if msg.is_empty() { None } else { Some(msg) },
        }
    }

    /// Wrap an error blaming some hardware or simulated hardware.
    ///
    /// The underlying error is provided, as well as optional extra context.
    #[must_use]
    pub fn device<S: Into<String>>(
        source: impl std::error::Error + Send + Sync + 'static,
        msg: S,
    ) -> Self {
        let msg = msg.into();
        Self::DeviceError {
            source: Box::new(source),
            msg: if msg.is_empty() { None } else { Some(msg) },
        }
    }

    /// Helper for `Other`.
    #[must_use]
    pub fn other<S: Into<String>>(
        source: impl std::error::Error + Send + Sync + 'static,
        msg: S,
    ) -> Self {
        let msg = msg.into();
        Self::Other {
            source: Box::new(source),
            msg: if msg.is_empty() { None } else { Some(msg) },
        }
    }
}

/// Create default `From<T>` for `Error`, with optional extra context.
///
/// ## Example
///
/// ```text
/// use rustradio::error_from;
/// error_from!(
///     "audio",
///     cpal::PlayStreamError,
///     cpal::BuildStreamError,
///     cpal::DevicesError,
///     cpal::DeviceNameError,
///     cpal::SupportedStreamConfigsError,
///     cpal::DefaultStreamConfigError,
/// );
/// ```
#[macro_export]
macro_rules! error_from {
    ($ctx:literal, $($err_ty:ty),* $(,)?) => {
        $(
            impl From<$err_ty> for Error {
                fn from(e: $err_ty) -> Self {
                    let s = if $ctx.is_empty() {
                        format!("{}", std::any::type_name::<$err_ty>())
                    } else {
                        format!("{} in {}", std::any::type_name::<$err_ty>(), $ctx)
                    };
                    Error::wrap(e, s)
                }
            }
        )*
    };
}

/// Helper macro for creating a series of one-in, one-out blocks and adding them
/// to a graph.
///
/// ## Example
///
/// ```
/// use rustradio::graph::{Graph, GraphRunner};
/// use rustradio::blocks::*;
/// use rustradio::blockchain;
///
/// let mut g = Graph::new();
/// let prev = blockchain![
///     g,      // Graph object.
///     prev,   // Variable to use for the streams from block to block.
///     SignalSourceFloat::new(44100.0, 1000.0, 1.0),
///     MultiplyConst::new(prev, 2.0),
///     MultiplyConst::new(prev, 4.0),
/// ];
/// ```
#[macro_export]
macro_rules! blockchain {
    ($g:expr, $prev:ident, $($cons:expr),* $(,)?) => {{
        $(
            let (block, $prev) = $cons;
            $g.add(Box::new(block));
            )*
            $prev
    }};
}

error_from!(
    "", // Can't attribute to a specific set of blocks.
    std::sync::mpsc::RecvError,
    std::sync::mpsc::TryRecvError,
    std::string::FromUtf8Error,
    std::array::TryFromSliceError,
    std::num::TryFromIntError,
);

/// Result convenience type.
pub type Result<T> = std::result::Result<T, Error>;

/// Repeat between zero and infinite times.
#[derive(Debug)]
pub struct Repeat {
    repeater: Repeater,
    count: u64,
}

impl Repeat {
    /// Repeat finite number of times. 0 Means not even once. 1 is default.
    #[must_use]
    pub fn finite(n: u64) -> Self {
        Self {
            repeater: Repeater::Finite(n),
            count: 0,
        }
    }

    /// Repeat infinite number of times.
    #[must_use]
    pub fn infinite() -> Self {
        Self {
            repeater: Repeater::Infinite,
            count: 0,
        }
    }

    /// Register a repeat being done, and return true if we should continue.
    #[must_use]
    pub fn again(&mut self) -> bool {
        self.count += 1;
        match self.repeater {
            Repeater::Finite(0) => {
                log::error!(
                    "Repeat::again() called when repeat is 0, count {}",
                    self.count
                );
                false
            }
            Repeater::Finite(n) => self.count < n,
            Repeater::Infinite => true,
        }
    }

    /// Return true if repeating is done.
    #[must_use]
    pub fn done(&self) -> bool {
        match self.repeater {
            Repeater::Finite(n) => self.count >= n,
            Repeater::Infinite => false,
        }
    }

    /// Return how many repeats have fully completed.
    #[must_use]
    pub fn count(&self) -> u64 {
        self.count
    }
}

#[derive(Debug)]
enum Repeater {
    Finite(u64),
    Infinite,
}

/// A CPU feature, such as `AVX` (x86) or `Vector` (RISC-V).
pub struct Feature {
    name: String,
    build: bool,
    detected: bool,
}

impl Feature {
    // Currently unused in WASM.
    #[must_use]
    #[allow(unused)]
    fn new<S: Into<String>>(name: S, build: bool, detected: bool) -> Self {
        Self {
            name: name.into(),
            build,
            detected,
        }
    }
}

/// Turn list of features into a nicely formatted table.
#[must_use]
pub fn environment_str(features: &[Feature]) -> String {
    use std::fmt::Write;
    let mut s = "Feature   Build Detected\n".to_string();
    for feature in features {
        let _ = writeln!(
            s,
            "{:10} {:-5}    {:-5}",
            feature.name, feature.build, feature.detected
        );
    }
    s
}

/// Check that the code wasn't built with features not detected at runtime.
///
/// This is a bigger problem than merely a runtime error would imply. If built
/// for features that are not here, that can only mean UB, before `main()` even
/// runs. So maybe this checking function doesn't actually add any value.
///
/// It does return the state of the features, though.
///
/// # Errors
///
/// If there are enabled processor features that are not supported. Though
/// again, this is UB.
pub fn check_environment() -> Result<Vec<Feature>> {
    #[allow(unused_mut)]
    let mut assumptions: Vec<Feature> = Vec::new();
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        assumptions.push(Feature::new(
            "FMA",
            cfg!(target_feature = "fma"),
            is_x86_feature_detected!("fma"),
        ));
        assumptions.push(Feature::new(
            "SSE",
            cfg!(target_feature = "sse"),
            is_x86_feature_detected!("sse"),
        ));
        assumptions.push(Feature::new(
            "SSE3",
            cfg!(target_feature = "sse3"),
            is_x86_feature_detected!("sse3"),
        ));
        assumptions.push(Feature::new(
            "AVX",
            cfg!(target_feature = "avx"),
            is_x86_feature_detected!("avx"),
        ));
        assumptions.push(Feature::new(
            "AVX2",
            cfg!(target_feature = "avx2"),
            is_x86_feature_detected!("avx2"),
        ));
    }

    // TODO: ideally we don't duplicate this test here, but reuse it from the
    // top of the file.
    //
    // We check for feature `simd` here as a substitute for checking we're on
    // nightly, where the feature stuff is allowed.
    #[cfg(all(
        feature = "simd",
        any(target_arch = "riscv32", target_arch = "riscv64")
    ))]
    {
        assumptions.push(Feature::new(
            "Vector",
            cfg!(target_feature = "v"),
            std::arch::is_riscv_feature_detected!("v"),
        ));
    }

    let errs: Vec<_> = assumptions
        .iter()
        .filter_map(|f| {
            if f.build && !f.detected {
                Some(format!(
                    "Feature {} assumed by build flags but not detected",
                    f.name
                ))
            } else {
                None
            }
        })
        .collect();
    if errs.is_empty() {
        Ok(assumptions)
    } else {
        Err(Error::msg(format!("{errs:?}")))
    }
}

/// Parse verbosity like "error", "warn", …
///
/// For use with clap. E.g.:
///
/// ```rust
/// use rustradio::parse_verbosity;
/// #[derive(clap::Parser)]
/// struct Opt {
///     #[arg(long, value_parser=parse_verbosity)]
///     verbose: usize,
/// }
/// ```
///
/// # Errors
///
/// If the log level is not one of the known strings.
pub fn parse_verbosity(in_s: &str) -> std::result::Result<usize, String> {
    use std::str::FromStr;
    log::Level::from_str(in_s)
        .map_err(|e| format!("{e}. Valid values are: error, warn, info, debug, trace"))
        .map(|v| v as usize - 1)
}

/// Parse frequencies like "100k", "2M", etc.
///
/// For use with clap. E.g.:
///
/// ```rust
/// use rustradio::parse_frequency;
/// #[derive(clap::Parser)]
/// struct Opt {
///     /// Frequency.
///     #[arg(long, value_parser=parse_frequency)]
///     freq: f64,
///     /// Sample rate.
///     #[arg(long, value_parser=parse_frequency, default_value_t = 300000.0)]
///     sample_rate: f64,
/// }
/// ```
///
/// Supported features:
/// * k/m/g suffix (case insensitive).
/// * underscores are stripped.
///
/// # Errors
///
/// If frequency string is not of a valid form.
pub fn parse_frequency(in_s: &str) -> std::result::Result<f64, String> {
    let s_binding;
    let s = if in_s.contains('_') {
        // Only create a copy if input actually contains underscores.
        s_binding = in_s.replace('_', "");
        s_binding.as_str()
    } else {
        in_s
    };
    let (nums, mul) = {
        let last = match s.chars().last() {
            None => return Err("empty string is not a frequency".into()),
            Some(ch) => ch.to_lowercase().next().ok_or("Empty string")?,
        };
        if s.len() > 1 {
            let rest = &s[..(s.len() - 1)];
            match last {
                'k' => (rest, 1_000.0),
                'm' => (rest, 1_000_000.0),
                'g' => (rest, 1_000_000_000.0),
                _ => (s, 1.0),
            }
        } else {
            (s, 1.0)
        }
    };
    Ok(nums.parse::<f64>().map_err(|e| {
        format!("Invalid number {in_s}: {e}. Has to be a float with optional k/m/g suffix")
    })? * mul)
}

/// A trait all sample types must implement.
pub trait Sample: Copy + Default + Send + Sync + 'static {
    /// The type of the sample.
    type Type;

    /// The serialized size of one sample.
    #[must_use]
    fn size() -> usize;

    /// Parse one sample.
    ///
    /// # Errors
    ///
    /// For the currently implemented Sample types, it can only fail if the
    /// passed byte slice is of the wrong size.
    fn parse(data: &[u8]) -> Result<Self::Type>;

    /// Serialize one sample.
    #[must_use]
    fn serialize(&self) -> Vec<u8>;
}

impl Sample for Complex {
    type Type = Complex;
    fn size() -> usize {
        std::mem::size_of::<Self>()
    }
    fn parse(data: &[u8]) -> Result<Self::Type> {
        if data.len() != Self::size() {
            return Err(Error::msg(format!(
                "Tried to parse Complex from {} bytes",
                data.len()
            )));
        }
        let i = Float::from_le_bytes(data[0..Self::size() / 2].try_into()?);
        let q = Float::from_le_bytes(data[Self::size() / 2..].try_into()?);
        Ok(Complex::new(i, q))
    }
    fn serialize(&self) -> Vec<u8> {
        let mut ret = Vec::new();
        ret.extend(Float::to_le_bytes(self.re));
        ret.extend(Float::to_le_bytes(self.im));
        ret
    }
}

impl Sample for Float {
    type Type = Float;
    fn size() -> usize {
        std::mem::size_of::<Self>()
    }
    fn parse(data: &[u8]) -> Result<Self::Type> {
        if data.len() != Self::size() {
            return Err(Error::msg(format!(
                "Tried to parse Float from {} bytes",
                data.len()
            )));
        }
        Ok(Float::from_le_bytes(data[0..Self::size()].try_into()?))
    }
    fn serialize(&self) -> Vec<u8> {
        Float::to_le_bytes(*self).to_vec()
    }
}

impl Sample for u8 {
    type Type = u8;
    fn size() -> usize {
        std::mem::size_of::<Self>()
    }
    fn parse(data: &[u8]) -> Result<Self::Type> {
        if data.len() != Self::size() {
            return Err(Error::msg(format!(
                "Tried to parse u8 from {} bytes",
                data.len()
            )));
        }
        Ok(data[0])
    }
    fn serialize(&self) -> Vec<u8> {
        vec![*self]
    }
}

impl Sample for u32 {
    type Type = u32;
    fn size() -> usize {
        4
    }
    fn parse(data: &[u8]) -> Result<Self::Type> {
        if data.len() != Self::size() {
            return Err(Error::msg(format!(
                "Tried to parse u32 from {} bytes",
                data.len()
            )));
        }
        Ok(u32::from_le_bytes(data[0..Self::size()].try_into()?))
    }
    fn serialize(&self) -> Vec<u8> {
        u32::to_le_bytes(*self).to_vec()
    }
}

impl Sample for i32 {
    type Type = i32;
    fn size() -> usize {
        std::mem::size_of::<Self>()
    }
    fn parse(data: &[u8]) -> Result<Self::Type> {
        if data.len() != Self::size() {
            return Err(Error::msg(format!(
                "Tried to parse i32 from {} bytes",
                data.len()
            )));
        }
        Ok(i32::from_le_bytes(data[0..Self::size()].try_into()?))
    }
    fn serialize(&self) -> Vec<u8> {
        i32::to_le_bytes(*self).to_vec()
    }
}

/// Trivial trait for types that have `.len()`.
#[allow(clippy::len_without_is_empty)]
pub trait Len {
    /// Get the length.
    #[must_use]
    fn len(&self) -> usize;
}
impl<T> Len for Vec<T> {
    fn len(&self) -> usize {
        self.len()
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
pub mod tests {
    //! Test helper functions.
    use super::*;

    /// For testing, assert that two slices are almost equal.
    ///
    /// Floating point numbers are almost never exactly equal.
    pub fn assert_almost_equal_complex(left: &[Complex], right: &[Complex]) {
        assert_eq!(
            left.len(),
            right.len(),
            "\nleft: {left:?}\nright: {right:?}",
        );
        for i in 0..left.len() {
            let dist = (left[i] - right[i]).norm_sqr().sqrt();
            if dist > 0.001 {
                assert_eq!(
                    left[i], right[i],
                    "\nElement {i}:\nleft: {left:?}\nright: {right:?}",
                );
            }
        }
    }

    /// For testing, assert that two slices are almost equal.
    ///
    /// Floating point numbers are almost never exactly equal.
    pub fn assert_almost_equal_float(left: &[Float], right: &[Float]) {
        assert_eq!(
            left.len(),
            right.len(),
            "\nleft: {left:?}\nright: {right:?}",
        );
        for i in 0..left.len() {
            let dist = (left[i] - right[i]).sqrt();
            if dist > 0.001 {
                assert_eq!(left[i], right[i], "\nleft: {left:?}\nright: {right:?}");
            }
        }
    }

    #[test]
    fn check_env() -> Result<()> {
        assert!(!environment_str(&check_environment()?).is_empty());
        Ok(())
    }

    #[test]
    fn error_wrap() {
        use std::error::Error as SysError;
        let e = Error::msg("foo");
        assert!(matches![e, Error::Plain(_)]);
        let _e2: &dyn std::error::Error = &e;
        let e_str = e.to_string();
        assert_eq!(e_str, "An error occurred: foo");
        let e3 = Error::wrap(e, "foo");
        assert!(matches![e3, Error::Other { source: _, msg: _ }]);
        let e4 = e3.source().unwrap();
        assert_eq!(e_str, e4.to_string());
        let e5 = e4.downcast_ref::<Error>().unwrap();
        assert!(matches![e5, Error::Plain(_)]);
    }

    #[test]
    fn frequency() {
        for (i, want) in &[
            ("", None),
            (".", None),
            ("k", None),
            ("r", None),
            (".k", None),
            ("0", Some(0.0f64)),
            ("0.", Some(0.0f64)),
            ("0.0", Some(0.0f64)),
            (".3", Some(0.3f64)),
            (".3k", Some(300.0f64)),
            ("3.k", Some(3_000.0f64)),
            ("100", Some(100.0)),
            ("123k", Some(123_000.0)),
            ("123kk", None),
            ("123.78922K", Some(123_789.22)),
            ("321m", Some(321_000_000.0)),
            ("2.45g", Some(2_450_000_000.0)),
            ("100r", None),
            ("r100", None),
            ("10k0", None),
            ("100_000", Some(100_000.0)),
            ("_1_2_3._4_", Some(123.4)),
        ] {
            let got = parse_frequency(i);
            match (got, want) {
                (Err(_), None) => {}
                (Ok(got), None) => panic!("For {i} got {got}, want error"),
                (Err(e), Some(want)) => panic!("For {i} got error {e:?}, want {want}"),
                (Ok(got), Some(want)) if got == *want => {}
                (Ok(got), Some(want)) => panic!("For {i} got {got} want {want}"),
            }
        }
    }

    #[test]
    fn repeat_test_infinite() {
        let mut r = Repeat::infinite();
        for n in 0..100 {
            assert_eq!(n, r.count());
            assert!(!r.done());
            assert!(r.again());
        }
    }

    #[test]
    fn repeat_test_none() {
        let mut r = Repeat::finite(0);
        assert_eq!(0, r.count());
        assert!(r.done());
        assert!(!r.again());
        assert_eq!(1, r.count());
        assert!(r.done());
        assert!(!r.again());
        assert_eq!(2, r.count());
    }

    #[test]
    fn repeat_test_one() {
        let mut r = Repeat::finite(1);
        assert_eq!(0, r.count());
        assert!(!r.done());

        assert!(!r.again());
        assert_eq!(1, r.count());
        assert!(r.done());

        assert!(!r.again());
        assert_eq!(2, r.count());
        assert!(r.done());
    }

    #[test]
    fn repeat_test_three() {
        let mut r = Repeat::finite(3);
        assert_eq!(0, r.count());
        assert!(!r.done());

        assert!(r.again());
        assert_eq!(1, r.count());
        assert!(!r.done());

        assert!(r.again());
        assert_eq!(2, r.count());
        assert!(!r.done());

        assert!(!r.again());
        assert_eq!(3, r.count());
        assert!(r.done());
    }
}