printf-compat 0.3.1

printf reimplemented in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Various ways to output formatting data.

use core::cell::Cell;
use core::ffi::*;
use core::fmt;
use core::str::from_utf8;

#[cfg(feature = "std")]
pub use yes_std::*;

use crate::{Argument, DoubleFormat, Flags, Specifier};

struct DummyWriter(usize);

impl fmt::Write for DummyWriter {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.0 += s.len();
        Ok(())
    }
}

struct WriteCounter<'a, T: fmt::Write>(&'a mut T, usize);

impl<'a, T: fmt::Write> fmt::Write for WriteCounter<'a, T> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.1 += s.len();
        self.0.write_str(s)
    }
}

fn write_str(
    w: &mut impl fmt::Write,
    flags: Flags,
    width: c_int,
    precision: Option<c_int>,
    b: &[u8],
) -> fmt::Result {
    let string = from_utf8(b).map_err(|_| fmt::Error)?;
    let precision = precision.unwrap_or(string.len() as c_int);
    if flags.contains(Flags::LEFT_ALIGN) {
        write!(
            w,
            "{:1$.prec$}",
            string,
            width as usize,
            prec = precision as usize
        )
    } else {
        write!(
            w,
            "{:>1$.prec$}",
            string,
            width as usize,
            prec = precision as usize
        )
    }
}

macro_rules! define_numeric {
    ($w: expr, $data: expr, $flags: expr, $width: expr, $precision: expr) => {
        define_numeric!($w, $data, $flags, $width, $precision, "")
    };
    ($w: expr, $data: expr, $flags: expr, $width: expr, $precision: expr, $ty:expr) => {{
        use fmt::Write;
        if $flags.contains(Flags::LEFT_ALIGN) {
            if $flags.contains(Flags::PREPEND_PLUS) {
                write!(
                    $w,
                    concat!("{:<+width$.prec$", $ty, "}"),
                    $data,
                    width = $width as usize,
                    prec = $precision as usize
                )
            } else if $flags.contains(Flags::PREPEND_SPACE) && !$data.is_sign_negative() {
                write!(
                    $w,
                    concat!(" {:<width$.prec$", $ty, "}"),
                    $data,
                    width = ($width as usize).wrapping_sub(1),
                    prec = $precision as usize
                )
            } else {
                write!(
                    $w,
                    concat!("{:<width$.prec$", $ty, "}"),
                    $data,
                    width = $width as usize,
                    prec = $precision as usize
                )
            }
        } else if $flags.contains(Flags::PREPEND_PLUS) {
            if $flags.contains(Flags::PREPEND_ZERO) {
                write!(
                    $w,
                    concat!("{:+0width$.prec$", $ty, "}"),
                    $data,
                    width = $width as usize,
                    prec = $precision as usize
                )
            } else {
                write!(
                    $w,
                    concat!("{:+width$.prec$", $ty, "}"),
                    $data,
                    width = $width as usize,
                    prec = $precision as usize
                )
            }
        } else if $flags.contains(Flags::PREPEND_ZERO) {
            if $flags.contains(Flags::PREPEND_SPACE) && !$data.is_sign_negative() {
                let mut d = DummyWriter(0);
                let _ = write!(
                    d,
                    concat!("{:.prec$", $ty, "}"),
                    $data,
                    prec = $precision as usize
                );
                if d.0 + 1 > $width as usize {
                    $width += 1;
                }
                write!(
                    $w,
                    concat!(" {:0width$.prec$", $ty, "}"),
                    $data,
                    width = ($width as usize).wrapping_sub(1),
                    prec = $precision as usize
                )
            } else {
                write!(
                    $w,
                    concat!("{:0width$.prec$", $ty, "}"),
                    $data,
                    width = $width as usize,
                    prec = $precision as usize
                )
            }
        } else {
            if $flags.contains(Flags::PREPEND_SPACE) && !$data.is_sign_negative() {
                let mut d = DummyWriter(0);
                let _ = write!(
                    d,
                    concat!("{:.prec$", $ty, "}"),
                    $data,
                    prec = $precision as usize
                );
                if d.0 + 1 > $width as usize {
                    $width = d.0 as i32 + 1;
                }
            }
            write!(
                $w,
                concat!("{:width$.prec$", $ty, "}"),
                $data,
                width = $width as usize,
                prec = $precision as usize
            )
        }
    }};
}

macro_rules! define_unumeric {
    ($w: expr, $data: expr, $flags: expr, $width: expr, $precision: expr) => {
        define_unumeric!($w, $data, $flags, $width, $precision, "")
    };
    ($w: expr, $data: expr, $flags: expr, $width: expr, $precision: expr, $ty:expr) => {{
        if $flags.contains(Flags::LEFT_ALIGN) {
            if $flags.contains(Flags::ALTERNATE_FORM) {
                write!(
                    $w,
                    concat!("{:<#width$", $ty, "}"),
                    $data,
                    width = $width as usize
                )
            } else {
                write!(
                    $w,
                    concat!("{:<width$", $ty, "}"),
                    $data,
                    width = $width as usize
                )
            }
        } else if $flags.contains(Flags::ALTERNATE_FORM) {
            if $flags.contains(Flags::PREPEND_ZERO) {
                write!(
                    $w,
                    concat!("{:#0width$", $ty, "}"),
                    $data,
                    width = $width as usize
                )
            } else {
                write!(
                    $w,
                    concat!("{:#width$", $ty, "}"),
                    $data,
                    width = $width as usize
                )
            }
        } else if $flags.contains(Flags::PREPEND_ZERO) {
            write!(
                $w,
                concat!("{:0width$", $ty, "}"),
                $data,
                width = $width as usize
            )
        } else {
            write!(
                $w,
                concat!("{:width$", $ty, "}"),
                $data,
                width = $width as usize
            )
        }
    }};
}

/// Write to a struct that implements [`fmt::Write`].
///
/// # Differences
///
/// There are a few differences from standard printf format:
///
/// - only valid UTF-8 data can be printed.
/// - an `X` format specifier with a `#` flag prints the hex data in uppercase,
///   but the leading `0x` is still lowercase.
/// - an `o` format specifier with a `#` flag precedes the number with an `o`
///   instead of `0`.
/// - `g`/`G` (shorted floating point) is aliased to `f`/`F`` (decimal floating
///   point).
/// - same for `a`/`A` (hex floating point).
/// - the `n` format specifier, [`Specifier::WriteBytesWritten`], is not
///   implemented and will cause an error if encountered.
/// - precision is ignored for integral types, instead of specifying the
///   minimum number of digits.
pub fn fmt_write(w: &mut impl fmt::Write) -> impl FnMut(Argument) -> c_int + '_ {
    use fmt::Write;
    move |Argument {
              flags,
              mut width,
              precision,
              specifier,
          }| {
        let mut w = WriteCounter(w, 0);
        let w = &mut w;
        let res = match specifier {
            Specifier::Percent => w.write_char('%'),
            Specifier::Bytes(data) => write_str(w, flags, width, precision, data),
            Specifier::String(data) => write_str(w, flags, width, precision, data.to_bytes()),
            Specifier::Hex(data) => {
                define_unumeric!(w, data, flags, width, precision.unwrap_or(0), "x")
            }
            Specifier::UpperHex(data) => {
                define_unumeric!(w, data, flags, width, precision.unwrap_or(0), "X")
            }
            Specifier::Octal(data) => {
                define_unumeric!(w, data, flags, width, precision.unwrap_or(0), "o")
            }
            Specifier::Uint(data) => {
                define_unumeric!(w, data, flags, width, precision.unwrap_or(0))
            }
            Specifier::Int(data) => define_numeric!(w, data, flags, width, precision.unwrap_or(0)),
            Specifier::Double { value, format } => match format {
                DoubleFormat::Normal
                | DoubleFormat::UpperNormal
                | DoubleFormat::Auto
                | DoubleFormat::UpperAuto
                | DoubleFormat::Hex
                | DoubleFormat::UpperHex => {
                    define_numeric!(w, value, flags, width, precision.unwrap_or(6))
                }
                DoubleFormat::Scientific => {
                    define_numeric!(w, value, flags, width, precision.unwrap_or(6), "e")
                }
                DoubleFormat::UpperScientific => {
                    define_numeric!(w, value, flags, width, precision.unwrap_or(6), "E")
                }
            },
            Specifier::Char(data) => {
                if flags.contains(Flags::LEFT_ALIGN) {
                    write!(w, "{:width$}", data as u8 as char, width = width as usize)
                } else {
                    write!(w, "{:>width$}", data as u8 as char, width = width as usize)
                }
            }
            Specifier::Pointer(data) => {
                if flags.contains(Flags::LEFT_ALIGN) {
                    write!(w, "{:<width$p}", data, width = width as usize)
                } else if flags.contains(Flags::PREPEND_ZERO) {
                    write!(w, "{:0width$p}", data, width = width as usize)
                } else {
                    write!(w, "{:width$p}", data, width = width as usize)
                }
            }
            Specifier::WriteBytesWritten(_, _) => Err(Default::default()),
        };
        match res {
            Ok(_) => w.1 as c_int,
            Err(_) => -1,
        }
    }
}

/// Returns an object that implements [`Display`][fmt::Display] for safely
/// printing formatting data. This is slightly less performant than using
/// [`fmt_write`], but may be the only option.
///
/// This shares the same caveats as [`fmt_write`].
///
/// # Safety
///
/// [`VaList`]s are *very* unsafe. The passed `format` and `args` parameter must be a valid [`printf` format string](http://www.cplusplus.com/reference/cstdio/printf/).
pub unsafe fn display<'a>(format: *const c_char, va_list: VaList<'a>) -> VaListDisplay<'a> {
    VaListDisplay {
        format,
        va_list,
        written: Cell::new(0),
    }
}

/// Helper struct created by [`display`] for safely printing `printf`-style
/// formatting with [`format!`] and `{}`. This can be used with anything that
/// uses [`format_args!`], such as [`println!`] or the `log` crate.
///
/// ```rust
/// #![feature(c_variadic)]
///
/// use core::ffi::{c_char, c_int};
///
/// #[unsafe(no_mangle)]
/// unsafe extern "C" fn c_library_print(str: *const c_char, args: ...) -> c_int {
///     let format = unsafe { printf_compat::output::display(str, args) };
///     println!("{}", format);
///     format.bytes_written()
/// }
/// ```
pub struct VaListDisplay<'a> {
    format: *const c_char,
    va_list: VaList<'a>,
    written: Cell<c_int>,
}

impl VaListDisplay<'_> {
    /// Get the number of bytes written, or 0 if there was an error.
    pub fn bytes_written(&self) -> c_int {
        self.written.get()
    }
}

impl<'a> fmt::Display for VaListDisplay<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        unsafe {
            let bytes = crate::format(self.format, self.va_list.clone(), fmt_write(f));
            self.written.set(bytes);
            if bytes < 0 { Err(fmt::Error) } else { Ok(()) }
        }
    }
}

#[cfg(feature = "std")]
mod yes_std {
    use std::io;

    use super::*;

    struct FmtWriter<T: io::Write>(T, io::Result<()>);

    impl<T: io::Write> fmt::Write for FmtWriter<T> {
        fn write_str(&mut self, s: &str) -> fmt::Result {
            match self.0.write_all(s.as_bytes()) {
                Ok(()) => Ok(()),
                Err(e) => {
                    self.1 = Err(e);
                    Err(fmt::Error)
                }
            }
        }
    }

    struct IoWriteCounter<'a, T: io::Write>(&'a mut T, usize);

    impl<'a, T: io::Write> io::Write for IoWriteCounter<'a, T> {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.0.write_all(buf)?;
            self.1 += buf.len();
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            self.0.flush()
        }
    }

    fn write_bytes(
        w: &mut impl io::Write,
        flags: Flags,
        width: c_int,
        precision: Option<c_int>,
        b: &[u8],
    ) -> io::Result<()> {
        let precision = precision.unwrap_or(b.len() as c_int);
        let b = b.get(..(b.len().min(precision as usize))).unwrap_or(&[]);

        if flags.contains(Flags::LEFT_ALIGN) {
            w.write_all(b)?;
            for _ in 0..((width as usize).saturating_sub(b.len())) {
                w.write_all(b" ")?;
            }
            Ok(())
        } else {
            for _ in 0..((width as usize).saturating_sub(b.len())) {
                w.write_all(b" ")?;
            }
            w.write_all(b)
        }
    }

    /// Write to a struct that implements [`io::Write`].
    ///
    /// This shares the same caveats as [`fmt_write`], except that non-UTF-8
    /// data is supported.
    pub fn io_write(w: &mut impl io::Write) -> impl FnMut(Argument) -> c_int + '_ {
        use io::Write;
        move |Argument {
                  flags,
                  width,
                  precision,
                  specifier,
              }| {
            let mut w = IoWriteCounter(w, 0);
            let mut w = &mut w;
            let res = match specifier {
                Specifier::Percent => w.write_all(b"%"),
                Specifier::Bytes(data) => write_bytes(w, flags, width, precision, data),
                Specifier::String(data) => write_bytes(w, flags, width, precision, data.to_bytes()),
                _ => {
                    let mut writer = FmtWriter(&mut w, Ok(()));
                    fmt_write(&mut writer)(Argument {
                        flags,
                        width,
                        precision,
                        specifier,
                    });
                    writer.1
                }
            };
            match res {
                Ok(_) => w.1 as c_int,
                Err(_) => -1,
            }
        }
    }
}