wc3 0.2.0

Read, edit, and write Warcraft III models, BLP textures, and MPQ archives
Documentation
use super::{Dialect, Write};
use crate::model::mdl;
use crate::model::FixedText;
use crate::model::IoError;
use std::fmt::Arguments;
use std::io::{Cursor as IoCursor, Write as IoWrite};
use std::str::from_utf8;

/// Write MDL records to a standard I/O sink.
///
/// Use [`Writer::with_dialect`] to choose output syntax and [`Writer::finish`]
/// to check that all opened blocks were closed. Output uses tabs, LF, and
/// round-tripping float literals. Errors may leave partial output; use
/// [`Write::encode_mdl`] when you need a complete string before replacing a file.
pub struct Writer<W> {
    output: W,
    depth: usize,
    dialect: Dialect,
}
impl<W: IoWrite> Writer<W> {
    /// Creates a streaming writer using the Warcraft III dialect.
    pub fn new(output: W) -> Self {
        Self::with_dialect(output, Dialect::Warcraft3)
    }
    /// Creates a streaming writer for the selected syntax.
    pub fn with_dialect(output: W, dialect: Dialect) -> Self {
        Self {
            output,
            depth: 0,
            dialect,
        }
    }
    /// Returns the syntax selected for this writer and all nested values.
    pub fn dialect(&self) -> Dialect {
        self.dialect
    }
    /// Access the sink without checking block balance; prefer finish on success.
    pub fn into_inner(self) -> W {
        self.output
    }
    /// Checks block balance and returns the sink without flushing it.
    pub fn finish(self) -> Result<W, mdl::WriteError> {
        if self.depth != 0 {
            Err(mdl::WriteError::UnbalancedBlocks)
        } else {
            Ok(self.output)
        }
    }
    /// Streams a value through its MDL codec using this writer.
    pub fn write<T: Write + ?Sized>(&mut self, value: &T) -> Result<(), IoError<mdl::WriteError>> {
        value.write_mdl(self)
    }
    /// Writes literal punctuation or formatting; does not change indentation.
    pub fn raw(&mut self, value: &str) -> Result<(), IoError<mdl::WriteError>> {
        self.output.write_all(value.as_bytes())?;
        Ok(())
    }
    /// Writes an ASCII identifier, rejecting invalid characters before output.
    pub fn identifier(&mut self, value: &str) -> Result<(), IoError<mdl::WriteError>> {
        let mut bytes = value.bytes();
        if !bytes
            .next()
            .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
            || !bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
        {
            return Err(mdl::WriteError::InvalidIdentifier.into());
        }
        self.raw(value)
    }
    /// Strings have no escaping. Quotes and NUL cannot be represented; CR/LF
    /// and backslashes are written literally, per the Warcraft III dialect.
    pub fn quoted(&mut self, value: &str) -> Result<(), IoError<mdl::WriteError>> {
        if value.contains(['"', '\0']) {
            return Err(mdl::WriteError::InvalidString.into());
        }
        self.raw("\"")?;
        self.raw(value)?;
        self.raw("\"")
    }
    /// Writes one tab for each currently open block.
    pub fn indent(&mut self) -> Result<(), IoError<mdl::WriteError>> {
        for _ in 0..self.depth {
            self.raw("\t")?;
        }
        Ok(())
    }
    /// Begins a block without parameters.
    pub fn begin_block(&mut self, name: &str) -> Result<(), IoError<mdl::WriteError>> {
        self.indent()?;
        self.identifier(name)?;
        self.open_body()
    }
    /// Writes an indented block header with a quoted name and opens its body.
    pub fn begin_named_block(
        &mut self,
        name: &str,
        value: &str,
    ) -> Result<(), IoError<mdl::WriteError>> {
        self.indent()?;
        self.identifier(name)?;
        self.raw(" ")?;
        self.quoted(value)?;
        self.open_body()
    }
    /// Writes a count-prefixed block header and opens its body.
    /// Rejects counts above `u32::MAX` before output.
    pub fn begin_counted_block(
        &mut self,
        name: &str,
        count: usize,
    ) -> Result<(), IoError<mdl::WriteError>> {
        if count > u32::MAX as usize {
            return Err(mdl::WriteError::SizeOverflow {
                field: "list count above u32::MAX",
            }
            .into());
        }
        self.indent()?;
        self.identifier(name)?;
        write!(self.output, " {count}")?;
        self.open_body()
    }
    /// Opens a body after a header written with the lower-level methods.
    pub fn open_body(&mut self) -> Result<(), IoError<mdl::WriteError>> {
        let depth = self
            .depth
            .checked_add(1)
            .ok_or(mdl::WriteError::UnbalancedBlocks)?;
        self.raw(" {\n")?;
        self.depth = depth;
        Ok(())
    }
    /// Closes the current block and writes its indented closing brace.
    /// Returns an error if no block is open.
    pub fn end_block(&mut self) -> Result<(), IoError<mdl::WriteError>> {
        self.depth = self
            .depth
            .checked_sub(1)
            .ok_or(mdl::WriteError::UnbalancedBlocks)?;
        self.indent()?;
        self.raw("}\n")
    }
    /// Writes an indented named value followed by a comma and newline.
    pub fn property<T: Write + ?Sized>(
        &mut self,
        name: &str,
        value: &T,
    ) -> Result<(), IoError<mdl::WriteError>> {
        self.indent()?;
        self.identifier(name)?;
        self.raw(" ")?;
        self.write(value)?;
        self.raw(",\n")
    }
    /// Writes the fixed form of an animatable property.
    pub fn static_property<T: Write + ?Sized>(
        &mut self,
        name: &str,
        value: &T,
    ) -> Result<(), IoError<mdl::WriteError>> {
        self.indent()?;
        self.raw("static ")?;
        self.identifier(name)?;
        self.raw(" ")?;
        self.write(value)?;
        self.raw(",\n")
    }
    /// Writes an indented flag name followed by a comma and newline.
    pub fn flag(&mut self, name: &str) -> Result<(), IoError<mdl::WriteError>> {
        self.indent()?;
        self.identifier(name)?;
        self.raw(",\n")
    }
    /// Writes an anonymous value and its entry separator.
    pub fn entry<T: Write + ?Sized>(&mut self, value: &T) -> Result<(), IoError<mdl::WriteError>> {
        self.indent()?;
        self.write(value)?;
        self.raw(",\n")
    }
    /// Writes a count-prefixed list of records. Each record owns its indentation
    /// and separator, just as it does in the corresponding parser list.
    pub fn counted<'a, T: Write + 'a>(
        &mut self,
        name: &str,
        items: impl ExactSizeIterator<Item = &'a T>,
    ) -> Result<(), IoError<mdl::WriteError>> {
        self.begin_counted_block(name, items.len())?;
        for item in items {
            self.write(item)?;
        }
        self.end_block()
    }
    pub(crate) fn formatted(
        &mut self,
        args: Arguments<'_>,
    ) -> Result<(), IoError<mdl::WriteError>> {
        self.output.write_fmt(args)?;
        Ok(())
    }
}

macro_rules! integers {
    ($($ty:ty),*) => { $(impl Write for $ty {
        fn write_mdl<W: IoWrite>(&self, writer: &mut Writer<W>) -> Result<(), IoError<mdl::WriteError>> {
            writer.formatted(format_args!("{self}"))
        }
    })* };
}
integers!(u8, u16, u32, i32);
impl Write for f32 {
    fn write_mdl<W: IoWrite>(
        &self,
        writer: &mut Writer<W>,
    ) -> Result<(), IoError<mdl::WriteError>> {
        if self.is_nan() {
            writer.raw("nan")
        } else if *self == f32::INFINITY {
            writer.raw("inf")
        } else if *self == f32::NEG_INFINITY {
            writer.raw("-inf")
        } else {
            // f32 Debug provides shortest-roundtrip digits. Use bounded stack
            // storage so integral exponent forms can retain a decimal point.
            let mut bytes = [0u8; 48];
            let mut buffer = IoCursor::new(&mut bytes[..]);
            write!(buffer, "{self:?}")?;
            let length = buffer.position() as usize;
            let text = from_utf8(&bytes[..length]).expect("f32 formatting is ASCII");
            if self.fract() == 0.0 && !text.contains('.') {
                let (mantissa, exponent) = text
                    .split_once('e')
                    .expect("integral f32 formatting has a decimal point or exponent");
                writer.raw(mantissa)?;
                writer.raw(".0e")?;
                writer.raw(exponent)
            } else {
                writer.raw(text)
            }
        }
    }
}
impl Write for str {
    fn write_mdl<W: IoWrite>(
        &self,
        writer: &mut Writer<W>,
    ) -> Result<(), IoError<mdl::WriteError>> {
        writer.quoted(self)
    }
}
impl<T: Write, const N: usize> Write for [T; N] {
    fn write_mdl<W: IoWrite>(
        &self,
        writer: &mut Writer<W>,
    ) -> Result<(), IoError<mdl::WriteError>> {
        writer.raw("{ ")?;
        for (i, value) in self.iter().enumerate() {
            if i != 0 {
                writer.raw(", ")?;
            }
            writer.write(value)?;
        }
        writer.raw(" }")
    }
}

/// Checks that fixed text has a faithful text representation, including padding.
/// Do not use the existing lossy text() accessor for MDL conversion.
fn fixed_text<const N: usize>(text: &FixedText<N>) -> Result<&str, mdl::WriteError> {
    let bytes = text.as_bytes();
    let end = bytes
        .iter()
        .position(|&b| b == 0)
        .ok_or(mdl::WriteError::Unrepresentable {
            field: "unterminated fixed text",
        })?;
    if bytes[end..].iter().any(|&b| b != 0) {
        return Err(mdl::WriteError::Unrepresentable {
            field: "nonzero fixed-text padding",
        });
    }
    from_utf8(&bytes[..end]).map_err(|_| mdl::WriteError::Unrepresentable {
        field: "non-UTF-8 fixed text",
    })
}
impl<const N: usize> Write for FixedText<N> {
    fn write_mdl<W: IoWrite>(
        &self,
        writer: &mut Writer<W>,
    ) -> Result<(), IoError<mdl::WriteError>> {
        writer.quoted(fixed_text(self)?)
    }
}

/// Checks whether fixed text can be emitted without losing its bytes.
pub(crate) fn validate_fixed_text<const N: usize>(
    text: &FixedText<N>,
) -> Result<(), mdl::WriteError> {
    let value = fixed_text(text)?;
    if value.contains(['"', '\0']) {
        return Err(mdl::WriteError::InvalidString);
    }
    Ok(())
}