Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • master
1 result

Target

Select target project
No results found
Select Git revision
  • master
1 result
Show changes

Commits on Source 48

28 files
+ 2614
212
Compare changes
  • Side-by-side
  • Inline

Files

.gitlab-ci.yml

0 → 100644
+11 −0
Original line number Original line Diff line number Diff line
image: "rust:latest"

before_script:
  - rustup component add rustfmt
  - rustup component add clippy

test:
  script:
    - cargo fmt -- --check
    - cargo clippy --all-targets --all-features -- -D warnings
    - cargo test
+7 −5
Original line number Original line Diff line number Diff line
[package]
[package]
name = "ham-cats"
name = "ham-cats"
version = "0.1.0"
version = "0.2.2"
edition = "2021"
edition = "2021"
license = "MIT"
license = "MIT"

description = "Reference implementations for CATS, the ham radio protocol"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
repository = "https://gitlab.scd31.com/cats/ham_cats"
homepage = "https://cats.radio"
categories = ["embedded", "encoding", "no-std", "no-std::no-alloc"]


[dependencies]
[dependencies]
arrayvec = { version = "0.7.4", default-features = false }
arrayvec = { version = "0.7.4", default-features = false }
@@ -12,6 +14,6 @@ bitvec = { version = "1.0.1", default-features = false }
crc = "3.0.1"
crc = "3.0.1"
encoding_rs = { version = "0.8.33", default-features = false }
encoding_rs = { version = "0.8.33", default-features = false }
half = { version = "2.3.1", default-features = false }
half = { version = "2.3.1", default-features = false }
labrador-ldpc = "1.1"
labrador-ldpc = "1.2.1"
paste = "1.0.14"
paste = "1.0.14"
snafu = "0.7.5"
snafu = { version = "0.7.5", default-features = false }

LICENSE.md

0 → 100644
+26 −0
Original line number Original line Diff line number Diff line
The MIT License (MIT)
=====================

Copyright © 2023 CATS

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

fuzz/.gitignore

0 → 100644
+3 −0
Original line number Original line Diff line number Diff line
target
corpus
artifacts

fuzz/Cargo.lock

0 → 100644
+243 −0
Original line number Original line Diff line number Diff line
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3

[[package]]
name = "arbitrary"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2d098ff73c1ca148721f37baad5ea6a465a13f9573aba8641fbbbae8164a54e"

[[package]]
name = "arrayvec"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711"

[[package]]
name = "bitvec"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c"
dependencies = [
 "funty",
 "radium",
 "tap",
 "wyz",
]

[[package]]
name = "cc"
version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0"
dependencies = [
 "jobserver",
 "libc",
]

[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"

[[package]]
name = "crc"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86ec7a15cbe22e59248fc7eadb1907dab5ba09372595da4d73dd805ed4417dfe"
dependencies = [
 "crc-catalog",
]

[[package]]
name = "crc-catalog"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cace84e55f07e7301bae1c519df89cdad8cc3cd868413d3fdbdeca9ff3db484"

[[package]]
name = "crunchy"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7"

[[package]]
name = "doc-comment"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10"

[[package]]
name = "encoding_rs"
version = "0.8.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1"
dependencies = [
 "cfg-if",
]

[[package]]
name = "funty"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"

[[package]]
name = "half"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc52e53916c08643f1b56ec082790d1e86a32e58dc5268f897f313fbae7b4872"
dependencies = [
 "cfg-if",
 "crunchy",
]

[[package]]
name = "ham-cats"
version = "0.2.0"
dependencies = [
 "arrayvec",
 "bitvec",
 "crc",
 "encoding_rs",
 "half",
 "labrador-ldpc",
 "paste",
 "snafu",
]

[[package]]
name = "ham-cats-fuzz"
version = "0.0.0"
dependencies = [
 "ham-cats",
 "libfuzzer-sys",
]

[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"

[[package]]
name = "jobserver"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "936cfd212a0155903bcbc060e316fb6cc7cbf2e1907329391ebadc1fe0ce77c2"
dependencies = [
 "libc",
]

[[package]]
name = "labrador-ldpc"
version = "1.1.1"

[[package]]
name = "libc"
version = "0.2.148"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cdc71e17332e86d2e1d38c1f99edcb6288ee11b815fb1a4b049eaa2114d369b"

[[package]]
name = "libfuzzer-sys"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a96cfd5557eb82f2b83fed4955246c988d331975a002961b07c81584d107e7f7"
dependencies = [
 "arbitrary",
 "cc",
 "once_cell",
]

[[package]]
name = "once_cell"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"

[[package]]
name = "paste"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"

[[package]]
name = "proc-macro2"
version = "1.0.67"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d433d9f1a3e8c1263d9456598b16fec66f4acc9a74dacffd35c7bb09b3a1328"
dependencies = [
 "unicode-ident",
]

[[package]]
name = "quote"
version = "1.0.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
dependencies = [
 "proc-macro2",
]

[[package]]
name = "radium"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"

[[package]]
name = "snafu"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4de37ad025c587a29e8f3f5605c00f70b98715ef90b9061a815b9e59e9042d6"
dependencies = [
 "doc-comment",
 "snafu-derive",
]

[[package]]
name = "snafu-derive"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "990079665f075b699031e9c08fd3ab99be5029b96f3b78dc0709e8f77e4efebf"
dependencies = [
 "heck",
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "tap"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"

[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"

[[package]]
name = "wyz"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed"
dependencies = [
 "tap",
]

fuzz/Cargo.toml

0 → 100644
+43 −0
Original line number Original line Diff line number Diff line
[package]
name = "ham-cats-fuzz"
version = "0.0.0"
authors = ["Automatically generated"]
publish = false
edition = "2018"

[package.metadata]
cargo-fuzz = true

[dependencies]
libfuzzer-sys = "0.4"

[dependencies.ham-cats]
path = ".."

# Prevent this from interfering with workspaces
[workspace]
members = ["."]

[[bin]]
name = "fuzz_target_1"
path = "fuzz_targets/fuzz_target_1.rs"
test = false
doc = false

[[bin]]
name = "fuzz_target_2"
path = "fuzz_targets/fuzz_target_2.rs"
test = false
doc = false

[[bin]]
name = "fuzz_target_3"
path = "fuzz_targets/fuzz_target_3.rs"
test = false
doc = false

[[bin]]
name = "fuzz_target_4"
path = "fuzz_targets/fuzz_target_4.rs"
test = false
doc = false
+10 −0
Original line number Original line Diff line number Diff line
#![no_main]
use libfuzzer_sys::fuzz_target;

use ham_cats::packet::Packet;

fuzz_target!(|data: &[u8]| {
    let mut buf = [0; 1024];

    let _ = Packet::<1024>::fully_decode(data, &mut buf);
});
+12 −0
Original line number Original line Diff line number Diff line
#![no_main]
use libfuzzer_sys::fuzz_target;

use ham_cats::{buffer::Buffer, packet::Packet};

fuzz_target!(|data: &[u8]| {
    let mut buf = [0; 1024];
    let mut buf = Buffer::new_empty(&mut buf);
    if buf.try_extend_from_slice(data).is_ok() {
        let _ = Packet::<1024>::semi_decode(buf);
    }
});
+12 −0
Original line number Original line Diff line number Diff line
#![no_main]
use libfuzzer_sys::fuzz_target;

use ham_cats::{buffer::Buffer, packet::Packet};

fuzz_target!(|data: &[u8]| {
    let mut buf = [0; 1024];
    let mut buf = Buffer::new_empty(&mut buf);
    if buf.try_extend_from_slice(data).is_ok() {
        let _ = Packet::<1024>::decode(buf);
    }
});
+16 −0
Original line number Original line Diff line number Diff line
#![no_main]
use libfuzzer_sys::fuzz_target;

use ham_cats::packet::Packet;
use std::convert::TryInto;

fuzz_target!(|data: &[u8]| {
    // [u8] -> [i8]
    let mut data: Vec<_> = data
        .iter()
        .map(|x| (u16::from(*x) as i16 - 128).try_into().unwrap())
        .collect();

    let mut buf = [0; 1024];
    let _ = Packet::<1024>::fully_decode_soft::<8192, i8>(&mut data, &mut buf);
});

src/buffer.rs

0 → 100644
+122 −0
Original line number Original line Diff line number Diff line
use core::ops::{Deref, DerefMut};

#[derive(Debug)]
pub struct BufferOverflow;

#[derive(Debug)]
pub struct Buffer<'a, const N: usize, T = u8> {
    data: &'a mut [T; N],
    i: usize,
}

impl<'a, const N: usize, T: Copy> Buffer<'a, N, T> {
    /// Constructs a new `Buffer`.
    /// `data` is the backing array.
    /// `i` is the number of elements in `data` that contain data (and should thus be exposed by `Buffer`)
    pub fn new(data: &'a mut [T; N], i: usize) -> Self {
        assert!(i <= data.len());

        Self { data, i }
    }

    pub fn new_full(data: &'a mut [T; N]) -> Self {
        let i = data.len();

        Self::new(data, i)
    }

    pub fn new_empty(data: &'a mut [T; N]) -> Self {
        Self::new(data, 0)
    }

    pub const fn remaining_capacity(&self) -> usize {
        N - self.i
    }

    pub fn try_push(&mut self, v: T) -> Result<(), BufferOverflow> {
        if self.i == N {
            return Err(BufferOverflow);
        }

        self.data[self.i] = v;
        self.i += 1;

        Ok(())
    }

    pub fn push(&mut self, v: T) {
        self.try_push(v).unwrap();
    }

    pub fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), BufferOverflow> {
        if self.remaining_capacity() < other.len() {
            return Err(BufferOverflow);
        }

        self.data[self.i..(self.i + other.len())].copy_from_slice(other);
        self.i += other.len();

        Ok(())
    }

    pub fn extend(&mut self, other: &[T]) {
        self.try_extend_from_slice(other).unwrap();
    }

    pub fn pop(&mut self) -> Option<T> {
        if self.i == 0 {
            return None;
        }

        self.i -= 1;

        Some(self.data[self.i])
    }

    pub fn truncate(&mut self, new_len: usize) {
        assert!(self.i >= new_len);

        self.i = new_len;
    }

    pub fn drain(&mut self, start: usize, end: usize) {
        assert!(end >= start);
        assert!(end <= self.i);
        let delta = end - start;
        let surplus = self.len() - end;

        for i in start..(start + surplus) {
            self[i] = self[i + delta];
        }

        self.i -= delta;
    }

    pub fn clone_backing<'b>(&self, buf: &'b mut [T; N]) -> Buffer<'b, N, T> {
        let mut out = Buffer::new_empty(buf);

        out.extend(self);

        out
    }
}

impl<'a, const N: usize, T> From<&'a mut [T; N]> for Buffer<'a, N, T> {
    fn from(data: &'a mut [T; N]) -> Self {
        Self { data, i: 0 }
    }
}

impl<const N: usize, T> Deref for Buffer<'_, N, T> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        &self.data[..self.i]
    }
}

impl<const N: usize, T> DerefMut for Buffer<'_, N, T> {
    fn deref_mut(&mut self) -> &mut [T] {
        &mut self.data[..self.i]
    }
}
+48 −0
Original line number Original line Diff line number Diff line
@@ -19,6 +19,9 @@ pub enum DecodeError {


    #[snafu(display("LDPC Decode error"))]
    #[snafu(display("LDPC Decode error"))]
    LdpcError,
    LdpcError,

    #[snafu(display("Given data does not fit in the CATS packet"))]
    Overflow,
}
}


#[derive(Debug, Snafu)]
#[derive(Debug, Snafu)]
@@ -38,3 +41,48 @@ pub enum CommentError {
    #[snafu(display("Given buffer too small for comment data"))]
    #[snafu(display("Given buffer too small for comment data"))]
    BufferOverflow,
    BufferOverflow,
}
}

#[derive(Debug, Snafu)]
pub enum DigipeatError {
    #[snafu(display("No route"))]
    NoRoute,

    #[snafu(display("Identification is us"))]
    Us,

    #[snafu(display("Max hops hit"))]
    MaxHops,

    #[snafu(display("Already digipeated by this node"))]
    AlreadyDigipeated,

    #[snafu(display("Future hop(s) are already set"))]
    SetDestiny,
}

#[derive(Debug, Snafu, PartialEq, Eq)]
pub enum AppendNodeError {
    #[snafu(display("Future hop(s) already set to a different node"))]
    SetFuture,

    #[snafu(display("Max hops hit"))]
    HopsOverflow,

    #[snafu(display("Node already in route"))]
    DuplicateNode,

    #[snafu(display("Given data causes the route whisker to overflow"))]
    RouteOverflow,
}

#[derive(Debug, Snafu, PartialEq, Eq)]
pub enum PacketRouteAppendError {
    #[snafu(display("No route whisker on packet"))]
    NoRouteWhisker,

    #[snafu(display("Route error"))]
    Route { error: AppendNodeError },

    #[snafu(display("CATS packet overflow"))]
    PacketOverflow,
}

src/identity.rs

0 → 100644
+19 −0
Original line number Original line Diff line number Diff line
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct Identity<'a> {
    callsign: &'a str,
    ssid: u8,
}

impl<'a> Identity<'a> {
    pub fn new(callsign: &'a str, ssid: u8) -> Self {
        Self { callsign, ssid }
    }

    pub fn callsign(&self) -> &'a str {
        self.callsign
    }

    pub fn ssid(&self) -> u8 {
        self.ssid
    }
}
+88 −16
Original line number Original line Diff line number Diff line
use arrayvec::ArrayVec;
use bitvec::prelude::*;
use bitvec::prelude::*;
use labrador_ldpc::decoder::DecodeFrom;


pub(crate) fn interleave<const N: usize>(data: &ArrayVec<u8, N>) -> ArrayVec<u8, N> {
use crate::{
    buffer::{Buffer, BufferOverflow},
    error::EncodeError,
};

pub(crate) fn interleave<const N: usize>(
    data: &[u8],
    out: &mut Buffer<N>,
) -> Result<(), EncodeError> {
    let bv = data.view_bits::<Msb0>();
    let bv = data.view_bits::<Msb0>();


    let mut out: ArrayVec<u8, N> = ArrayVec::new();
    let initial_length = out.len();
    for _ in 0..data.len() {
    for _ in 0..data.len() {
        out.push(0);
        out.try_push(0).map_err(|_| EncodeError::CatsOverflow)?;
    }
    }
    let bv_out = out.view_bits_mut::<Msb0>();
    let bv_out = out[initial_length..].view_bits_mut::<Msb0>();


    let mut out_i = 0;
    let mut out_i = 0;
    for i in 0..32 {
    for i in 0..32 {
@@ -23,15 +31,17 @@ pub(crate) fn interleave<const N: usize>(data: &ArrayVec<u8, N>) -> ArrayVec<u8,
        }
        }
    }
    }


    out
    Ok(())
}
}


pub(crate) fn uninterleave<const N: usize>(data: &ArrayVec<u8, N>) -> ArrayVec<u8, N> {
pub(crate) fn uninterleave<const N: usize>(
    data: &[u8],
    out: &mut Buffer<N>,
) -> Result<(), BufferOverflow> {
    let bv = data.view_bits::<Msb0>();
    let bv = data.view_bits::<Msb0>();


    let mut out: ArrayVec<u8, N> = ArrayVec::new();
    for _ in 0..data.len() {
    for _ in 0..data.len() {
        out.push(0);
        out.try_push(0)?;
    }
    }
    let bv_out = out.view_bits_mut::<Msb0>();
    let bv_out = out.view_bits_mut::<Msb0>();


@@ -48,24 +58,86 @@ pub(crate) fn uninterleave<const N: usize>(data: &ArrayVec<u8, N>) -> ArrayVec<u
        }
        }
    }
    }


    out
    Ok(())
}

pub(crate) fn uninterleave_soft<const N: usize, T: DecodeFrom>(
    data: &[T],
    out: &mut Buffer<N, T>,
) -> Result<(), BufferOverflow> {
    for _ in 0..data.len() {
        out.try_push(T::zero())?;
    }

    let mut out_i = 0;
    for i in 0..32 {
        for j in (0..data.len()).step_by(32) {
            if i + j >= data.len() {
                continue;
            }

            out[i + j] = data[out_i];

            out_i += 1;
        }
    }

    Ok(())
}
}


#[cfg(test)]
#[cfg(test)]
mod tests {
mod tests {
    use super::*;
    use super::*;
    use crate::soft_bit::FromHardBit;


    #[test]
    #[test]
    fn interleaver_works() {
    fn interleaver_works() {
        let orig =
        let mut data = [0x84, 0x73, 0x12, 0xA3, 0xFF, 0x00, 0xC2, 0x1B, 0x77];
            ArrayVec::try_from([0x84, 0x73, 0x12, 0xA3, 0xFF, 0x00, 0xC2, 0x1B, 0x77]).unwrap();
        let orig = Buffer::new_full(&mut data);
        let interleaved = interleave(&orig);

        let mut interleaved = [0; 10];
        let mut interleaved = Buffer::new(&mut interleaved, 0);
        interleaved.push(b'H');


        let expected = [0xCD, 0xB5, 0xDB, 0x2A, 0x0A, 0x52, 0x0C, 0x89, 0x4F];
        interleave(&orig, &mut interleaved).unwrap();

        let expected = [b'H', 0xCD, 0xB5, 0xDB, 0x2A, 0x0A, 0x52, 0x0C, 0x89, 0x4F];
        assert_eq!(expected, interleaved[..]);
        assert_eq!(expected, interleaved[..]);


        let uninterleaved = uninterleave(&interleaved);
        let mut uninterleaved = [0; 10];
        let mut uninterleaved = Buffer::new(&mut uninterleaved, 0);
        uninterleave(&interleaved[1..], &mut uninterleaved).unwrap();

        assert_eq!(*orig, *uninterleaved);
    }

    #[test]
    fn hard_interleave_soft_uninterleave() {
        let mut data = [0x84, 0x73, 0x12, 0xA3, 0xFF, 0x00, 0xC2, 0x1B, 0x77];
        let orig = Buffer::new_full(&mut data);

        let mut interleaved = [0; 10];
        let mut interleaved = Buffer::new(&mut interleaved, 0);
        interleaved.push(b'H');


        assert_eq!(orig, uninterleaved);
        interleave(&orig, &mut interleaved).unwrap();

        let mut soft_interleaved = [0.0; 10 * 8];
        for (i, b) in interleaved.iter().enumerate() {
            for j in 0..8 {
                soft_interleaved[8 * i + j] = f32::from_hard_bit(b & (1 << (7 - j)) > 0);
            }
        }

        let mut uninterleaved = [0.0; 10 * 8];
        let mut uninterleaved = Buffer::new(&mut uninterleaved, 0);
        uninterleave_soft(&soft_interleaved[8..], &mut uninterleaved).unwrap();

        assert_eq!(orig.len() * 8, uninterleaved.len());
        for (i, b) in orig.iter().enumerate() {
            for j in 0..8 {
                assert_eq!(uninterleaved[8 * i + j].hard_bit(), *b & (1 << (7 - j)) > 0);
            }
        }
    }
    }
}
}
+184 −38
Original line number Original line Diff line number Diff line
use arrayvec::ArrayVec;
use labrador_ldpc::{decoder::DecodeFrom, LDPCCode};
use labrador_ldpc::LDPCCode;


use crate::error::EncodeError;
use crate::{buffer::Buffer, error::EncodeError};


macro_rules! enc_chunk {
macro_rules! enc_chunk {
    ($d:ident, $i:ident, $t:ident, $n:literal) => {
    ($d:ident, $i:ident, $t:ident, $n:literal) => {
@@ -37,8 +36,29 @@ macro_rules! dec_chunk {
    };
    };
}
}


macro_rules! dec_chunk_soft {
    ($d:ident, $p:ident, $w:ident, $w_u8:ident, $out:ident, $t:ident, $n:literal) => {
        ::paste::paste! {
            let code_data = &mut $d[..$n];
            let code_parity = &$p.get_mut(..$n)?;

            let mut input = [T::zero(); $n * 2];
            input[..$n].copy_from_slice(code_data);
            input[$n..].copy_from_slice(code_parity);
            const CODE: LDPCCode = LDPCCode::[<$t>];

			let mut out_tmp = [0; CODE.output_len()];
            CODE.decode_ms(&input, &mut out_tmp, &mut $w[..CODE.decode_ms_working_len()], &mut $w_u8[..CODE.decode_ms_working_u8_len()], 16);
			$out.try_extend_from_slice(&out_tmp[..$n/8]).ok()?;

            $d = &mut $d[$n..];
            $p = &mut $p[$n..];
        }
    };
}

// On failure this still modifies the data array!
// On failure this still modifies the data array!
pub(crate) fn encode<const N: usize>(data: &mut ArrayVec<u8, N>) -> Result<(), EncodeError> {
pub(crate) fn encode<const N: usize>(data: &mut Buffer<N>) -> Result<(), EncodeError> {
    let mut i = 0;
    let mut i = 0;
    let n = data.len();
    let n = data.len();


@@ -84,7 +104,7 @@ pub(crate) fn encode<const N: usize>(data: &mut ArrayVec<u8, N>) -> Result<(), E
    Ok(())
    Ok(())
}
}


pub(crate) fn decode<const N: usize>(data_av: &mut ArrayVec<u8, N>) -> Option<()> {
pub(crate) fn decode<const N: usize>(data_av: &mut Buffer<N>) -> Option<()> {
    if data_av.len() < 2 {
    if data_av.len() < 2 {
        return None;
        return None;
    }
    }
@@ -92,6 +112,10 @@ pub(crate) fn decode<const N: usize>(data_av: &mut ArrayVec<u8, N>) -> Option<()
    let len = [data_av[data_av.len() - 2], data_av[data_av.len() - 1]];
    let len = [data_av[data_av.len() - 2], data_av[data_av.len() - 1]];
    let len = u16::from_le_bytes(len).into();
    let len = u16::from_le_bytes(len).into();


    if len >= data_av.len() {
        return None;
    }

    let (mut data, parity) = data_av.split_at_mut(len);
    let (mut data, parity) = data_av.split_at_mut(len);
    let mut parity = parity.get_mut(..parity.len().checked_sub(2)?)?;
    let mut parity = parity.get_mut(..parity.len().checked_sub(2)?)?;


@@ -150,28 +174,125 @@ pub(crate) fn decode<const N: usize>(data_av: &mut ArrayVec<u8, N>) -> Option<()
    Some(())
    Some(())
}
}


pub(crate) fn decode_soft<const N: usize, const M: usize, T: DecodeFrom>(
    data_av: &mut Buffer<N, T>,
    out: &mut Buffer<M>,
) -> Option<()> {
    if data_av.len() % 8 != 0 {
        return None;
    }

    if data_av.len() < 16 {
        return None;
    }

    let len: usize = len_from_soft(data_av[(data_av.len() - 16)..].try_into().unwrap()).into();

    if len * 8 + 16 >= data_av.len() {
        return None;
    }

    let data_len = data_av.len().checked_sub(16)?;
    let data_av = data_av.get_mut(..data_len)?;

    let (mut data, mut parity) = data_av.split_at_mut(len * 8);

    let mut working = [T::zero(); LDPCCode::TM8192.decode_ms_working_len()];
    let mut working_u8 = [0; LDPCCode::TM8192.decode_ms_working_u8_len()];

    loop {
        match data.len() {
            4096.. => {
                dec_chunk_soft!(data, parity, working, working_u8, out, TM8192, 4096);
            }

            1024.. => {
                dec_chunk_soft!(data, parity, working, working_u8, out, TM2048, 1024);
            }

            256.. => {
                dec_chunk_soft!(data, parity, working, working_u8, out, TC512, 256);
            }

            128.. => {
                dec_chunk_soft!(data, parity, working, working_u8, out, TC256, 128);
            }

            64.. => {
                dec_chunk_soft!(data, parity, working, working_u8, out, TC128, 64);
            }

            0 => break,

            _ => {
                // Extra bits are padded with 0xAA
                // We need to tell the soft decoder that these bits can't have flipped
                // So we use T::maxval
                let mut code_data = [
                    1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,
                    1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,
                    1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,
                ]
                .map(|x| if x > 0 { -T::maxval() } else { T::maxval() });
                code_data[..data.len()].copy_from_slice(data);
                let code_parity = &parity.get_mut(..64)?;

                let mut input = [T::zero(); 128];
                input[..64].copy_from_slice(&code_data);
                input[64..].copy_from_slice(code_parity);
                let mut tmp_out = [0; LDPCCode::TC128.output_len()];
                LDPCCode::TC128.decode_ms(
                    &input,
                    &mut tmp_out,
                    &mut working[..LDPCCode::TC128.decode_ms_working_len()],
                    &mut working_u8[..LDPCCode::TC128.decode_ms_working_u8_len()],
                    16,
                );
                out.try_extend_from_slice(&tmp_out[..(data.len() / 8)])
                    .ok()?;

                data = &mut data[..0];
                parity = &mut parity[..0];
            }
        }
    }

    Some(())
}

fn len_from_soft<T: DecodeFrom>(bits: &[T; 16]) -> u16 {
    let mut upper = 0;
    for b in &bits[0..8] {
        upper <<= 1;
        upper |= u8::from(b.hard_bit());
    }

    let mut lower = 0;
    for b in &bits[8..] {
        lower <<= 1;
        lower |= u8::from(b.hard_bit());
    }

    u16::from_le_bytes([upper, lower])
}

#[cfg(test)]
#[cfg(test)]
mod tests {
mod tests {
    use super::*;
    use super::*;
    use arrayvec::ArrayVec;
    use crate::soft_bit::FromHardBit;
    use bitvec::{order::Msb0, view::BitView};


    #[test]
    #[test]
    fn len_test() {
    fn len_test() {
        // from the example in the docs
        // from the example in the docs
        let mut data: ArrayVec<u8, 8191> = ArrayVec::new();
        let mut buf = [0; 8191];
        let mut data = Buffer::new_empty(&mut buf);


        for _ in 0..41 {
        for _ in 0..41 {
            data.extend(
            data.extend(b"Example packet data  wueirpqwerwrywqoeiruy29346129384761");
                b"Example packet data  wueirpqwerwrywqoeiruy29346129384761"
                    .iter()
                    .cloned(),
            );
        }
        }
        data.extend(
        data.extend(b"Example packet data  wueirpqwerwrywqoeiru346129384761");
            b"Example packet data  wueirpqwerwrywqoeiru346129384761"

                .iter()
                .cloned(),
        );
        assert_eq!(2349, data.len());
        assert_eq!(2349, data.len());


        encode(&mut data).unwrap();
        encode(&mut data).unwrap();
@@ -181,51 +302,50 @@ mod tests {


    #[test]
    #[test]
    fn basic_encode_decode_short() {
    fn basic_encode_decode_short() {
        let mut data: ArrayVec<u8, 32> = ArrayVec::new();
        let mut buf = [0; 32];
        let mut buf2 = [0; 32];
        let mut data = Buffer::new_empty(&mut buf);
        data.try_extend_from_slice(b"Hello world!").unwrap();
        data.try_extend_from_slice(b"Hello world!").unwrap();
        let orig = data.clone();
        let orig = data.clone_backing(&mut buf2);


        encode(&mut data).unwrap();
        encode(&mut data).unwrap();


        decode(&mut data).unwrap();
        decode(&mut data).unwrap();


        assert_eq!(orig, data);
        assert_eq!(*orig, *data);
    }
    }


    #[test]
    #[test]
    fn basic_encode_decode() {
    fn basic_encode_decode() {
        let mut data: ArrayVec<u8, 8191> = ArrayVec::new();
        let mut buf = [0; 8191];
        let mut buf2 = [0; 8191];
        let mut data = Buffer::new_empty(&mut buf);
        for _ in 0..50 {
        for _ in 0..50 {
            data.extend(
            data.extend(b"This is a test packet. jsalksjd093809324JASLD:LKD*#$)(*#@)");
                b"This is a test packet. jsalksjd093809324JASLD:LKD*#$)(*#@)"
                    .iter()
                    .cloned(),
            );
        }
        }
        let orig = data.clone();
        let orig = data.clone_backing(&mut buf2);


        encode(&mut data).unwrap();
        encode(&mut data).unwrap();
        assert_ne!(orig, data);
        assert_ne!(*orig, *data);


        decode(&mut data).unwrap();
        decode(&mut data).unwrap();


        assert_eq!(orig, data);
        assert_eq!(*orig, *data);
    }
    }


    #[test]
    #[test]
    fn encode_decode_with_bit_flips() {
    fn encode_decode_with_bit_flips() {
        let mut data: ArrayVec<u8, 8191> = ArrayVec::new();
        let mut buf = [0; 8191];
        let mut buf2 = [0; 8191];
        let mut data = Buffer::new_empty(&mut buf);

        for _ in 0..50 {
        for _ in 0..50 {
            data.extend(
            data.extend(b"jsalksjd093809324JASLD:LKD*#$)(*#@) Another test packet");
                b"jsalksjd093809324JASLD:LKD*#$)(*#@) Another test packet"
                    .iter()
                    .cloned(),
            );
        }
        }
        let orig = data.clone();
        let orig = data.clone_backing(&mut buf2);


        encode(&mut data).unwrap();
        encode(&mut data).unwrap();
        assert_ne!(orig, data);
        assert_ne!(*orig, *data);


        data[234] ^= 0x55;
        data[234] ^= 0x55;
        data[0] ^= 0xAA;
        data[0] ^= 0xAA;
@@ -233,6 +353,32 @@ mod tests {


        decode(&mut data).unwrap();
        decode(&mut data).unwrap();


        assert_eq!(orig, data);
        assert_eq!(*orig, *data);
    }

    #[test]
    fn basic_encode_decode_soft() {
        let mut buf = [0; 8191];
        let mut buf2 = [0; 8191];
        let mut data = Buffer::new_empty(&mut buf);
        for _ in 0..50 {
            data.extend(b"This is a test packet. jsalksjd093809324JASLD:LKD*#$)(*#@)");
        }
        let orig = data.clone_backing(&mut buf2);

        encode(&mut data).unwrap();
        assert_ne!(*orig, *data);

        let mut soft = [0.0; 8191 * 8];
        let mut soft = Buffer::new_empty(&mut soft);
        for b in data.view_bits::<Msb0>() {
            soft.push(f32::from_hard_bit(*b));
        }

        let mut out = [0; 8191];
        let mut out = Buffer::new_empty(&mut out);
        decode_soft(&mut soft, &mut out).unwrap();

        assert_eq!(*orig, *out);
    }
    }
}
}
+4 −1
Original line number Original line Diff line number Diff line
#![no_std]
#![cfg_attr(not(test), no_std)]


pub mod buffer;
pub mod error;
pub mod error;
pub mod identity;
pub mod interleaver;
pub mod interleaver;
pub mod ldpc;
pub mod ldpc;
pub mod packet;
pub mod packet;
pub mod soft_bit;
pub mod whisker;
pub mod whisker;
pub mod whitener;
pub mod whitener;


+551 −55

File changed.

Preview size limit exceeded, changes collapsed.

src/soft_bit.rs

0 → 100644
+40 −0
Original line number Original line Diff line number Diff line
pub use labrador_ldpc::decoder::DecodeFrom;

// Less than zero = 1 bit
// Greater than zero = 0 bit
pub trait FromHardBit {
    fn from_hard_bit(bit: bool) -> Self;
}

impl<T: DecodeFrom> FromHardBit for T {
    fn from_hard_bit(bit: bool) -> Self {
        if bit {
            -Self::one()
        } else {
            Self::one()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn e2e() {
        assert!(f32::from_hard_bit(true).hard_bit());
        assert!(!f32::from_hard_bit(false).hard_bit());

        assert!(f64::from_hard_bit(true).hard_bit());
        assert!(!f64::from_hard_bit(false).hard_bit());

        assert!(i8::from_hard_bit(true).hard_bit());
        assert!(!i8::from_hard_bit(false).hard_bit());

        assert!(i16::from_hard_bit(true).hard_bit());
        assert!(!i16::from_hard_bit(false).hard_bit());

        assert!(i32::from_hard_bit(true).hard_bit());
        assert!(!i32::from_hard_bit(false).hard_bit());
    }
}
Original line number Original line Diff line number Diff line
use arrayvec::ArrayVec;
use arrayvec::ArrayVec;


#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct Arbitrary(pub ArrayVec<u8, 255>);
pub struct Arbitrary(pub ArrayVec<u8, 255>);


impl Arbitrary {
impl Arbitrary {
Original line number Original line Diff line number Diff line
@@ -2,7 +2,7 @@ use core::str::FromStr;


use arrayvec::ArrayString;
use arrayvec::ArrayString;


#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Destination {
pub struct Destination {
    ack: u8,
    ack: u8,
    callsign: ArrayString<253>,
    callsign: ArrayString<253>,
@@ -36,7 +36,7 @@ impl Destination {
    }
    }


    pub fn ack_num(&self) -> u8 {
    pub fn ack_num(&self) -> u8 {
        self.ack
        self.ack & !(1 << 7)
    }
    }


    pub fn callsign(&self) -> &str {
    pub fn callsign(&self) -> &str {
Original line number Original line Diff line number Diff line
use core::fmt::{Debug, Display};
use half::f16;
use half::f16;


#[derive(Debug, PartialEq)]
#[derive(PartialEq, Clone)]
pub struct Gps {
pub struct Gps {
    latitude: i32,
    latitude: i32,
    longitude: i32,
    longitude: i32,
@@ -33,8 +34,14 @@ impl Gps {
        let longitude = longitude.clamp(-179.999, 179.999);
        let longitude = longitude.clamp(-179.999, 179.999);
        let longitude = (longitude * ((1u32 << 31) as f64) / 180.0) as i32;
        let longitude = (longitude * ((1u32 << 31) as f64) / 180.0) as i32;


        let heading = heading.clamp(0.0, 359.999);
        let heading = if heading >= 0.0 {
        let heading = (heading * 128.0 / 360.0) as u8;
            heading % 360.0
        } else {
            // slightly hacky no-std floor
            let factor = (-heading / 360.0) as u32 as f64;
            360.0 * (1.0 + factor) + heading
        };
        let heading = round(heading * 128.0 / 180.0) as u8;


        Self {
        Self {
            latitude,
            latitude,
@@ -55,7 +62,7 @@ impl Gps {
    }
    }


    pub fn heading(&self) -> f64 {
    pub fn heading(&self) -> f64 {
        self.heading as f64 / 128.0 * 360.0
        self.heading as f64 / 128.0 * 180.0
    }
    }


    pub fn encode<'a>(&self, buf: &'a mut [u8]) -> Option<&'a [u8]> {
    pub fn encode<'a>(&self, buf: &'a mut [u8]) -> Option<&'a [u8]> {
@@ -93,3 +100,68 @@ impl Gps {
        })
        })
    }
    }
}
}

impl Debug for Gps {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.debug_struct("Gps")
            .field("latitude", &DebugUnits(self.latitude(), "°"))
            .field("longitude", &DebugUnits(self.longitude(), "°"))
            .field("altitude", &DebugUnits(self.altitude, " m"))
            .field("max_error", &DebugUnits(self.max_error, " m"))
            .field("heading", &DebugUnits(self.heading(), "°"))
            .field("speed", &DebugUnits(self.speed, " m/s"))
            .finish()
    }
}

struct DebugUnits<'a, T>(T, &'a str);

impl<T: Display> Debug for DebugUnits<'_, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}{}", self.0, self.1)
    }
}

// no-std and it's not worth bringing in a library for this
fn round(v: f64) -> u32 {
    let floor = v as u32;
    let delta = v - floor as f64;
    if delta <= 0.5 {
        floor
    } else {
        floor + 1
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn heading_is_correct() {
        let gps = Gps::new(0.0, 0.0, f16::from_f32(0.0), 0, 359.0, f16::from_f32(0.0));
        assert_eq!(gps.heading, 255);

        let gps = Gps::new(0.0, 0.0, f16::from_f32(0.0), 0, 0.0, f16::from_f32(0.0));
        assert_eq!(gps.heading, 0);

        let gps = Gps::new(0.0, 0.0, f16::from_f32(0.0), 0, -20.0, f16::from_f32(0.0));
        assert_eq!(gps.heading, 242);

        let gps = Gps::new(0.0, 0.0, f16::from_f32(0.0), 0, 719.0, f16::from_f32(0.0));
        assert_eq!(gps.heading, 255);

        let gps = Gps::new(0.0, 0.0, f16::from_f32(0.0), 0, 180.0, f16::from_f32(0.0));
        assert_eq!(gps.heading, 128);

        let gps = Gps::new(0.0, 0.0, f16::from_f32(0.0), 0, 540.0, f16::from_f32(0.0));
        assert_eq!(gps.heading, 128);
    }

    #[test]
    fn debug_printing() {
        let gps = Gps::new(0.0, 0.0, f16::from_f32(0.0), 0, 359.0, f16::from_f32(0.0));
        let x = format!("{gps:?}");
        assert_eq!(x,"Gps { latitude: 0°, longitude: 0°, altitude: 0 m, max_error: 0 m, heading: 358.59375°, speed: 0 m/s }")
    }
}
Original line number Original line Diff line number Diff line
use arrayvec::ArrayString;
use arrayvec::ArrayString;


#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Identification {
pub struct Identification {
    pub icon: u16,
    pub callsign: ArrayString<252>,
    pub callsign: ArrayString<252>,
    pub ssid: u8,
    pub ssid: u8,
    pub icon: u16,
}
}


impl Identification {
impl Identification {
    pub fn new(icon: u16, call: &str, ssid: u8) -> Option<Self> {
    pub fn new(call: &str, ssid: u8, icon: u16) -> Option<Self> {
        let callsign = ArrayString::from(call).ok()?;
        let callsign = ArrayString::from(call).ok()?;


        Some(Self {
        Some(Self {
+138 −38
Original line number Original line Diff line number Diff line
@@ -3,6 +3,7 @@ mod comment;
mod destination;
mod destination;
mod gps;
mod gps;
mod identification;
mod identification;
mod node_info;
mod route;
mod route;
mod timestamp;
mod timestamp;
mod unknown;
mod unknown;
@@ -15,7 +16,8 @@ pub use self::{
    destination::Destination,
    destination::Destination,
    gps::Gps,
    gps::Gps,
    identification::Identification,
    identification::Identification,
    route::{Route, RouteIter, RouteNode},
    node_info::{NodeInfo, NodeInfoBuilder},
    route::{PastHop, Route, RouteHop, RouteIter},
    timestamp::Timestamp,
    timestamp::Timestamp,
    unknown::Unknown,
    unknown::Unknown,
};
};
@@ -27,6 +29,7 @@ pub(crate) const COMMENT_TYPE: u8 = 0x03;
pub(crate) const ROUTE_TYPE: u8 = 0x04;
pub(crate) const ROUTE_TYPE: u8 = 0x04;
pub(crate) const DESTINATION_TYPE: u8 = 0x05;
pub(crate) const DESTINATION_TYPE: u8 = 0x05;
pub(crate) const ARBITRARY_TYPE: u8 = 0x06;
pub(crate) const ARBITRARY_TYPE: u8 = 0x06;
pub(crate) const NODE_INFO_TYPE: u8 = 0x09;


#[derive(Debug)]
#[derive(Debug)]
pub enum Whisker {
pub enum Whisker {
@@ -37,6 +40,7 @@ pub enum Whisker {
    Route(Route),
    Route(Route),
    Destination(Destination),
    Destination(Destination),
    Arbitrary(Arbitrary),
    Arbitrary(Arbitrary),
    NodeInfo(NodeInfo),
    Unknown(Unknown),
    Unknown(Unknown),
}
}


@@ -137,16 +141,21 @@ impl<'a> WhiskerIter<'a> {
            ARBITRARY_TYPE => Whisker::Arbitrary(
            ARBITRARY_TYPE => Whisker::Arbitrary(
                Arbitrary::decode(data).ok_or(DecodeError::MalformedWhisker { position })?,
                Arbitrary::decode(data).ok_or(DecodeError::MalformedWhisker { position })?,
            ),
            ),
            NODE_INFO_TYPE => Whisker::NodeInfo(
                NodeInfo::decode(data).ok_or(DecodeError::MalformedWhisker { position })?,
            ),


            // safe to unwrap because we know len has to be 255 or less, since it's a u8
            // safe to unwrap because we know len has to be 255 or less, since it's a u8
            whisker_type => Whisker::Unknown(Unknown::new(whisker_type, data.try_into().unwrap())),
            whisker_type => {
                Whisker::Unknown(Unknown::new(whisker_type, data[1..].try_into().unwrap()))
            }
        };
        };


        Ok(out)
        Ok(out)
    }
    }
}
}


impl<'a> Iterator for WhiskerIter<'a> {
impl Iterator for WhiskerIter<'_> {
    type Item = Result<Whisker, DecodeError>;
    type Item = Result<Whisker, DecodeError>;


    fn next(&mut self) -> Option<Self::Item> {
    fn next(&mut self) -> Option<Self::Item> {
@@ -170,7 +179,7 @@ impl<'a> ValidatedWhiskerIter<'a> {
    }
    }
}
}


impl<'a> Iterator for ValidatedWhiskerIter<'a> {
impl Iterator for ValidatedWhiskerIter<'_> {
    type Item = Whisker;
    type Item = Whisker;


    fn next(&mut self) -> Option<Self::Item> {
    fn next(&mut self) -> Option<Self::Item> {
@@ -182,7 +191,10 @@ impl<'a> Iterator for ValidatedWhiskerIter<'a> {
mod tests {
mod tests {
    use half::f16;
    use half::f16;


    use crate::whisker::route::RouteNode;
    use crate::{
        identity::Identity,
        whisker::route::{PastHop, RouteHop},
    };


    use super::*;
    use super::*;


@@ -192,7 +204,7 @@ mod tests {
        let call = "VE9ABCDEFGZZ4839-???";
        let call = "VE9ABCDEFGZZ4839-???";
        let ssid = 17;
        let ssid = 17;


        let ident = Identification::new(icon, call, ssid).unwrap();
        let ident = Identification::new(call, ssid, icon).unwrap();
        let mut buf = [0; 256];
        let mut buf = [0; 256];


        let encoded = ident.encode(&mut buf).unwrap();
        let encoded = ident.encode(&mut buf).unwrap();
@@ -236,7 +248,7 @@ mod tests {


        assert_eq!(89.99899999704212, gps.latitude());
        assert_eq!(89.99899999704212, gps.latitude());
        assert_eq!(-179.9989999551326, gps.longitude());
        assert_eq!(-179.9989999551326, gps.longitude());
        assert_eq!(120.9375, gps.heading());
        assert_eq!(123.75, gps.heading());
    }
    }


    #[test]
    #[test]
@@ -246,11 +258,58 @@ mod tests {
            23.45,
            23.45,
            f16::from_f32(45.02),
            f16::from_f32(45.02),
            24,
            24,
            360.0,
            359.0,
            f16::from_f32(12.3),
            f16::from_f32(12.3),
        );
        );


        assert_eq!(357.1875, gps.heading());
        assert_eq!(358.59375, gps.heading());

        let gps = Gps::new(
            4.0,
            23.45,
            f16::from_f32(45.02),
            24,
            957.47,
            f16::from_f32(12.3),
        );

        assert_eq!(957.65625 - 360.0 * 2.0, gps.heading());
    }

    #[test]
    fn gps_min_heading() {
        let gps = Gps::new(
            4.0,
            23.45,
            f16::from_f32(45.02),
            24,
            0.0,
            f16::from_f32(12.3),
        );

        assert_eq!(0.0, gps.heading());

        let gps = Gps::new(
            4.0,
            23.45,
            f16::from_f32(45.02),
            24,
            -22.0,
            f16::from_f32(12.3),
        );

        assert_eq!(337.5, gps.heading());

        let gps = Gps::new(
            4.0,
            23.45,
            f16::from_f32(45.02),
            24,
            -1206.0,
            f16::from_f32(12.3),
        );

        assert_eq!(233.4375, gps.heading());
    }
    }


    #[test]
    #[test]
@@ -285,43 +344,47 @@ mod tests {
    #[test]
    #[test]
    fn route_push_and_iter() {
    fn route_push_and_iter() {
        let mut route = Route::new(34);
        let mut route = Route::new(34);
        route.push_callsign("VE2XYZ", 23, false).unwrap();
        route
            .push_past(PastHop::new(Identity::new("VE2XYZ", 23), None))
            .unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();
        route.push_callsign("VE9AAAAA", 94, true).unwrap();
        route.push_future(Identity::new("VE9AAAAA", 94)).unwrap();
        assert!(route.push_callsign("VE9AAAAA", 94, false).is_none());
        // past after future - not allowed
        assert!(route
            .push_past(PastHop::new(Identity::new("VE9AAAAA", 94), None))
            .is_none());


        // too long
        // too long
        assert!(route
        assert!(route
            .push_callsign(
            .push_future(Identity::new(
                "lsdfjslkdfjlksdjflksfjsdklfjsdklfjsdklfjsdklfjsklfsef;jklsdfjkl;sdf;klsdf;klsjdfJSDJFSKL:DFJDSL:KFskldfj;slkdfjsdkl;fjdskl;fjsdfl;kjsdfl;ksdjfkl;ssdfl;kjsdfl;ksdjf;sdklsd;lfkjsdlfk;jsdl;fkjsd;klfjsd;fljsf;oidfjgwper0tujdfgndfjkl;gjnergjol;kehfgo;dijge;oghdfkl;gjdfkl;gjdeior;lgjedr;ioghjdorighndeklo;grjiop[",
                "lsdfjslkdfjlksdjflksfjsdklfjsdklfjsdklfjsdklfjsklfsef;jklsdfjkl;sdf;klsdf;klsjdfJSDJFSKL:DFJDSL:KFskldfj;slkdfjsdkl;fjdskl;fjsdfl;kjsdfl;ksdjfkl;ssdfl;kjsdfl;ksdjf;sdklsd;lfkjsdlfk;jsdl;fkjsd;klfjsd;fljsf;oidfjgwper0tujdfgndfjkl;gjnergjol;kehfgo;dijge;oghdfkl;gjdfkl;gjdeior;lgjedr;ioghjdorighndeklo;grjiop[",
                20,
                20,
                true,
            )).is_none());
            ).is_none());


        route
        route
            .push_callsign("This is the last callsign", 0, true)
            .push_future(Identity::new("This is the last callsign", 0))
            .unwrap();
            .unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();


        let mut iter = route.iter();
        let mut iter = route.iter();
        assert_eq!(
        assert_eq!(
            RouteNode::Identity("VE2XYZ", 23, false),
            RouteHop::Past(PastHop::new(Identity::new("VE2XYZ", 23), None)),
            iter.next().unwrap()
            iter.next().unwrap()
        );
        );
        assert_eq!(RouteNode::Internet, iter.next().unwrap());
        assert_eq!(RouteHop::Internet, iter.next().unwrap());
        assert_eq!(RouteNode::Internet, iter.next().unwrap());
        assert_eq!(RouteHop::Internet, iter.next().unwrap());
        assert_eq!(RouteNode::Internet, iter.next().unwrap());
        assert_eq!(RouteHop::Internet, iter.next().unwrap());
        assert_eq!(
        assert_eq!(
            RouteNode::Identity("VE9AAAAA", 94, true),
            RouteHop::Future(Identity::new("VE9AAAAA", 94)),
            iter.next().unwrap()
            iter.next().unwrap()
        );
        );
        assert_eq!(
        assert_eq!(
            RouteNode::Identity("This is the last callsign", 0, true),
            RouteHop::Future(Identity::new("This is the last callsign", 0)),
            iter.next().unwrap()
            iter.next().unwrap()
        );
        );
        assert_eq!(RouteNode::Internet, iter.next().unwrap());
        assert_eq!(RouteHop::Internet, iter.next().unwrap());
        assert_eq!(None, iter.next());
        assert_eq!(None, iter.next());


        assert_eq!(34, route.max_hops);
        assert_eq!(34, route.max_hops);
@@ -330,13 +393,15 @@ mod tests {
    #[test]
    #[test]
    fn route_e2e() {
    fn route_e2e() {
        let mut route = Route::new(34);
        let mut route = Route::new(34);
        route.push_callsign("VE2XYZ", 23, false).unwrap();
        route
            .push_past(PastHop::new(Identity::new("VE2XYZ", 23), Some(0.0)))
            .unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();
        route.push_callsign("VE9AAAAA", 94, true).unwrap();
        route.push_future(Identity::new("VE9AAAAA", 94)).unwrap();
        route
        route
            .push_callsign("This is the last callsign", 0, true)
            .push_future(Identity::new("This is the last callsign", 0))
            .unwrap();
            .unwrap();
        route.push_internet().unwrap();
        route.push_internet().unwrap();


@@ -350,44 +415,70 @@ mod tests {
    #[test]
    #[test]
    fn route_doc_examples() {
    fn route_doc_examples() {
        let mut ex1 = Route::new(4);
        let mut ex1 = Route::new(4);
        ex1.push_callsign("VE1ABC", 0, false);
        ex1.push_past(PastHop::new(Identity::new("VE1ABC", 0), Some(-96.0)))
        ex1.push_callsign("VE2DEF", 234, false);
            .unwrap();
        ex1.push_callsign("VE3XYZ", 14, false);
        ex1.push_past(PastHop::new(Identity::new("VE2DEF", 234), Some(-13.0)))
            .unwrap();
        ex1.push_past(PastHop::new(Identity::new("VE3XYZ", 14), Some(-106.0)))
            .unwrap();


        let mut buf = [0; 256];
        let mut buf = [0; 256];
        let encoded = ex1.encode(&mut buf).unwrap();
        let encoded = ex1.encode(&mut buf).unwrap();
        assert_eq!(
        assert_eq!(
            &[
            &[
                0x19, 0x04, 0x56, 0x45, 0x31, 0x41, 0x42, 0x43, 0xFF, 0x00, 0x56, 0x45, 0x32, 0x44,
                0x1C, 0x04, 0x56, 0x45, 0x31, 0x41, 0x42, 0x43, 0xFF, 0x00, 0x60, 0x56, 0x45, 0x32,
                0x45, 0x46, 0xFF, 0xEA, 0x56, 0x45, 0x33, 0x58, 0x59, 0x5A, 0xFF, 0x0E
                0x44, 0x45, 0x46, 0xFF, 0xEA, 0xDC, 0x56, 0x45, 0x33, 0x58, 0x59, 0x5A, 0xFF, 0x0E,
                0x51
            ],
            &encoded
        );

        let mut ex1_5 = Route::new(4);
        ex1_5
            .push_past(PastHop::new(Identity::new("VE1ABC", 0), Some(-96.0)))
            .unwrap();
        ex1_5.push_future(Identity::new("VE2DEF", 234)).unwrap();
        ex1_5.push_future(Identity::new("VE3XYZ", 14)).unwrap();

        let mut buf = [0; 256];
        let encoded = ex1_5.encode(&mut buf).unwrap();
        assert_eq!(
            &[
                0x1A, 0x04, 0x56, 0x45, 0x31, 0x41, 0x42, 0x43, 0xFF, 0x00, 0x60, 0x56, 0x45, 0x32,
                0x44, 0x45, 0x46, 0xFD, 0xEA, 0x56, 0x45, 0x33, 0x58, 0x59, 0x5A, 0xFD, 0x0E,
            ],
            ],
            &encoded
            &encoded
        );
        );


        let mut ex2 = Route::new(3);
        let mut ex2 = Route::new(3);
        ex2.push_callsign("VE1ABC", 0, false);
        ex2.push_past(PastHop::new(Identity::new("VE1ABC", 0), None))
            .unwrap();
        ex2.push_internet();
        ex2.push_internet();
        ex2.push_callsign("VE2DEF", 234, false);
        ex2.push_past(PastHop::new(Identity::new("VE2DEF", 234), Some(-86.5)))
            .unwrap();
        ex2.push_internet();
        ex2.push_internet();
        ex2.push_callsign("VE3XYZ", 14, false);
        ex2.push_past(PastHop::new(Identity::new("VE3XYZ", 14), Some(-65.0)))
            .unwrap();


        let encoded = ex2.encode(&mut buf).unwrap();
        let encoded = ex2.encode(&mut buf).unwrap();
        assert_eq!(
        assert_eq!(
            &[
            &[
                0x1B, 0x03, 0x56, 0x45, 0x31, 0x41, 0x42, 0x43, 0xFF, 0x00, 0xFE, 0x56, 0x45, 0x32,
                0x1E, 0x03, 0x56, 0x45, 0x31, 0x41, 0x42, 0x43, 0xFF, 0x00, 0x00, 0xFE, 0x56, 0x45,
                0x44, 0x45, 0x46, 0xFF, 0xEA, 0xFE, 0x56, 0x45, 0x33, 0x58, 0x59, 0x5A, 0xFF, 0x0E
                0x32, 0x44, 0x45, 0x46, 0xFF, 0xEA, 0x6E, 0xFE, 0x56, 0x45, 0x33, 0x58, 0x59, 0x5A,
                0xFF, 0x0E, 0x8E
            ],
            ],
            &encoded
            &encoded
        );
        );


        let mut ex3 = Route::new(0);
        let mut ex3 = Route::new(0);
        ex3.push_callsign("VE1ABC", 0, false);
        ex3.push_past(PastHop::new(Identity::new("VE1ABC", 0), Some(-42.5)))
            .unwrap();
        ex3.push_internet();
        ex3.push_internet();
        ex3.push_internet();
        ex3.push_internet();


        let encoded = ex3.encode(&mut buf).unwrap();
        let encoded = ex3.encode(&mut buf).unwrap();
        assert_eq!(
        assert_eq!(
            &[0x0B, 0x00, 0x56, 0x45, 0x31, 0x41, 0x42, 0x43, 0xFF, 0x00, 0xFE, 0xFE],
            &[0x0C, 0x00, 0x56, 0x45, 0x31, 0x41, 0x42, 0x43, 0xFF, 0x00, 0xB0, 0xFE, 0xFE],
            &encoded
            &encoded
        );
        );
    }
    }
@@ -405,6 +496,15 @@ mod tests {
        assert_eq!(dest, decoded);
        assert_eq!(dest, decoded);
    }
    }


    #[test]
    fn dest_ack() {
        let dest = Destination::new(true, 84, "abc", 17).unwrap();
        assert_eq!(84, dest.ack_num());
        assert!(dest.is_ack());
        assert_eq!("abc", dest.callsign());
        assert_eq!(17, dest.ssid());
    }

    #[test]
    #[test]
    fn arbitrary_e2e() {
    fn arbitrary_e2e() {
        let data = b"Hello world! This is an example comment";
        let data = b"Hello world! This is an example comment";