zesterer / ariadne

A fancy diagnostics & error reporting crate
https://crates.io/crates/ariadne
MIT License
1.61k stars 72 forks source link

Don't consume writer when writing a report #63

Closed ctron closed 1 year ago

ctron commented 1 year ago

Using Report::write one has to pass in a writer. However, the writer is passed in as mut w: W, consuming the instance in the process.

However, it would be sufficient to just require w: &mut W, as that is all that is needed, not consuming the writer.

Consuming the writer is especially a problem I one wants to write out to a String, which you can never get back, as its being consumed in the process.

zesterer commented 1 year ago

&mut impl Write itself implements Write, so you can just pass a mutable reference like .write(&mut my_string).

ctron commented 1 year ago

Indeed it does! I guess what I was missing was the fact that my_string must be mutable as well.

So I ended up with something like:

fn write_to<W:std::io::Write>(&self, mut w: &mut W) {
  for i in &self.stuff {
    let report = Report::new().finish();
    report.write(&self.cache, &mut w);
  }
}

fn write_to_stdout(&self) {
  self.write_to(&mut std::io::stdout().lock())
}

Thanks for teaching me a new Rust trick! :wink:

zesterer commented 1 year ago

No problem, glad you got it working :)