use super::OutputOptions;
use super::dsdiff::{DsdiffDeparture, chunk};
use crate::error::Error;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CommentKind {
General,
Channel(u16),
SoundSource(u16),
FileHistory(u16),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Comment {
pub year: u16,
pub month: u8,
pub day: u8,
pub hour: u8,
pub minutes: u8,
pub kind: CommentKind,
pub text: String,
}
impl Comment {
pub fn new(kind: CommentKind, text: &str) -> Self {
Comment { year: 0, month: 0, day: 0, hour: 0, minutes: 0, kind, text: text.to_owned() }
}
}
pub(super) fn text_bytes(s: &str, options: &OutputOptions) -> Vec<u8> {
if options.departs(DsdiffDeparture::D2) {
return s.chars().filter(|&c| latin1(c)).map(|c| c as u8).collect();
}
let replacement = options.dsdiff_text_replacement;
s.chars().filter_map(|c| if (' '..='~').contains(&c) { Some(c as u8) } else { replacement }).collect()
}
fn latin1(c: char) -> bool {
(' '..='~').contains(&c) || ('\u{A0}'..='\u{FF}').contains(&c)
}
pub(super) fn diin_text(out: &mut Vec<u8>, id: &[u8; 4], text: Option<&str>, options: &OutputOptions) {
let Some(text) = text else { return };
let t = text_bytes(text, options);
if t.is_empty() && !options.dsdiff_empty_text {
return;
}
let mut d = (t.len() as u32).to_be_bytes().to_vec();
d.extend_from_slice(&t);
if options.dsdiff_text_pad_counted && t.len() % 2 == 1 {
d.push(0);
}
chunk(out, id, &d);
}
pub(super) fn comt(channels: u8, options: &OutputOptions) -> Result<Option<Vec<u8>>, Error> {
let mut data = vec![0, 0];
let mut count = 0u16;
for c in &options.dsdiff_comments {
if c.month > 12 || c.day > 31 || c.hour > 23 || c.minutes > 59 {
return Err(Error::InvalidArgument("a comment's time stamp is out of range"));
}
let (kind, reference) = match c.kind {
CommentKind::General => (0u16, 0u16),
CommentKind::Channel(r) if r <= u16::from(channels) => (1, r),
CommentKind::SoundSource(r) if r <= 2 => (2, r),
CommentKind::FileHistory(r) if r <= 4 => (3, r),
_ => return Err(Error::InvalidArgument("a comment's reference is out of range")),
};
let t = text_bytes(&c.text, options);
if t.is_empty() && !options.dsdiff_empty_text {
continue;
}
count = count.checked_add(1).ok_or(Error::InvalidArgument("at most 65 535 comments"))?;
data.extend_from_slice(&c.year.to_be_bytes());
data.extend_from_slice(&[c.month, c.day, c.hour, c.minutes]);
data.extend_from_slice(&kind.to_be_bytes());
data.extend_from_slice(&reference.to_be_bytes());
data.extend_from_slice(&(t.len() as u32).to_be_bytes());
data.extend_from_slice(&t);
if t.len() % 2 == 1 {
data.push(0);
}
}
if count == 0 {
return Ok(None);
}
data[..2].copy_from_slice(&count.to_be_bytes());
let mut out = Vec::new();
chunk(&mut out, b"COMT", &data);
Ok(Some(out))
}