iof/write/
separator.rs

1//! Separator and default separator.
2use std::{
3    fmt::{self, Formatter, Write as _},
4    io::{self, Write},
5};
6
7/// Position.
8///
9/// The index of the last item that has been written.
10pub type Position = usize;
11
12/// Separator.
13pub trait Separator {
14    /// Write the separator to [fmt::Write].
15    fn write_fmt(&self, f: &mut Formatter<'_>) -> fmt::Result;
16    /// Write the separator to [io::Write].
17    fn write_io(&self, s: &mut (impl Write + ?Sized)) -> io::Result<()>;
18}
19
20impl Separator for char {
21    #[inline]
22    fn write_fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
23        f.write_char(*self)
24    }
25
26    #[inline]
27    fn write_io(&self, s: &mut (impl Write + ?Sized)) -> io::Result<()> {
28        s.write_all(self.encode_utf8(&mut [0; 4]).as_bytes())
29    }
30}
31
32impl Separator for str {
33    #[inline]
34    fn write_fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
35        f.write_str(self)
36    }
37
38    #[inline]
39    fn write_io(&self, s: &mut (impl Write + ?Sized)) -> io::Result<()> {
40        s.write_all(self.as_bytes())
41    }
42}
43
44impl Separator for String {
45    #[inline]
46    fn write_fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
47        f.write_str(self)
48    }
49
50    #[inline]
51    fn write_io(&self, s: &mut (impl Write + ?Sized)) -> io::Result<()> {
52        s.write_all(self.as_bytes())
53    }
54}
55
56impl<T: Separator + ?Sized> Separator for &T {
57    #[inline]
58    fn write_fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
59        <T as Separator>::write_fmt(*self, f)
60    }
61
62    #[inline]
63    fn write_io(&self, s: &mut (impl Write + ?Sized)) -> io::Result<()> {
64        <T as Separator>::write_io(*self, s)
65    }
66}