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.
11 pub struct FormatWith
<'a
, I
, F
> {
13 /// FormatWith uses interior mutability because Display::fmt takes &self.
14 inner
: RefCell
<Option
<(I
, F
)>>,
17 /// Format all iterator elements lazily, separated by `sep`.
19 /// The format value can only be formatted once, after that the iterator is
22 /// See [`.format()`](../trait.Itertools.html#method.format)
23 /// for more information.
25 pub struct Format
<'a
, I
> {
27 /// Format uses interior mutability because Display::fmt takes &self.
28 inner
: RefCell
<Option
<I
>>,
31 pub fn new_format
<'a
, I
, F
>(iter
: I
, separator
: &'a
str, f
: F
) -> FormatWith
<'a
, I
, F
>
33 F
: FnMut(I
::Item
, &mut dyn FnMut(&dyn fmt
::Display
) -> fmt
::Result
) -> fmt
::Result
37 inner
: RefCell
::new(Some((iter
, f
))),
41 pub fn new_format_default
<'a
, I
>(iter
: I
, separator
: &'a
str) -> Format
<'a
, I
>
46 inner
: RefCell
::new(Some(iter
)),
50 impl<'a
, I
, F
> fmt
::Display
for FormatWith
<'a
, I
, F
>
52 F
: FnMut(I
::Item
, &mut dyn FnMut(&dyn fmt
::Display
) -> fmt
::Result
) -> fmt
::Result
54 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
55 let (mut iter
, mut format
) = match self.inner
.borrow_mut().take() {
57 None
=> panic
!("FormatWith: was already formatted once"),
60 if let Some(fst
) = iter
.next() {
61 format(fst
, &mut |disp
: &dyn fmt
::Display
| disp
.fmt(f
))?
;
63 if self.sep
.len() > 0 {
65 f
.write_str(self.sep
)?
;
67 format(elt
, &mut |disp
: &dyn fmt
::Display
| disp
.fmt(f
))?
;
74 impl<'a
, I
> Format
<'a
, I
>
77 fn format
<F
>(&self, f
: &mut fmt
::Formatter
, mut cb
: F
) -> fmt
::Result
78 where F
: FnMut(&I
::Item
, &mut fmt
::Formatter
) -> fmt
::Result
,
80 let mut iter
= match self.inner
.borrow_mut().take() {
82 None
=> panic
!("Format: was already formatted once"),
85 if let Some(fst
) = iter
.next() {
88 if self.sep
.len() > 0 {
89 f
.write_str(self.sep
)?
;
98 macro_rules
! impl_format
{
99 ($
($fmt_trait
:ident
)*) => {
101 impl<'a
, I
> fmt
::$fmt_trait
for Format
<'a
, I
>
103 I
::Item
: fmt
::$fmt_trait
,
105 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
106 self.format(f
, fmt
::$fmt_trait
::fmt
)
113 impl_format
!{Display Debug
114 UpperExp LowerExp UpperHex LowerHex Octal Binary Pointer
}