use alloc::{collections::BTreeMap, string::String};
use thiserror::Error;
pub const MAXIMUM_COMMON_TABLE_ENTRIES: usize = 65_536;
pub const MAXIMUM_COMMON_TABLE_TEXT_BYTES: usize = 1024;
pub const DEFAULT_MAXIMUM_TABLES: usize = 1024;
pub const DEFAULT_MAXIMUM_TABLE_ENTRIES: usize = 1_048_576;
pub const MAXIMUM_TABLES: usize = 4096;
pub const MAXIMUM_TABLE_ENTRIES: usize = 4_194_304;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TableRepositoryLimits {
pub tables: usize,
pub entries: usize,
}
impl Default for TableRepositoryLimits {
fn default() -> Self {
Self {
tables: DEFAULT_MAXIMUM_TABLES,
entries: DEFAULT_MAXIMUM_TABLE_ENTRIES,
}
}
}
impl TableRepositoryLimits {
pub const fn with_tables(mut self, tables: usize) -> Self {
self.tables = tables;
self
}
pub const fn with_entries(mut self, entries: usize) -> Self {
self.entries = entries;
self
}
pub const fn validate(self) -> Result<(), TableError> {
if self.tables == 0 || self.entries == 0 {
return Err(TableError::ZeroRepositoryLimit);
}
if self.tables > MAXIMUM_TABLES {
return Err(TableError::RepositoryTableLimit(self.tables));
}
if self.entries > MAXIMUM_TABLE_ENTRIES {
return Err(TableError::RepositoryEntryLimit(self.entries));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableEntry {
pub code: u32,
pub label: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommonTable {
pub number: u16,
pub revision: String,
pub entries: BTreeMap<u32, TableEntry>,
}
impl CommonTable {
pub fn validate(&self) -> Result<(), TableError> {
if self.revision.trim().is_empty() {
return Err(TableError::MissingRevision(self.number));
}
if self.revision.len() > MAXIMUM_COMMON_TABLE_TEXT_BYTES {
return Err(TableError::TextTooLong("revision", self.revision.len()));
}
if self.entries.len() > MAXIMUM_COMMON_TABLE_ENTRIES {
return Err(TableError::TooManyEntries(self.entries.len()));
}
for (code, entry) in &self.entries {
if *code != entry.code {
return Err(TableError::MismatchedCode {
key: *code,
value: entry.code,
});
}
if entry.label.trim().is_empty() {
return Err(TableError::EmptyLabel(*code));
}
if entry.label.len() > MAXIMUM_COMMON_TABLE_TEXT_BYTES {
return Err(TableError::TextTooLong("entry label", entry.label.len()));
}
}
Ok(())
}
pub fn resolve(&self, code: u32) -> ResolvedCode<'_> {
match self.entries.get(&code) {
Some(entry) => ResolvedCode::Known(entry),
None => ResolvedCode::Unknown(code),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolvedCode<'a> {
Known(&'a TableEntry),
Unknown(u32),
}
#[derive(Debug, Clone)]
pub struct TableRepository {
tables: BTreeMap<u16, CommonTable>,
limits: TableRepositoryLimits,
total_entries: usize,
}
impl Default for TableRepository {
fn default() -> Self {
Self::new()
}
}
impl TableRepository {
pub const fn new() -> Self {
Self {
tables: BTreeMap::new(),
limits: TableRepositoryLimits {
tables: DEFAULT_MAXIMUM_TABLES,
entries: DEFAULT_MAXIMUM_TABLE_ENTRIES,
},
total_entries: 0,
}
}
pub fn with_limits(limits: TableRepositoryLimits) -> Result<Self, TableError> {
limits.validate()?;
Ok(Self {
tables: BTreeMap::new(),
limits,
total_entries: 0,
})
}
pub fn replace(&mut self, table: CommonTable) -> Result<Option<CommonTable>, TableError> {
table.validate()?;
let previous = self.tables.get(&table.number);
let previous_entries = previous.map_or(0, |table| table.entries.len());
if previous.is_none() && self.tables.len() >= self.limits.tables {
return Err(TableError::RepositoryTableLimit(self.limits.tables));
}
let total_entries = self
.total_entries
.checked_sub(previous_entries)
.and_then(|count| count.checked_add(table.entries.len()))
.ok_or(TableError::RepositoryEntryLimit(self.limits.entries))?;
if total_entries > self.limits.entries {
return Err(TableError::RepositoryEntryLimit(self.limits.entries));
}
let previous = self.tables.insert(table.number, table);
self.total_entries = total_entries;
Ok(previous)
}
pub fn get(&self, number: u16) -> Option<&CommonTable> {
self.tables.get(&number)
}
pub fn len(&self) -> usize {
self.tables.len()
}
pub fn is_empty(&self) -> bool {
self.tables.is_empty()
}
pub const fn total_entries(&self) -> usize {
self.total_entries
}
pub const fn limits(&self) -> TableRepositoryLimits {
self.limits
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum TableError {
#[error("table repository limits must be greater than zero")]
ZeroRepositoryLimit,
#[error("table repository table limit is {0}")]
RepositoryTableLimit(usize),
#[error("table repository entry limit is {0}")]
RepositoryEntryLimit(usize),
#[error("table {0} has no source revision")]
MissingRevision(u16),
#[error("map key {key} does not match entry code {value}")]
MismatchedCode {
key: u32,
value: u32,
},
#[error("code {0} has an empty name")]
EmptyLabel(u32),
#[error("table {0} contains {1} UTF-8 bytes")]
TextTooLong(&'static str, usize),
#[error("common table contains too many entries: {0}")]
TooManyEntries(usize),
}