use crate::klv::{self, be_uint, Items};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum Tag {
SecurityClassification = 1,
CountryCodingMethod = 2,
ClassifyingCountry = 3,
SciShiInformation = 4,
Caveats = 5,
ReleasingInstructions = 6,
ClassifiedBy = 7,
DerivedFrom = 8,
ClassificationReason = 9,
DeclassificationDate = 10,
ClassificationAndMarkingSystem = 11,
ObjectCountryCodingMethod = 12,
ObjectCountryCodes = 13,
ClassificationComments = 14,
StreamId = 19,
TransportStreamId = 20,
ItemDesignatorId = 21,
Version = 22,
CountryCodingMethodVersionDate = 23,
ObjectCountryCodingMethodVersionDate = 24,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Classification {
Unclassified,
Restricted,
Confidential,
Secret,
TopSecret,
Other(u8),
}
impl Classification {
pub fn from_u8(v: u8) -> Self {
match v {
1 => Classification::Unclassified,
2 => Classification::Restricted,
3 => Classification::Confidential,
4 => Classification::Secret,
5 => Classification::TopSecret,
o => Classification::Other(o),
}
}
pub fn to_u8(self) -> u8 {
match self {
Classification::Unclassified => 1,
Classification::Restricted => 2,
Classification::Confidential => 3,
Classification::Secret => 4,
Classification::TopSecret => 5,
Classification::Other(o) => o,
}
}
pub fn as_str(self) -> &'static str {
match self {
Classification::Unclassified => "UNCLASSIFIED",
Classification::Restricted => "RESTRICTED",
Classification::Confidential => "CONFIDENTIAL",
Classification::Secret => "SECRET",
Classification::TopSecret => "TOP SECRET",
Classification::Other(_) => "UNKNOWN",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SecuritySet<'a> {
body: &'a [u8],
}
impl<'a> SecuritySet<'a> {
pub fn new(body: &'a [u8]) -> Self {
SecuritySet { body }
}
pub fn body(&self) -> &'a [u8] {
self.body
}
pub fn items(&self) -> Items<'a> {
Items::new(self.body)
}
pub fn raw(&self, tag: Tag) -> Option<&'a [u8]> {
klv::find(self.body, tag as u32)
}
pub fn classification(&self) -> Option<Classification> {
match self.raw(Tag::SecurityClassification)? {
[v] => Some(Classification::from_u8(*v)),
_ => None,
}
}
pub fn text(&self, tag: Tag) -> Option<&'a str> {
core::str::from_utf8(self.raw(tag)?).ok()
}
pub fn country_coding_method(&self) -> Option<u8> {
self.raw(Tag::CountryCodingMethod)
.and_then(be_uint)
.map(|v| v as u8)
}
pub fn object_country_codes(&self) -> Option<CountryCodes<'a>> {
self.raw(Tag::ObjectCountryCodes)
.map(|raw| CountryCodes { raw })
}
pub fn version(&self) -> Option<u64> {
self.raw(Tag::Version).and_then(be_uint)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CountryCodes<'a> {
raw: &'a [u8],
}
impl<'a> CountryCodes<'a> {
pub fn raw(&self) -> &'a [u8] {
self.raw
}
fn is_utf16(&self) -> bool {
self.raw.len() % 2 == 0
&& !self.raw.is_empty()
&& self.raw.iter().step_by(2).all(|&b| b == 0)
}
pub fn chars(&self) -> impl Iterator<Item = char> + 'a {
let utf16 = self.is_utf16();
let raw = self.raw;
let units = (0..if utf16 { raw.len() / 2 } else { raw.len() }).map(move |i| {
if utf16 {
u16::from_be_bytes([raw[2 * i], raw[2 * i + 1]])
} else {
raw[i] as u16
}
});
core::char::decode_utf16(units).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER))
}
pub fn eq_str(&self, s: &str) -> bool {
self.chars().eq(s.chars())
}
}
#[cfg(feature = "alloc")]
pub use builder::Builder;
#[cfg(feature = "alloc")]
mod builder {
use super::*;
use crate::klv::enc;
use crate::Error;
use alloc::vec::Vec;
#[derive(Clone, Debug)]
pub struct Builder {
body: Vec<u8>,
}
impl Builder {
pub fn new(classification: Classification, classifying_country: &str) -> Self {
let mut body = Vec::new();
enc::push_item(&mut body, 1, &[classification.to_u8()]).expect("small item");
enc::push_item(&mut body, 2, &[7]).expect("small item");
enc::push_item(&mut body, 3, classifying_country.as_bytes()).expect("small item");
Builder { body }
}
pub fn text(&mut self, tag: Tag, value: &str) -> Result<&mut Self, Error> {
if tag == Tag::ObjectCountryCodes {
return self.object_country_codes(value);
}
enc::push_item(&mut self.body, tag as u32, value.as_bytes())?;
Ok(self)
}
pub fn object_country_codes(&mut self, value: &str) -> Result<&mut Self, Error> {
let units: Vec<u8> = value.encode_utf16().flat_map(u16::to_be_bytes).collect();
enc::push_item(&mut self.body, 12, &[7])?;
enc::push_item(&mut self.body, 13, &units)?;
Ok(self)
}
pub fn raw(&mut self, tag: u32, value: &[u8]) -> Result<&mut Self, Error> {
enc::push_item(&mut self.body, tag, value)?;
Ok(self)
}
pub fn body(&self) -> Vec<u8> {
let mut b = self.body.clone();
enc::push_item(&mut b, 22, &12u16.to_be_bytes()).expect("small item");
b
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_sample_set() {
let body = [
0x01, 0x01, 0x01, 0x02, 0x01, 0x07, 0x03, 0x05, b'/', b'/', b'U', b'S', b'A', 0x0C,
0x01, 0x07, 0x0D, 0x06, 0x00, 0x55, 0x00, 0x53, 0x00, 0x41, 0x16, 0x02, 0x00, 0x0A,
];
let s = SecuritySet::new(&body);
assert_eq!(s.classification(), Some(Classification::Unclassified));
assert_eq!(s.text(Tag::ClassifyingCountry), Some("//USA"));
assert!(s.object_country_codes().unwrap().eq_str("USA"));
assert_eq!(s.version(), Some(10));
assert_eq!(s.country_coding_method(), Some(7));
}
#[cfg(feature = "alloc")]
#[test]
fn builder_round_trip() {
let mut b = Builder::new(Classification::Unclassified, "//USA");
b.object_country_codes("USA;CAN").unwrap();
let body = b.body();
let s = SecuritySet::new(&body);
assert_eq!(s.classification(), Some(Classification::Unclassified));
assert!(s.object_country_codes().unwrap().eq_str("USA;CAN"));
assert_eq!(s.version(), Some(12));
}
}