microrti-encoding 0.2.2

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
Documentation
//! Strings and opaque data: the MIM variable arrays of characters and bytes.

use std::fmt;

use crate::buffer::{ByteReader, ByteWriter, COUNT_BOUNDARY};
use crate::error::{DecoderError, EncoderError};
use crate::typed::{Decode, Encode, Representation};

/// Encodes a variable array of single-octet elements: count, then the octets.
pub(crate) fn encode_octets(octets: &[u8], writer: &mut ByteWriter<'_>) {
    writer.align(COUNT_BOUNDARY);
    writer.put_count(octets.len());
    writer.put_slice(octets);
}

/// Decodes a variable array of single-octet elements without copying.
pub(crate) fn decode_octets<'a>(reader: &mut ByteReader<'a>) -> Result<&'a [u8], DecoderError> {
    reader.align(COUNT_BOUNDARY)?;
    let count = reader.read_count()?;
    reader.take(count)
}

fn encode_utf16(text: &str, writer: &mut ByteWriter<'_>) {
    writer.align(COUNT_BOUNDARY);
    writer.put_count(text.encode_utf16().count());
    for unit in text.encode_utf16() {
        writer.put_slice(&unit.to_be_bytes());
    }
}

fn decode_utf16(reader: &mut ByteReader<'_>) -> Result<String, DecoderError> {
    reader.align(COUNT_BOUNDARY)?;
    let count = reader.read_count()?;
    let octets = reader.take(count.saturating_mul(2))?;
    let units = octets.as_chunks::<2>().0.iter().map(|pair| u16::from_be_bytes(*pair));
    char::decode_utf16(units).collect::<Result<String, _>>().map_err(|error| DecoderError::InvalidValue {
        type_name: "HLAunicodeString",
        detail: format!("unpaired surrogate {:#06x}", error.unpaired_surrogate()),
    })
}

/// Declares an element that is an `HLAvariableArray` of `HLAbyte` holding opaque octets.
macro_rules! octet_array_element {
    ($(#[$doc:meta])* $name:ident) => {
        $(#[$doc])*
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
        pub struct $name(pub Vec<u8>);

        impl $name {
            /// Wraps the given octets.
            pub fn new(octets: impl Into<Vec<u8>>) -> Self {
                Self(octets.into())
            }

            /// The wrapped octets.
            pub fn as_bytes(&self) -> &[u8] {
                &self.0
            }

            /// Unwraps the octets.
            pub fn into_bytes(self) -> Vec<u8> {
                self.0
            }
        }

        impl From<Vec<u8>> for $name {
            fn from(octets: Vec<u8>) -> Self {
                Self(octets)
            }
        }

        impl From<&[u8]> for $name {
            fn from(octets: &[u8]) -> Self {
                Self(octets.to_vec())
            }
        }

        impl From<$name> for Vec<u8> {
            fn from(value: $name) -> Self {
                value.0
            }
        }

        impl AsRef<[u8]> for $name {
            fn as_ref(&self) -> &[u8] {
                &self.0
            }
        }

        impl $crate::typed::Encode for $name {
            const OCTET_BOUNDARY: usize = 4;

            fn encode(&self, writer: &mut $crate::buffer::ByteWriter<'_>) {
                $crate::strings::encode_octets(&self.0, writer);
            }

            fn encoded_len(&self) -> usize {
                4 + self.0.len()
            }
        }

        impl $crate::typed::Decode for $name {
            fn decode(
                reader: &mut $crate::buffer::ByteReader<'_>,
            ) -> Result<Self, $crate::error::DecoderError> {
                $crate::strings::decode_octets(reader).map(|octets| Self(octets.to_vec()))
            }
        }
    };
}
pub(crate) use octet_array_element;

octet_array_element! {
    /// `HLAopaqueData`: an `HLAvariableArray` of `HLAbyte` (32-bit big-endian count, then the octets).
    HLAopaqueData
}

impl Representation<Vec<u8>> for HLAopaqueData {
    const BOUNDARY: usize = 4;

    fn encode_value(value: &Vec<u8>, writer: &mut ByteWriter<'_>) {
        encode_octets(value, writer);
    }

    fn decode_value(reader: &mut ByteReader<'_>) -> Result<Vec<u8>, DecoderError> {
        decode_octets(reader).map(<[u8]>::to_vec)
    }
}

/// `HLAASCIIstring`: an `HLAvariableArray` of `HLAASCIIchar`, one octet per character.
///
/// The wrapped text is guaranteed to be ASCII, so encoding cannot fail; decoding rejects octets above
/// `0x7F`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct HLAASCIIstring(String);

impl HLAASCIIstring {
    /// Wraps `text`, which must consist of ASCII characters only.
    pub fn new(text: impl Into<String>) -> Result<Self, EncoderError> {
        let text = text.into();
        match text.chars().find(|character| !character.is_ascii()) {
            None => Ok(Self(text)),
            Some(character) => Err(EncoderError::InvalidValue {
                type_name: "HLAASCIIstring",
                detail: format!("{character:?} is not an ASCII character"),
            }),
        }
    }

    /// The text.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Unwraps the text.
    pub fn into_string(self) -> String {
        self.0
    }
}

impl TryFrom<&str> for HLAASCIIstring {
    type Error = EncoderError;

    fn try_from(text: &str) -> Result<Self, EncoderError> {
        Self::new(text)
    }
}

impl TryFrom<String> for HLAASCIIstring {
    type Error = EncoderError;

    fn try_from(text: String) -> Result<Self, EncoderError> {
        Self::new(text)
    }
}

impl std::str::FromStr for HLAASCIIstring {
    type Err = EncoderError;

    fn from_str(text: &str) -> Result<Self, EncoderError> {
        Self::new(text)
    }
}

impl From<HLAASCIIstring> for String {
    fn from(value: HLAASCIIstring) -> Self {
        value.0
    }
}

impl AsRef<str> for HLAASCIIstring {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for HLAASCIIstring {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl Encode for HLAASCIIstring {
    const OCTET_BOUNDARY: usize = 4;

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        encode_octets(self.0.as_bytes(), writer);
    }

    fn encoded_len(&self) -> usize {
        4 + self.0.len()
    }
}

impl Decode for HLAASCIIstring {
    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
        let octets = decode_octets(reader)?;
        if let Some(octet) = octets.iter().find(|octet| !octet.is_ascii()) {
            return Err(DecoderError::InvalidValue {
                type_name: "HLAASCIIstring",
                detail: format!("octet {octet:#04x} is not an ASCII character"),
            });
        }
        match std::str::from_utf8(octets) {
            Ok(text) => Ok(Self(text.to_owned())),
            Err(error) => {
                Err(DecoderError::InvalidValue { type_name: "HLAASCIIstring", detail: error.to_string() })
            }
        }
    }
}

/// `HLAunicodeString`: an `HLAvariableArray` of `HLAunicodeChar`, that is UTF-16 code units in big-endian
/// order (IEEE 1516.2 4.14.4, 4.14.6). The count is the number of code units; characters outside the BMP
/// take a surrogate pair.
///
/// `String` and `str` have the same encoding, so plain Rust strings can be used wherever the datatype is
/// `HLAunicodeString`. A byte order mark is an ordinary character (U+FEFF). The standard does not say
/// what a receiver does with an unpaired surrogate; decoding rejects it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct HLAunicodeString(pub String);

impl HLAunicodeString {
    /// Wraps `text`.
    pub fn new(text: impl Into<String>) -> Self {
        Self(text.into())
    }

    /// The text.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Unwraps the text.
    pub fn into_string(self) -> String {
        self.0
    }
}

impl From<String> for HLAunicodeString {
    fn from(text: String) -> Self {
        Self(text)
    }
}

impl From<&str> for HLAunicodeString {
    fn from(text: &str) -> Self {
        Self(text.to_owned())
    }
}

impl From<HLAunicodeString> for String {
    fn from(value: HLAunicodeString) -> Self {
        value.0
    }
}

impl AsRef<str> for HLAunicodeString {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for HLAunicodeString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl Encode for HLAunicodeString {
    const OCTET_BOUNDARY: usize = 4;

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        encode_utf16(&self.0, writer);
    }
}

impl Decode for HLAunicodeString {
    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
        decode_utf16(reader).map(Self)
    }
}

impl Representation<String> for HLAunicodeString {
    const BOUNDARY: usize = 4;

    fn encode_value(value: &String, writer: &mut ByteWriter<'_>) {
        encode_utf16(value, writer);
    }

    fn decode_value(reader: &mut ByteReader<'_>) -> Result<String, DecoderError> {
        decode_utf16(reader)
    }
}

/// Encoded as `HLAunicodeString`.
impl Encode for str {
    const OCTET_BOUNDARY: usize = 4;

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        encode_utf16(self, writer);
    }
}

/// Encoded as `HLAunicodeString`.
impl Encode for String {
    const OCTET_BOUNDARY: usize = 4;

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        encode_utf16(self, writer);
    }
}

impl Decode for String {
    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
        decode_utf16(reader)
    }
}