use std::fmt;
use crate::buffer::{ByteReader, ByteWriter, COUNT_BOUNDARY};
use crate::error::{DecoderError, EncoderError};
use crate::typed::{Decode, Encode, Representation};
pub(crate) fn encode_octets(octets: &[u8], writer: &mut ByteWriter<'_>) {
writer.align(COUNT_BOUNDARY);
writer.put_count(octets.len());
writer.put_slice(octets);
}
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()),
})
}
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 {
pub fn new(octets: impl Into<Vec<u8>>) -> Self {
Self(octets.into())
}
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
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
}
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)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct HLAASCIIstring(String);
impl HLAASCIIstring {
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"),
}),
}
}
pub fn as_str(&self) -> &str {
&self.0
}
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() })
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct HLAunicodeString(pub String);
impl HLAunicodeString {
pub fn new(text: impl Into<String>) -> Self {
Self(text.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
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)
}
}
impl Encode for str {
const OCTET_BOUNDARY: usize = 4;
fn encode(&self, writer: &mut ByteWriter<'_>) {
encode_utf16(self, writer);
}
}
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)
}
}