Struct frame_support::dispatch::fmt::Formatter 1.0.0[−][src]
pub struct Formatter<'a> { /* fields omitted */ }
Expand description
Configuration for formatting.
A Formatter
represents various options related to formatting. Users do not
construct Formatter
s directly; a mutable reference to one is passed to
the fmt
method of all formatting traits, like Debug
and Display
.
To interact with a Formatter
, you’ll call various methods to change the
various options related to formatting. For examples, please see the
documentation of the methods defined on Formatter
below.
Implementations
Performs the correct padding for an integer which has already been emitted into a str. The str should not contain the sign for the integer, that will be added by this method.
Arguments
- is_nonnegative - whether the original integer was either positive or zero.
- prefix - if the ‘#’ character (Alternate) is provided, this is the prefix to put in front of the number.
- buf - the byte array that the number has been formatted into
This function will correctly account for the flags provided as well as the minimum width. It will not take precision into account.
Examples
use std::fmt; struct Foo { nb: i32 } impl Foo { fn new(nb: i32) -> Foo { Foo { nb, } } } impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { // We need to remove "-" from the number output. let tmp = self.nb.abs().to_string(); formatter.pad_integral(self.nb >= 0, "Foo ", &tmp) } } assert_eq!(&format!("{}", Foo::new(2)), "2"); assert_eq!(&format!("{}", Foo::new(-1)), "-1"); assert_eq!(&format!("{}", Foo::new(0)), "0"); assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1"); assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
This function takes a string slice and emits it to the internal buffer after applying the relevant formatting flags specified. The flags recognized for generic strings are:
- width - the minimum width of what to emit
- fill/align - what to emit and where to emit it if the string provided needs to be padded
- precision - the maximum length to emit, the string is truncated if it is longer than this length
Notably this function ignores the flag
parameters.
Examples
use std::fmt; struct Foo; impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.pad("Foo") } } assert_eq!(&format!("{:<4}", Foo), "Foo "); assert_eq!(&format!("{:0>4}", Foo), "0Foo");
Writes some data to the underlying buffer contained within this formatter.
Examples
use std::fmt; struct Foo; impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("Foo") // This is equivalent to: // write!(formatter, "Foo") } } assert_eq!(&format!("{}", Foo), "Foo"); assert_eq!(&format!("{:0>8}", Foo), "Foo");
Writes some formatted information into this instance.
Examples
use std::fmt; struct Foo(i32); impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_fmt(format_args!("Foo {}", self.0)) } } assert_eq!(&format!("{}", Foo(-1)), "Foo -1"); assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
👎 Deprecated since 1.24.0: use the sign_plus
, sign_minus
, alternate
, or sign_aware_zero_pad
methods instead
use the sign_plus
, sign_minus
, alternate
, or sign_aware_zero_pad
methods instead
Flags for formatting
Character used as ‘fill’ whenever there is alignment.
Examples
use std::fmt; struct Foo; impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let c = formatter.fill(); if let Some(width) = formatter.width() { for _ in 0..width { write!(formatter, "{}", c)?; } Ok(()) } else { write!(formatter, "{}", c) } } } // We set alignment to the right with ">". assert_eq!(&format!("{:G>3}", Foo), "GGG"); assert_eq!(&format!("{:t>6}", Foo), "tttttt");
Flag indicating what form of alignment was requested.
Examples
extern crate core; use std::fmt::{self, Alignment}; struct Foo; impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let s = if let Some(s) = formatter.align() { match s { Alignment::Left => "left", Alignment::Right => "right", Alignment::Center => "center", } } else { "into the void" }; write!(formatter, "{}", s) } } assert_eq!(&format!("{:<}", Foo), "left"); assert_eq!(&format!("{:>}", Foo), "right"); assert_eq!(&format!("{:^}", Foo), "center"); assert_eq!(&format!("{}", Foo), "into the void");
Optionally specified integer width that the output should be.
Examples
use std::fmt; struct Foo(i32); impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if let Some(width) = formatter.width() { // If we received a width, we use it write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width) } else { // Otherwise we do nothing special write!(formatter, "Foo({})", self.0) } } } assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) "); assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
Optionally specified precision for numeric types. Alternatively, the maximum width for string types.
Examples
use std::fmt; struct Foo(f32); impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if let Some(precision) = formatter.precision() { // If we received a precision, we use it. write!(formatter, "Foo({1:.*})", precision, self.0) } else { // Otherwise we default to 2. write!(formatter, "Foo({:.2})", self.0) } } } assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)"); assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
Determines if the +
flag was specified.
Examples
use std::fmt; struct Foo(i32); impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if formatter.sign_plus() { write!(formatter, "Foo({}{})", if self.0 < 0 { '-' } else { '+' }, self.0) } else { write!(formatter, "Foo({})", self.0) } } } assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)"); assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
Determines if the -
flag was specified.
Examples
use std::fmt; struct Foo(i32); impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if formatter.sign_minus() { // You want a minus sign? Have one! write!(formatter, "-Foo({})", self.0) } else { write!(formatter, "Foo({})", self.0) } } } assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)"); assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
Determines if the #
flag was specified.
Examples
use std::fmt; struct Foo(i32); impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if formatter.alternate() { write!(formatter, "Foo({})", self.0) } else { write!(formatter, "{}", self.0) } } } assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)"); assert_eq!(&format!("{}", Foo(23)), "23");
Determines if the 0
flag was specified.
Examples
use std::fmt; struct Foo(i32); impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { assert!(formatter.sign_aware_zero_pad()); assert_eq!(formatter.width(), Some(4)); // We ignore the formatter's options. write!(formatter, "{}", self.0) } } assert_eq!(&format!("{:04}", Foo(23)), "23");
Creates a DebugStruct
builder designed to assist with creation of
fmt::Debug
implementations for structs.
Examples
use std::fmt; use std::net::Ipv4Addr; struct Foo { bar: i32, baz: String, addr: Ipv4Addr, } impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Foo") .field("bar", &self.bar) .field("baz", &self.baz) .field("addr", &format_args!("{}", self.addr)) .finish() } } assert_eq!( "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }", format!("{:?}", Foo { bar: 10, baz: "Hello World".to_string(), addr: Ipv4Addr::new(127, 0, 0, 1), }) );
Creates a DebugTuple
builder designed to assist with creation of
fmt::Debug
implementations for tuple structs.
Examples
use std::fmt; use std::marker::PhantomData; struct Foo<T>(i32, String, PhantomData<T>); impl<T> fmt::Debug for Foo<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_tuple("Foo") .field(&self.0) .field(&self.1) .field(&format_args!("_")) .finish() } } assert_eq!( "Foo(10, \"Hello\", _)", format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>)) );
Creates a DebugList
builder designed to assist with creation of
fmt::Debug
implementations for list-like structures.
Examples
use std::fmt; struct Foo(Vec<i32>); impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_list().entries(self.0.iter()).finish() } } assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
Creates a DebugSet
builder designed to assist with creation of
fmt::Debug
implementations for set-like structures.
Examples
use std::fmt; struct Foo(Vec<i32>); impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_set().entries(self.0.iter()).finish() } } assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
In this more complex example, we use format_args!
and .debug_set()
to build a list of match arms:
use std::fmt; struct Arm<'a, L: 'a, R: 'a>(&'a (L, R)); struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V); impl<'a, L, R> fmt::Debug for Arm<'a, L, R> where L: 'a + fmt::Debug, R: 'a + fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { L::fmt(&(self.0).0, fmt)?; fmt.write_str(" => ")?; R::fmt(&(self.0).1, fmt) } } impl<'a, K, V> fmt::Debug for Table<'a, K, V> where K: 'a + fmt::Debug, V: 'a + fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_set() .entries(self.0.iter().map(Arm)) .entry(&Arm(&(format_args!("_"), &self.1))) .finish() } }
Creates a DebugMap
builder designed to assist with creation of
fmt::Debug
implementations for map-like structures.
Examples
use std::fmt; struct Foo(Vec<(String, i32)>); impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish() } } assert_eq!( format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])), r#"{"A": 10, "B": 11}"# );
Trait Implementations
use serde::Serialize; use std::fmt::{self, Display}; #[derive(Serialize)] #[serde(rename_all = "kebab-case")] pub enum MessageType { StartRequest, EndRequest, } impl Display for MessageType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.serialize(f) } }
The output type produced by this Serializer
during successful
serialization. Most serializers that produce text or binary output
should set Ok = ()
and serialize into an io::Write
or buffer
contained within the Serializer
instance. Serializers that build
in-memory data structures may be simplified by using Ok
to propagate
the data structure around. Read more
type SerializeSeq = Impossible<(), Error>
type SerializeSeq = Impossible<(), Error>
Type returned from serialize_seq
for serializing the content of the
sequence. Read more
type SerializeTuple = Impossible<(), Error>
type SerializeTuple = Impossible<(), Error>
Type returned from serialize_tuple
for serializing the content of
the tuple. Read more
type SerializeTupleStruct = Impossible<(), Error>
type SerializeTupleStruct = Impossible<(), Error>
Type returned from serialize_tuple_struct
for serializing the
content of the tuple struct. Read more
type SerializeTupleVariant = Impossible<(), Error>
type SerializeTupleVariant = Impossible<(), Error>
Type returned from serialize_tuple_variant
for serializing the
content of the tuple variant. Read more
type SerializeMap = Impossible<(), Error>
type SerializeMap = Impossible<(), Error>
Type returned from serialize_map
for serializing the content of the
map. Read more
type SerializeStruct = Impossible<(), Error>
type SerializeStruct = Impossible<(), Error>
Type returned from serialize_struct
for serializing the content of
the struct. Read more
type SerializeStructVariant = Impossible<(), Error>
type SerializeStructVariant = Impossible<(), Error>
Type returned from serialize_struct_variant
for serializing the
content of the struct variant. Read more
Serialize a unit struct like struct Unit
or PhantomData<T>
. Read more
Serialize a unit variant like E::A
in enum E { A, B }
. Read more
Serialize a newtype struct like struct Millimeters(u8)
. Read more
Serialize a chunk of raw byte data. Read more
Serialize a newtype variant like E::N
in enum E { N(u8) }
. Read more
pub fn serialize_seq(
self,
_len: Option<usize>
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeSeq, Error>
pub fn serialize_seq(
self,
_len: Option<usize>
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeSeq, Error>
Begin to serialize a variably sized sequence. This call must be
followed by zero or more calls to serialize_element
, then a call to
end
. Read more
pub fn serialize_tuple(
self,
_len: usize
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeTuple, Error>
pub fn serialize_tuple(
self,
_len: usize
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeTuple, Error>
Begin to serialize a statically sized sequence whose length will be
known at deserialization time without looking at the serialized data.
This call must be followed by zero or more calls to serialize_element
,
then a call to end
. Read more
pub fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeTupleStruct, Error>
pub fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeTupleStruct, Error>
Begin to serialize a tuple struct like struct Rgb(u8, u8, u8)
. This
call must be followed by zero or more calls to serialize_field
, then a
call to end
. Read more
pub fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeTupleVariant, Error>
pub fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeTupleVariant, Error>
Begin to serialize a tuple variant like E::T
in enum E { T(u8, u8) }
. This call must be followed by zero or more calls to
serialize_field
, then a call to end
. Read more
pub fn serialize_map(
self,
_len: Option<usize>
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeMap, Error>
pub fn serialize_map(
self,
_len: Option<usize>
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeMap, Error>
Begin to serialize a map. This call must be followed by zero or more
calls to serialize_key
and serialize_value
, then a call to end
. Read more
pub fn serialize_struct(
self,
_name: &'static str,
_len: usize
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeStruct, Error>
pub fn serialize_struct(
self,
_name: &'static str,
_len: usize
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeStruct, Error>
Begin to serialize a struct like struct Rgb { r: u8, g: u8, b: u8 }
.
This call must be followed by zero or more calls to serialize_field
,
then a call to end
. Read more
pub fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeStructVariant, Error>
pub fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize
) -> Result<<&'a mut Formatter<'b> as Serializer>::SerializeStructVariant, Error>
Begin to serialize a struct variant like E::S
in enum E { S { r: u8, g: u8, b: u8 } }
. This call must be followed by zero or more calls to
serialize_field
, then a call to end
. Read more
Serialize a string produced by an implementation of Display
. Read more
fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error> where
I: IntoIterator,
<I as IntoIterator>::Item: Serialize,
fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error> where
I: IntoIterator,
<I as IntoIterator>::Item: Serialize,
Collect an iterator as a sequence. Read more
fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error> where
I: IntoIterator<Item = (K, V)>,
K: Serialize,
V: Serialize,
fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error> where
I: IntoIterator<Item = (K, V)>,
K: Serialize,
V: Serialize,
Collect an iterator as a map. Read more
Determine whether Serialize
implementations should serialize in
human-readable form. Read more
Writes a string slice into this writer, returning whether the write succeeded. Read more
Auto Trait Implementations
impl<'a> !RefUnwindSafe for Formatter<'a>
impl<'a> !UnwindSafe for Formatter<'a>
Blanket Implementations
Mutably borrows from an owned value. Read more
impl<T> Downcast for T where
T: Any,
impl<T> Downcast for T where
T: Any,
Convert Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
. Read more
pub fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
pub fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
Convert Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
. Read more
Convert &Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s. Read more
pub fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
pub fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
Convert &mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s. Read more
Instruments this type with the provided Span
, returning an
Instrumented
wrapper. Read more
type Output = T
type Output = T
Should always be Self
The counterpart to unchecked_from
.
Consume self to return an equivalent value of T
.
pub fn vzip(self) -> V