luau-printf 0.732.0

Luau musl snprintf-compatible narrow byte formatting
Documentation
/** Musl snprintf-compatible byte formatting for Luau, forked from `fish-printf`. */
pub use bstr::{BStr, BString};

mod arg;
pub use arg::{Arg, ToArg};

mod fmt_fp;
mod printf_impl;
pub use printf_impl::{Error, printf_locale_to_slice, sprintf_locale};
pub mod locale;

#[cfg(test)]
mod tests;

/// A macro to format a byte string with C-locale formatting rules.
///
/// # Examples
///
/// ```
/// use luau_printf::sprintf;
///
/// // Create a `BString` from a format string.
/// let s = sprintf!("%0.5g", 123456.0);
/// assert_eq!(s, "1.2346e+05");
///
/// // Write to an existing byte sink.
/// let mut s = Vec::new();
/// sprintf!(=> &mut s, "%0.5g", 123456.0);
/// assert_eq!(s.as_slice(), b"1.2346e+05");
/// ```
#[macro_export]
macro_rules! sprintf {
    // Write to a newly allocated BString, and return it.
    // This panics if the format string or arguments are invalid.
    (
        $fmt:expr // Format string, as bytes.
        $(, $($arg:expr),*)? // arguments
    ) => {
        {
            let mut target = ::std::vec::Vec::new();
            $crate::sprintf!(=> &mut target, $fmt $(, $($arg),*)?);
            $crate::BString::from(target)
        }
    };

    // Variant which writes to a target.
    // The target should implement std::io::Write.
    (
        => $target:expr, // target string
        $fmt:expr // format string
        $(, $($arg:expr),*)? // arguments
    ) => {
        {
            // May be no args!
            #[allow(unused_imports)]
            use $crate::ToArg as _;
            let fmt = $crate::BStr::new(::std::convert::AsRef::<[u8]>::as_ref(&$fmt));
            $crate::printf_c_locale(
                $target,
                fmt,
                &mut [$( $($arg.to_arg()),* )?],
            ).unwrap()
        }
    };
}

/// Formats a byte string using the provided format specifiers and arguments, using the C locale.
///
/// # Parameters
/// - `f`: The receiver of formatted output.
/// - `fmt`: The format string being parsed.
/// - `args`: Iterator over the arguments to format.
///
/// # Returns
/// A `Result` which is `Ok` containing the number of bytes written on success, or an `Error`.
///
/// # Example
///
/// ```
/// use luau_printf::{printf_c_locale, ToArg};
///
/// let mut output = Vec::new();
/// let fmt = luau_printf::BStr::new("%0.5g");
/// let mut args = [123456.0_f64.to_arg()];
///
/// let result = printf_c_locale(&mut output, fmt, &mut args);
///
/// assert_eq!(result, Ok(10));
/// assert_eq!(output.as_slice(), b"1.2346e+05");
/// ```
pub fn printf_c_locale<W: std::io::Write + ?Sized>(
    f: &mut W,
    fmt: &BStr,
    args: &mut [Arg],
) -> Result<usize, Error> {
    sprintf_locale(f, fmt, &locale::C_LOCALE, args)
}

/// Formats a byte string into a fixed-size byte slice using C-locale formatting rules.
///
/// The returned count is the number of bytes that would have been written
/// without truncation. Bytes that do not fit in `buffer` are discarded.
pub fn printf_c_locale_to_slice(
    buffer: &mut [u8],
    fmt: &BStr,
    args: &mut [Arg],
) -> Result<usize, Error> {
    printf_locale_to_slice(buffer, fmt, &locale::C_LOCALE, args)
}