You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I was curious so I did some playing around with this, and got a proof-of-concept working:
use serde::Serialize;use std::{fmt, io};structFormatterAdapter<'a,'b>(&'a mut fmt::Formatter<'b>);impl io::WriteforFormatterAdapter<'_,'_>{fnwrite(&mutself,buf:&[u8]) -> io::Result<usize>{let s = unsafe{// serde_json does not emit invalid UTF-8
std::str::from_utf8_unchecked(buf)};// Or if you can't guarantee that FormatterAdapter is only used with serde_json output:// let s = std::str::from_utf8(buf).map_err(io::Error::other)?;matchself.0.write_str(s){Ok(_) => Ok(s.len()),Err(_) => Err(io::ErrorKind::Other.into()),}}fnflush(&mutself) -> io::Result<()>{Ok(())}}pubfnto_formatter<T>(value:&T,f:&mut fmt::Formatter<'_>) -> serde_json::Result<()>whereT: ?Sized + serde::Serialize,{let adapter = FormatterAdapter(f);
serde_json::to_writer(adapter, value)}
Note that if the inner value's Serialize impl returns an error then, this outputs the error as text. This is because rust considers string formatting to be infallible except for when the underlying stream fails (see https://doc.rust-lang.org/std/fmt/struct.Error.html) - so returning a std::fmt::Error from the Debug/Display impl actually causes a runtime panic with the message a formatting trait implementation returned an error when the underlying stream did not
Is it possible to serialize a value directly to fmt::Formatter?
Usecase:
This doesn't work because
to_writer
requiresstd::io::Write
, which we can't get fromstd::fmt::Formatter
The text was updated successfully, but these errors were encountered: