use crate::{prelude::*, utils::buffers::buffer_to_hex};
mod to_instructions;
use crate::crypto::CryptoImpl;
use binrw::{BinRead, BinWrite, io::Cursor};
use core::{
fmt::{Debug, Display, Formatter},
hash::Hash,
result::Result,
str,
str::FromStr,
};
pub mod equality;
use datex_crypto_facade::crypto::Crypto;
use hex::decode;
mod classification;
mod convert_parts;
mod datex_hash;
mod datex_native;
mod datex_native_structural;
mod get_core_lib_type_id;
mod get_datex_type;
pub mod serde_dif;
#[cfg(feature = "ast")]
mod to_datex_expression_data;
mod try_clone;
mod value_access;
#[derive(
BinWrite, BinRead, Debug, Clone, Copy, Hash, PartialEq, Eq, Default,
)]
pub enum EndpointInstance {
#[default]
#[br(magic = 0u16)]
#[bw(magic = 0u16)]
Any,
#[br(magic = 65535u16)]
#[bw(magic = 65535u16)]
All,
Instance(u16),
}
impl EndpointInstance {
pub fn new(instance: u16) -> EndpointInstance {
match instance {
0 => EndpointInstance::Any,
65535 => EndpointInstance::All,
_ => EndpointInstance::Instance(instance),
}
}
}
#[derive(
Debug, Hash, PartialEq, Eq, Clone, Copy, Default, BinWrite, BinRead,
)]
#[brw(repr(u8))]
pub enum EndpointType {
#[default]
Person = 0,
Institution = 1,
Anonymous = 0xFF,
}
#[derive(BinWrite, BinRead, Clone, Hash, PartialEq, Eq)]
#[brw(little)]
pub struct Endpoint {
pub ty: EndpointType,
pub identifier: [u8; 18],
pub instance: EndpointInstance,
}
impl Debug for Endpoint {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "Endpoint({})", self)
}
}
impl Default for Endpoint {
fn default() -> Self {
Endpoint::LOCAL
}
}
impl TryFrom<&str> for Endpoint {
type Error = InvalidEndpointError;
fn try_from(name: &str) -> Result<Self, Self::Error> {
Endpoint::from_string(name)
}
}
impl TryFrom<String> for Endpoint {
type Error = InvalidEndpointError;
fn try_from(name: String) -> Result<Self, Self::Error> {
Endpoint::from_string(&name)
}
}
#[derive(PartialEq, Debug, Clone, Eq)]
pub enum InvalidEndpointError {
InvalidCharacters,
MaxLengthExceeded,
MinLengthNotMet,
InvalidInstance,
ReservedName,
}
impl Display for InvalidEndpointError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
InvalidEndpointError::InvalidCharacters => {
core::write!(f, "Endpoint contains invalid characters")
}
InvalidEndpointError::MaxLengthExceeded => {
core::write!(
f,
"Endpoint name exceeds maximum length of 18 characters"
)
}
InvalidEndpointError::MinLengthNotMet => {
core::write!(
f,
"Endpoint name must be at least 3 characters long"
)
}
InvalidEndpointError::InvalidInstance => {
core::write!(f, "Endpoint instance must be between 1 and 65534")
}
InvalidEndpointError::ReservedName => {
core::write!(f, "Endpoint name is reserved")
}
}
}
}
#[derive(PartialEq, Debug)]
pub struct EndpointParsingError;
impl Endpoint {
const PREFIX_PERSON: &'static str = "@";
const PREFIX_INSTITUTION: &'static str = "@+";
const PREFIX_ANONYMOUS: &'static str = "@@";
const ALIAS_LOCAL: &'static str = "local";
const ALIAS_ANY: &'static str = "any";
pub const ANY: Endpoint = Endpoint {
ty: EndpointType::Anonymous,
identifier: [255; 18],
instance: EndpointInstance::Any,
};
pub const ANY_ALL_INSTANCES: Endpoint = Endpoint {
ty: EndpointType::Anonymous,
identifier: [255; 18],
instance: EndpointInstance::All,
};
pub const LOCAL: Endpoint = Endpoint {
ty: EndpointType::Anonymous,
identifier: [0; 18],
instance: EndpointInstance::Any,
};
pub const LOCAL_ALL_INSTANCES: Endpoint = Endpoint {
ty: EndpointType::Anonymous,
identifier: [0; 18],
instance: EndpointInstance::All,
};
pub fn random() -> Endpoint {
Self::anonymous(Self::random_anonymous_id(), EndpointInstance::Any)
.unwrap()
}
pub fn anonymous(
identifier: [u8; 18],
instance: EndpointInstance,
) -> Result<Endpoint, InvalidEndpointError> {
if identifier == [255; 18] {
return if instance == EndpointInstance::Any {
Ok(Endpoint::ANY)
} else if instance == EndpointInstance::All {
Ok(Endpoint::ANY_ALL_INSTANCES)
} else {
Ok(Endpoint {
ty: EndpointType::Anonymous,
identifier,
instance,
})
};
}
if identifier == [0; 18] {
return if instance == EndpointInstance::Any {
Ok(Endpoint::LOCAL)
} else if instance == EndpointInstance::All {
Ok(Endpoint::LOCAL_ALL_INSTANCES)
} else {
Ok(Endpoint {
ty: EndpointType::Anonymous,
identifier,
instance,
})
};
}
Ok(Endpoint {
ty: EndpointType::Anonymous,
identifier,
instance,
})
}
pub fn new(name: &str) -> Endpoint {
Endpoint::from_string(name).unwrap_or_else(|_| {
panic!("Failed to convert str {name} to Endpoint")
})
}
pub fn person(
name: &str,
instance: EndpointInstance,
) -> Result<Endpoint, InvalidEndpointError> {
Self::named(name, instance, EndpointType::Person)
}
pub fn institution(
name: &str,
instance: EndpointInstance,
) -> Result<Endpoint, InvalidEndpointError> {
Self::named(name, instance, EndpointType::Institution)
}
pub fn as_local_if_endpoint(&self, endpoint: &Endpoint) -> Endpoint {
if self == endpoint {
Endpoint::LOCAL
} else {
self.clone()
}
}
fn from_string(name: &str) -> Result<Endpoint, InvalidEndpointError> {
let name = name.to_string();
if name
== format!("{}{}", Endpoint::PREFIX_ANONYMOUS, Endpoint::ALIAS_ANY)
{
return Ok(Endpoint::ANY);
} else if name
== format!(
"{}{}",
Endpoint::PREFIX_ANONYMOUS,
Endpoint::ALIAS_LOCAL
)
{
return Ok(Endpoint::LOCAL);
}
let mut name_part = name.clone();
let mut instance = EndpointInstance::Any;
if name.contains('/') {
let parts: Vec<&str> = name.split('/').collect();
if parts.len() != 2 {
return Err(InvalidEndpointError::InvalidCharacters);
}
name_part = parts[0].to_string();
let instance_str = parts[1];
if instance_str == "*" {
instance = EndpointInstance::All;
} else {
let instance_num = instance_str
.parse::<u16>()
.map_err(|_| InvalidEndpointError::InvalidInstance)?;
instance = EndpointInstance::new(instance_num);
}
}
match name_part {
s if s.starts_with(&format!(
"{}{}",
Endpoint::PREFIX_ANONYMOUS,
Endpoint::ALIAS_ANY
)) =>
{
Ok(Endpoint {
ty: EndpointType::Anonymous,
identifier: [255u8; 18],
instance,
})
}
s if s.starts_with(&format!(
"{}{}",
Endpoint::PREFIX_ANONYMOUS,
Endpoint::ALIAS_LOCAL
)) =>
{
Ok(Endpoint {
ty: EndpointType::Anonymous,
identifier: [0u8; 18],
instance,
})
}
s if s.starts_with(Endpoint::PREFIX_ANONYMOUS) => {
let s = s.trim_start_matches(Endpoint::PREFIX_ANONYMOUS);
if s.len() < 18 * 2 {
return Err(InvalidEndpointError::MinLengthNotMet);
} else if s.len() > 18 * 2 {
return Err(InvalidEndpointError::MaxLengthExceeded);
}
let bytes = decode(s)
.map_err(|_| InvalidEndpointError::InvalidCharacters)?;
let byte_slice: &[u8] = &bytes;
Endpoint::anonymous(byte_slice.try_into().unwrap(), instance)
}
s if s.starts_with(Endpoint::PREFIX_INSTITUTION) => {
Endpoint::named(&s[2..], instance, EndpointType::Institution)
}
s if s.starts_with(Endpoint::PREFIX_PERSON) => {
Endpoint::named(&s[1..], instance, EndpointType::Person)
}
_ => Err(InvalidEndpointError::InvalidCharacters),
}
}
pub fn from_slice(
binary: [u8; 21],
) -> Result<Endpoint, EndpointParsingError> {
let mut reader = Cursor::new(binary);
let endpoint =
Endpoint::read(&mut reader).map_err(|_| EndpointParsingError)?;
if !Self::is_endpoint_valid(&endpoint) {
return Err(EndpointParsingError);
}
Ok(endpoint)
}
fn named(
name: &str,
instance: EndpointInstance,
type_: EndpointType,
) -> Result<Endpoint, InvalidEndpointError> {
if !Self::is_instance_valid(&instance) {
return Err(InvalidEndpointError::InvalidInstance);
}
let name_bytes = Endpoint::name_to_bytes(name)?;
Ok(Endpoint {
ty: type_,
identifier: name_bytes,
instance,
})
}
fn name_to_bytes(name: &str) -> Result<[u8; 18], InvalidEndpointError> {
let mut identifier = String::into_bytes(
name.to_string().trim_end_matches('\0').to_string(),
);
if identifier.len() > 18 {
return Err(InvalidEndpointError::MaxLengthExceeded);
}
if identifier.len() < 3 {
return Err(InvalidEndpointError::MinLengthNotMet);
}
identifier.resize(18, 0);
if !Self::are_name_chars_valid(identifier.clone().try_into().unwrap()) {
return Err(InvalidEndpointError::InvalidCharacters);
};
Ok(identifier.try_into().unwrap())
}
fn random_anonymous_id() -> [u8; 18] {
let buffer = CryptoImpl::random_bytes(18);
if buffer.iter().any(|&b| b != 0) {
return buffer.try_into().unwrap();
}
panic!("Could not generate random anonymous id");
}
fn are_name_chars_valid(name: [u8; 18]) -> bool {
let mut is_null = false;
for c in name.iter() {
if is_null && *c != 0x00 {
return false;
}
if *c == 0x00 {
is_null = true;
continue;
}
if !(*c >= 0x30 && *c <= 0x39 || *c >= 0x61 && *c <= 0x7A) && *c != 0x2D && *c != 0x5F
{
return false;
}
}
true
}
fn is_endpoint_valid(endpoint: &Endpoint) -> bool {
if !Self::is_instance_valid(&endpoint.instance) {
return false;
}
match endpoint.ty {
EndpointType::Person | EndpointType::Institution => {
Self::are_name_chars_valid(endpoint.identifier)
}
_ => true,
}
}
fn is_instance_valid(endpoint_instance: &EndpointInstance) -> bool {
match endpoint_instance {
EndpointInstance::All => true,
EndpointInstance::Any => true,
EndpointInstance::Instance(instance) => {
*instance > 0 && *instance < 65535
}
}
}
pub fn is_local_or_equals_endpoint(&self, endpoint: &Endpoint) -> bool {
if self.is_local() {
return true;
}
self == endpoint
}
pub fn to_slice(&self) -> [u8; 21] {
let mut writer = Cursor::new(Vec::new());
self.write(&mut writer).unwrap();
writer.into_inner().try_into().unwrap()
}
pub fn ty(&self) -> EndpointType {
self.ty
}
pub fn instance(&self) -> EndpointInstance {
self.instance
}
pub fn is_local(&self) -> bool {
self == &Endpoint::LOCAL
}
pub fn is_any(&self) -> bool {
self == &Endpoint::ANY
}
pub fn instance_is_broadcast(&self) -> bool {
self.instance == EndpointInstance::All
}
pub fn is_any_instance(&self) -> bool {
self.instance == EndpointInstance::Any
}
pub fn any_instance(&self) -> Endpoint {
Endpoint {
ty: self.ty,
identifier: self.identifier,
instance: EndpointInstance::Any,
}
}
pub fn all_instances(&self) -> Endpoint {
Endpoint {
ty: self.ty,
identifier: self.identifier,
instance: EndpointInstance::All,
}
}
}
impl Display for Endpoint {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self.ty {
EndpointType::Anonymous => {
if self.identifier == [255; 18] {
core::write!(
f,
"{}{}",
Endpoint::PREFIX_ANONYMOUS,
Endpoint::ALIAS_ANY
)?;
}
else if self.identifier == [0; 18] {
core::write!(
f,
"{}{}",
Endpoint::PREFIX_ANONYMOUS,
Endpoint::ALIAS_LOCAL
)?;
}
else {
core::write!(
f,
"{}{}",
Endpoint::PREFIX_ANONYMOUS,
buffer_to_hex(self.identifier.to_vec())
)?
}
}
EndpointType::Person => core::write!(
f,
"{}{}",
Endpoint::PREFIX_PERSON,
str::from_utf8(&self.identifier)
.unwrap()
.trim_end_matches('\0')
)?,
EndpointType::Institution => core::write!(
f,
"{}{}",
Endpoint::PREFIX_INSTITUTION,
str::from_utf8(&self.identifier)
.unwrap()
.trim_end_matches('\0')
)?,
};
match self.instance {
EndpointInstance::Any => (),
EndpointInstance::All => f.write_str("/*")?,
EndpointInstance::Instance(instance) => {
core::write!(f, "/{instance}")?
}
};
Ok(())
}
}
impl FromStr for Endpoint {
type Err = InvalidEndpointError;
fn from_str(name: &str) -> Result<Self, Self::Err> {
Endpoint::from_string(name)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utilities() {
let endpoint: Endpoint = Endpoint::from_string("@ben/42").unwrap();
assert!(!endpoint.is_any_instance());
assert!(!endpoint.instance_is_broadcast());
let main_endpoint = endpoint.any_instance();
assert!(main_endpoint.is_any_instance());
assert_eq!(main_endpoint.to_string(), "@ben");
assert_eq!(main_endpoint.instance, EndpointInstance::Any);
let broadcast_endpoint = endpoint.all_instances();
assert!(broadcast_endpoint.instance_is_broadcast());
assert_eq!(broadcast_endpoint.to_string(), "@ben/*");
}
#[test]
fn parse_from_string() {
let endpoint = Endpoint::from_string("@jonas").unwrap();
assert_eq!(endpoint.ty, EndpointType::Person);
assert_eq!(endpoint.instance, EndpointInstance::Any);
assert_eq!(endpoint.to_string(), "@jonas");
assert_eq!(
endpoint.identifier,
[
106, 111, 110, 97, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
]
);
let endpoint = Endpoint::from_string("@+unyt").unwrap();
assert_eq!(endpoint.ty, EndpointType::Institution);
assert_eq!(endpoint.instance, EndpointInstance::Any);
assert_eq!(endpoint.to_string(), "@+unyt");
let endpoint = Endpoint::from_string(
&format!("@@{}", "A".repeat(18 * 2)).to_string(),
)
.unwrap();
assert_eq!(endpoint.ty, EndpointType::Anonymous);
assert_eq!(endpoint.instance, EndpointInstance::Any);
assert_eq!(endpoint.to_string(), format!("@@{}", "A".repeat(18 * 2)));
let valid_endpoint_names = vec![
"@jonas",
"@@any/*",
"@@local",
"@+unyt",
"@test/42",
"@test/*",
"@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
"@@BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
"@+institution/42",
"@+deno/9999",
"@+deno/65534",
];
for name in valid_endpoint_names {
let endpoint = Endpoint::from_string(name).unwrap();
assert_eq!(endpoint.to_string(), name);
}
}
#[test]
fn too_long() {
let endpoint =
Endpoint::person("too-long-endpoint-name", EndpointInstance::Any);
assert_eq!(endpoint, Err(InvalidEndpointError::MaxLengthExceeded));
let endpoint = Endpoint::from_string("@too-long-endpoint-name");
assert_eq!(endpoint, Err(InvalidEndpointError::MaxLengthExceeded));
let to_long_endpoint_names = vec![
"@too-long-endpoint-name",
"@@FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA",
"@+too-long-endpoint-name",
"@@FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA/0001",
];
for name in to_long_endpoint_names {
let endpoint = Endpoint::from_string(name);
assert_eq!(endpoint, Err(InvalidEndpointError::MaxLengthExceeded));
}
}
#[test]
fn too_short() {
let endpoint = Endpoint::person("ab", EndpointInstance::Any);
assert_eq!(endpoint, Err(InvalidEndpointError::MinLengthNotMet));
let endpoint =
Endpoint::person("ab\0\0\0\0\0\0\0\0", EndpointInstance::Any);
assert_eq!(endpoint, Err(InvalidEndpointError::MinLengthNotMet));
let endpoint = Endpoint::from_string("@ab");
assert_eq!(endpoint, Err(InvalidEndpointError::MinLengthNotMet));
let to_short_endpoint_names = vec![
"@ab",
"@@ff",
"@+ff",
"@@fffffff",
"@ab\0\0\0\0\0\0\0\0",
"@@FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA/0001",
];
for name in to_short_endpoint_names {
let endpoint = Endpoint::from_string(name);
assert_eq!(endpoint, Err(InvalidEndpointError::MinLengthNotMet));
}
}
#[test]
fn invalid_characters() {
let endpoint = Endpoint::person("äüö", EndpointInstance::Any);
assert_eq!(endpoint, Err(InvalidEndpointError::InvalidCharacters));
let endpoint = Endpoint::person("__O", EndpointInstance::Any);
assert_eq!(endpoint, Err(InvalidEndpointError::InvalidCharacters));
let endpoint = Endpoint::person("#@!", EndpointInstance::Any);
assert_eq!(endpoint, Err(InvalidEndpointError::InvalidCharacters));
let endpoint = Endpoint::person("\0__", EndpointInstance::Any);
assert_eq!(endpoint, Err(InvalidEndpointError::InvalidCharacters));
let endpoint = Endpoint::from_string("@äüö");
assert_eq!(endpoint, Err(InvalidEndpointError::InvalidCharacters));
let endpoint = Endpoint::from_string("@Jonas");
assert_eq!(endpoint, Err(InvalidEndpointError::InvalidCharacters));
let endpoint =
Endpoint::from_string(&format!("@@{}X", "F".repeat(18 * 2 - 1)));
assert_eq!(endpoint, Err(InvalidEndpointError::InvalidCharacters));
let invalid_endpoint_names = vec![
"@äüö",
"@@FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFX",
"@+äüö",
"@@FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFX/0001",
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFX/0001",
"test",
"@dff@",
"1",
"",
];
for name in invalid_endpoint_names {
let endpoint = Endpoint::from_string(name);
assert_eq!(endpoint, Err(InvalidEndpointError::InvalidCharacters));
}
}
#[test]
fn invalid_instance() {
let endpoint = Endpoint::person("test", EndpointInstance::Instance(0));
assert_eq!(endpoint, Err(InvalidEndpointError::InvalidInstance));
let endpoint =
Endpoint::person("test", EndpointInstance::Instance(65535));
assert_eq!(endpoint, Err(InvalidEndpointError::InvalidInstance));
}
#[test]
fn special_instances() {
let endpoint = Endpoint::from_string("@+unyt/0");
assert_eq!(
endpoint,
Ok(Endpoint {
ty: EndpointType::Institution,
identifier: Endpoint::name_to_bytes("unyt").unwrap(),
instance: EndpointInstance::Any,
})
);
let endpoint = Endpoint::from_string("@+unyt/65535");
assert_eq!(
endpoint,
Ok(Endpoint {
ty: EndpointType::Institution,
identifier: Endpoint::name_to_bytes("unyt").unwrap(),
instance: EndpointInstance::All,
})
);
let endpoint = Endpoint::from_string("@+unyt/*");
assert_eq!(
endpoint,
Ok(Endpoint {
ty: EndpointType::Institution,
identifier: Endpoint::name_to_bytes("unyt").unwrap(),
instance: EndpointInstance::All,
})
);
}
#[test]
fn any_instance() {
let binary = [
EndpointType::Anonymous as u8,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0x00,
0x00,
];
let endpoint = Endpoint::from_slice(binary);
assert_eq!(endpoint, Ok(Endpoint::ANY));
}
#[test]
fn special_endpoints() {
let endpoint = Endpoint::from_string("@@any").unwrap();
assert_eq!(endpoint.to_string(), "@@any");
assert_eq!(endpoint, Endpoint::ANY);
let endpoint = Endpoint::from_string("@@any/42").unwrap();
assert_eq!(endpoint.to_string(), "@@any/42");
let endpoint = Endpoint::from_string("@@local").unwrap();
assert_eq!(endpoint.to_string(), "@@local");
assert_eq!(endpoint, Endpoint::LOCAL);
let endpoint =
Endpoint::from_string("@@FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")
.unwrap();
assert_eq!(endpoint, Endpoint::ANY);
let endpoint =
Endpoint::from_string("@@000000000000000000000000000000000000")
.unwrap();
assert_eq!(endpoint, Endpoint::LOCAL);
}
#[test]
fn format_named_endpoint() {
let endpoint = Endpoint::person("test", EndpointInstance::Any).unwrap();
assert_eq!(endpoint.to_string(), "@test");
let endpoint =
Endpoint::institution("test", EndpointInstance::Any).unwrap();
assert_eq!(endpoint.to_string(), "@+test");
let endpoint =
Endpoint::person("test", EndpointInstance::Instance(42)).unwrap();
assert_eq!(endpoint.to_string(), "@test/42");
let endpoint = Endpoint::person("test", EndpointInstance::All).unwrap();
assert_eq!(endpoint.to_string(), "@test/*");
}
#[test]
fn format_anonymous_endpoint() {
let endpoint =
Endpoint::anonymous([0xaa; 18], EndpointInstance::Any).unwrap();
assert_eq!(
endpoint.to_string(),
"@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
);
let endpoint =
Endpoint::from_string("@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/42")
.unwrap();
assert_eq!(
endpoint.to_string(),
"@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/42"
);
}
#[test]
fn random_anonymous_endpoint() {
let endpoint1 = Endpoint::random();
let endpoint2 = Endpoint::random();
assert_ne!(endpoint1, endpoint2);
assert_eq!(endpoint1.ty, EndpointType::Anonymous);
assert_eq!(endpoint2.ty, EndpointType::Anonymous);
}
}