Trait Write

pub trait Write

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:

  1. Using a custom trait allows us to require using Jiff's error type. (Although this extra flexibility isn't currently used much, since printing rarely fails for any reason other than the underlying jiff::fmt::Write implementation failing.)
  2. 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 with std::fmt::Write because there is no std::fmt::Write trait implementation for Vec<u8>.

Required Methods

fn write_str(&mut self, string: &str) -> Result<(), Error>

Write the given string to this writer, returning whether the write succeeded or not.

Provided Methods

fn write_char(&mut self, char: char) -> Result<(), Error>

Write the given character to this writer, returning whether the write succeeded or not.

unsafe fn as_mut_vec(&mut self) -> Option<&mut Vec<u8>>

Returns a Vec<u8> backing store for this implementation.

Consumers of this trait may call this method to get a view directly into a buffer for more optimized writing.

The default implementation always returns None.

This method is only available when Jiff's alloc feature is enabled.

Safety

Callers must ensure that only valid UTF-8 is written to the buffer returned.

Implementors