Trait Write
pub trait Write {
// Required method
fn write_str(&mut self, string: &str) -> Result<(), Error> ⓘ;
// Provided method
fn write_char(&mut self, char: char) -> Result<(), Error> ⓘ { ... }
}
dep_jiff
and alloc
only.Expand description
A trait for printing datetimes or spans into Unicode-accepting buffers or streams.
The most useful implementations of this trait are for the String
and
Vec<u8>
types. But any implementation of std::fmt::Write
and
std::io::Write
can be used via the StdFmtWrite
and StdIoWrite
adapters, respectively.
Most users of Jiff should not need to interact with this trait directly.
Instead, printing is handled via the Display
implementation of the relevant type.
§Design
This trait is a near-clone of the std::fmt::Write
trait. It’s also very
similar to the std::io::Write
trait, but like std::fmt::Write
, this
trait is limited to writing valid UTF-8. The UTF-8 restriction was adopted
because we really want to support printing datetimes and spans to String
buffers. If we permitted writing &[u8]
data, then writing to a String
buffer would always require a costly UTF-8 validation check.
The std::fmt::Write
trait wasn’t used itself because:
- Using a custom trait allows us to require using Jiff’s error type. (Although this extra flexibility isn’t currently used, since printing only fails when writing to the underlying buffer or stream fails.)
- Using a custom trait allows us more control over the implementations of
the trait. For example, a custom trait means we can format directly into
a
Vec<u8>
buffer, which isn’t possible withstd::fmt::Write
because there is nostd::fmt::Write
trait implementation forVec<u8>
.