use alloc::string::String;
use alloc::vec::Vec;
use crate::ber::{Cursor, Encoder, Tag, Tlv, universal};
use crate::common::{Error, Limits, Result};
pub const TAG_GRAPHIC_STRING: Tag = Tag::universal(universal::GRAPHIC_STRING, false);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct FileName<'a>(&'a [u8]);
impl<'a> FileName<'a> {
pub const fn from_encoded(contents: &'a [u8]) -> FileName<'a> {
FileName(contents)
}
pub const fn as_encoded(&self) -> &'a [u8] {
self.0
}
pub fn components(&self) -> impl Iterator<Item = &'a str> {
Cursor::new(self.0).map_while(Result::ok).map_while(|t| t.visible_string().ok())
}
pub fn display(&self) -> String {
let mut out = String::new();
for (n, part) in self.components().enumerate() {
if n > 0 {
out.push('/');
}
out.push_str(part);
}
out
}
pub fn parse(t: &Tlv<'a>, limits: &Limits) -> Result<FileName<'a>> {
let mut n = 0usize;
for part in t.children() {
let part = part?;
if part.value.len() > limits.max_primitive_len {
return Err(Error::LimitExceeded { limit: "max_primitive_len", value: part.value.len() });
}
part.visible_string()?;
n += 1;
if n > 32 {
return Err(Error::LimitExceeded { limit: "file name components", value: n });
}
}
Ok(FileName(t.value))
}
pub fn write_contents(&self, e: &mut Encoder) {
e.raw(self.0);
}
}
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct FileNameBuf(Vec<u8>);
impl FileNameBuf {
pub fn from_path(path: &str) -> Result<FileNameBuf> {
let mut e = Encoder::new();
e.visible_string(TAG_GRAPHIC_STRING, path)?;
Ok(FileNameBuf(e.into_vec()))
}
pub fn from_components(parts: &[&str]) -> Result<FileNameBuf> {
let mut e = Encoder::new();
for p in parts {
e.visible_string(TAG_GRAPHIC_STRING, p)?;
}
Ok(FileNameBuf(e.into_vec()))
}
pub fn as_name(&self) -> FileName<'_> {
FileName(&self.0)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FileAttributes<'a> {
pub size: u32,
pub last_modified: Option<&'a str>,
}
impl<'a> FileAttributes<'a> {
pub(super) fn parse(t: &Tlv<'a>) -> Result<FileAttributes<'a>> {
let mut c = t.children();
let size = c.next_tag(Tag::context(0))?.unsigned_lenient_u32()?;
let last_modified = c.next_if_tag(Tag::context(1))?.map(|t| t.visible_string()).transpose()?;
Ok(FileAttributes { size, last_modified })
}
pub(super) fn write(&self, tag: Tag, e: &mut Encoder) -> Result<()> {
e.constructed(tag, |e| {
e.unsigned(Tag::context(0), u64::from(self.size))?;
if let Some(m) = self.last_modified {
e.visible_string(Tag::context(1), m)?;
}
Ok(())
})?;
Ok(())
}
}
pub(super) fn directory_entries<'a>(list: &Tlv<'a>) -> Cursor<'a> {
let mut outer = list.children();
let Some(Ok(first)) = outer.next() else { return list.children() };
if first.tag != Tag::universal(universal::SEQUENCE, true) {
return list.children();
}
match first.children().next() {
Some(Ok(inner)) if inner.tag == Tag::universal(universal::SEQUENCE, true) => first.children(),
None => first.children(),
_ => list.children(),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DirectoryEntry<'a> {
pub name: FileName<'a>,
pub attributes: FileAttributes<'a>,
}
impl<'a> DirectoryEntry<'a> {
pub(super) fn parse(t: &Tlv<'a>, limits: &Limits) -> Result<DirectoryEntry<'a>> {
let mut c = t.expect(Tag::universal(universal::SEQUENCE, true))?.children();
let name = FileName::parse(&c.next_tag(Tag::context_constructed(0))?, limits)?;
let attributes = FileAttributes::parse(&c.next_tag(Tag::context_constructed(1))?)?;
Ok(DirectoryEntry { name, attributes })
}
pub(super) fn write(&self, e: &mut Encoder) -> Result<()> {
e.constructed(Tag::universal(universal::SEQUENCE, true), |e| {
e.constructed(Tag::context_constructed(0), |e| {
self.name.write_contents(e);
Ok(())
})?;
self.attributes.write(Tag::context_constructed(1), e)?;
Ok(())
})?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_path_is_one_component_and_reads_back_as_the_path() {
let buf = FileNameBuf::from_path("COMTRADE/rec0001.cfg").unwrap();
let name = buf.as_name();
assert_eq!(name.components().collect::<Vec<_>>(), ["COMTRADE/rec0001.cfg"]);
assert_eq!(name.display(), "COMTRADE/rec0001.cfg");
let split = FileNameBuf::from_components(&["COMTRADE", "rec0001.cfg"]).unwrap();
assert_eq!(split.as_name().display(), "COMTRADE/rec0001.cfg");
assert_eq!(split.as_name().components().count(), 2);
}
#[test]
fn a_file_name_survives_a_decode_and_re_encode() {
let buf = FileNameBuf::from_components(&["a", "b"]).unwrap();
let mut e = Encoder::new();
e.constructed(Tag::context_constructed(0), |e| {
buf.as_name().write_contents(e);
Ok(())
})
.unwrap();
let bytes = e.into_vec();
let t = Cursor::new(&bytes).next_required().unwrap();
let name = FileName::parse(&t, &Limits::DEFAULT).unwrap();
assert_eq!(name.as_encoded(), buf.as_name().as_encoded());
}
}