Why is the `capacity` 0 in log?

#![feature(fmt_internals)]

use core::fmt;

use log::error;

struct Logger;

impl log::Log for Logger {
    fn enabled(&self, _metadata: &log::Metadata) -> bool {
        true
    }

    fn flush(&self) {}

    fn log(&self, record: &log::Record) {
        let capacity = record.args().estimated_capacity();
        println!("capacity  {}", capacity);
    }
}

static LOGGER: Logger = Logger;

pub struct Time {
    second: u32,
    minute: u32,
    hour: u32,
    day: u32,
    month: u32,
    year: u32,
}

impl fmt::Debug for Time {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "{:x}/{:x}/{:x} {:x}:{:x}:{:x}",
            self.year, self.month, self.day, self.hour, self.minute, self.second
        ))
    }
}

impl fmt::Display for Time {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "{:x}/{:x}/{:x} {:x}:{:x}:{:x}",
            self.year, self.month, self.day, self.hour, self.minute, self.second
        ))
    }
}

fn main() {
    log::set_max_level(log::LevelFilter::Info);
    match log::set_logger(&LOGGER) {
        Ok(_) => println!("Logger initialized."),
        Err(e) => println!("Logger setup failed! error: {}", e),
    }
    let t = Time {
        second: 100,
        year: 60,
        month: 1,
        minute: 2,
        hour: 5,
        day: 9,
    };
    error!("{}", t);
}

(Playground)

Why do I get the capacity 0 in log function?

It's an estimate, it could be wrong in any direction and any amount. Especially since this is an internal implementation detail I don't think you can expect any guarantees nor documentation of behavior. You could find your way to the source code and figure out what it's doing but that's strongly discouraged, as the compiler warnings say.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.