2 use std
::cell
::RefCell
;
4 /// Format all iterator elements lazily, separated by `sep`.
6 /// The format value can only be formatted once, after that the iterator is
9 /// See [`.format_with()`](../trait.Itertools.html#method.format_with) for more information.
10 pub struct FormatWith
<'a
, I
, F
> {
12 /// FormatWith uses interior mutability because Display::fmt takes &self.
13 inner
: RefCell
<Option
<(I
, F
)>>,
16 /// Format all iterator elements lazily, separated by `sep`.
18 /// The format value can only be formatted once, after that the iterator is
21 /// See [`.format()`](../trait.Itertools.html#method.format)
22 /// for more information.
24 pub struct Format
<'a
, I
> {
26 /// Format uses interior mutability because Display::fmt takes &self.
27 inner
: RefCell
<Option
<I
>>,
30 pub fn new_format
<'a
, I
, F
>(iter
: I
, separator
: &'a
str, f
: F
) -> FormatWith
<'a
, I
, F
>
32 F
: FnMut(I
::Item
, &mut FnMut(&fmt
::Display
) -> fmt
::Result
) -> fmt
::Result
36 inner
: RefCell
::new(Some((iter
, f
))),
40 pub fn new_format_default
<'a
, I
>(iter
: I
, separator
: &'a
str) -> Format
<'a
, I
>
45 inner
: RefCell
::new(Some(iter
)),
49 impl<'a
, I
, F
> fmt
::Display
for FormatWith
<'a
, I
, F
>
51 F
: FnMut(I
::Item
, &mut FnMut(&fmt
::Display
) -> fmt
::Result
) -> fmt
::Result
53 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
54 let (mut iter
, mut format
) = match self.inner
.borrow_mut().take() {
56 None
=> panic
!("FormatWith: was already formatted once"),
59 if let Some(fst
) = iter
.next() {
60 try
!(format(fst
, &mut |disp
: &fmt
::Display
| disp
.fmt(f
)));
62 if self.sep
.len() > 0 {
64 try
!(f
.write_str(self.sep
));
66 try
!(format(elt
, &mut |disp
: &fmt
::Display
| disp
.fmt(f
)));
73 impl<'a
, I
> Format
<'a
, I
>
76 fn format
<F
>(&self, f
: &mut fmt
::Formatter
, mut cb
: F
) -> fmt
::Result
77 where F
: FnMut(&I
::Item
, &mut fmt
::Formatter
) -> fmt
::Result
,
79 let mut iter
= match self.inner
.borrow_mut().take() {
81 None
=> panic
!("Format: was already formatted once"),
84 if let Some(fst
) = iter
.next() {
87 if self.sep
.len() > 0 {
88 try
!(f
.write_str(self.sep
));
97 macro_rules
! impl_format
{
98 ($
($fmt_trait
:ident
)*) => {
100 impl<'a
, I
> fmt
::$fmt_trait
for Format
<'a
, I
>
102 I
::Item
: fmt
::$fmt_trait
,
104 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
105 self.format(f
, fmt
::$fmt_trait
::fmt
)
112 impl_format
!{Display Debug
113 UpperExp LowerExp UpperHex LowerHex Octal Binary Pointer
}