rune_alloc/fmt/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
//! Built-in formatting utilities.

mod impls;

use core::fmt::{self, Arguments};

use crate::borrow::TryToOwned;
use crate::error::Error;
use crate::string::String;

/// Fallible write formatting implementation.
pub trait TryWrite {
    /// Writes a string slice into this writer, returning whether the write
    /// succeeded.
    ///
    /// This method can only succeed if the entire string slice was successfully
    /// written, and this method will not return until all data has been
    /// written or an error occurs.
    ///
    /// # Errors
    ///
    /// This function will return an instance of [`Error`] on error.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::alloc::fmt::TryWrite;
    /// use rune::alloc::{String, Error};
    ///
    /// fn writer<W: TryWrite>(f: &mut W, s: &str) -> Result<(), Error> {
    ///     f.try_write_str(s)
    /// }
    ///
    /// let mut buf = String::new();
    /// writer(&mut buf, "hola")?;
    /// assert_eq!(&buf, "hola");
    /// # Ok::<_, rune::alloc::Error>(())
    /// ```
    fn try_write_str(&mut self, s: &str) -> Result<(), Error>;

    /// Writes a [`char`] into this writer, returning whether the write succeeded.
    ///
    /// A single [`char`] may be encoded as more than one byte.
    /// This method can only succeed if the entire byte sequence was successfully
    /// written, and this method will not return until all data has been
    /// written or an error occurs.
    ///
    /// # Errors
    ///
    /// This function will return an instance of [`Error`] on error.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::alloc::fmt::TryWrite;
    /// use rune::alloc::{String, Error};
    ///
    /// fn writer<W: TryWrite>(f: &mut W, c: char) -> Result<(), Error> {
    ///     f.try_write_char(c)
    /// }
    ///
    /// let mut buf = String::new();
    /// writer(&mut buf, 'a')?;
    /// writer(&mut buf, 'b')?;
    /// assert_eq!(&buf, "ab");
    /// # Ok::<_, rune::alloc::Error>(())
    /// ```
    #[inline]
    fn try_write_char(&mut self, c: char) -> Result<(), Error> {
        self.try_write_str(c.encode_utf8(&mut [0; 4]))
    }

    #[inline]
    #[doc(hidden)]
    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), Error> {
        struct Writer<'a, T>
        where
            T: ?Sized,
        {
            target: &'a mut T,
            error: Option<Error>,
        }

        impl<T> fmt::Write for Writer<'_, T>
        where
            T: ?Sized + TryWrite,
        {
            #[inline]
            fn write_str(&mut self, s: &str) -> fmt::Result {
                if let Err(error) = (*self.target).try_write_str(s) {
                    self.error = Some(error);
                }

                Ok(())
            }

            #[inline]
            fn write_char(&mut self, c: char) -> fmt::Result {
                if let Err(error) = (*self.target).try_write_char(c) {
                    self.error = Some(error);
                }

                Ok(())
            }
        }

        let mut writer = Writer {
            target: self,
            error: None,
        };

        if let Err(fmt::Error) = fmt::write(&mut writer, args) {
            return Err(Error::FormatError);
        }

        if let Some(error) = writer.error {
            Err(error)
        } else {
            Ok(())
        }
    }
}

/// The `format` function takes an [`Arguments`] struct and returns the
/// resulting formatted string.
///
/// The [`Arguments`] instance can be created with the [`format_args!`] macro.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use rune::alloc::fmt;
///
/// let s = fmt::try_format(format_args!("Hello, {}!", "world"))?;
/// assert_eq!(s, "Hello, world!");
/// # Ok::<_, rune::alloc::Error>(())
/// ```
///
/// Please note that using [`try_format!`] might be preferable. Example:
///
/// ```
/// use rune::alloc::try_format;
///
/// let s = try_format!("Hello, {}!", "world");
/// assert_eq!(s, "Hello, world!");
/// # Ok::<_, rune::alloc::Error>(())
/// ```
///
/// [`format_args!`]: core::format_args
/// [`try_format!`]: try_format!
#[inline]
pub fn try_format(args: Arguments<'_>) -> Result<String, Error> {
    #[cfg(rune_nightly)]
    fn estimated_capacity(args: &Arguments<'_>) -> usize {
        args.estimated_capacity()
    }

    #[cfg(not(rune_nightly))]
    fn estimated_capacity(_: &Arguments<'_>) -> usize {
        0
    }

    fn format_inner(args: Arguments<'_>) -> Result<String, Error> {
        let capacity = estimated_capacity(&args);
        let mut output = String::try_with_capacity(capacity)?;
        output.write_fmt(args)?;
        Ok(output)
    }

    match args.as_str() {
        Some(string) => string.try_to_owned(),
        None => format_inner(args),
    }
}