writeable/
lib.rs

1// This file is part of ICU4X. For terms of use, please see the file
2// called LICENSE at the top level of the ICU4X source tree
3// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5// https://github.com/unicode-org/icu4x/blob/main/documents/process/boilerplate.md#library-annotations
6#![cfg_attr(all(not(test), not(doc)), no_std)]
7#![cfg_attr(
8    not(test),
9    deny(
10        clippy::indexing_slicing,
11        clippy::unwrap_used,
12        clippy::expect_used,
13        clippy::panic,
14        clippy::exhaustive_structs,
15        clippy::exhaustive_enums,
16        missing_debug_implementations,
17    )
18)]
19
20//! `writeable` is a utility crate of the [`ICU4X`] project.
21//!
22//! It includes [`Writeable`], a core trait representing an object that can be written to a
23//! sink implementing `std::fmt::Write`. It is an alternative to `std::fmt::Display` with the
24//! addition of a function indicating the number of bytes to be written.
25//!
26//! `Writeable` improves upon `std::fmt::Display` in two ways:
27//!
28//! 1. More efficient, since the sink can pre-allocate bytes.
29//! 2. Smaller code, since the format machinery can be short-circuited.
30//!
31//! # Examples
32//!
33//! ```
34//! use std::fmt;
35//! use writeable::assert_writeable_eq;
36//! use writeable::LengthHint;
37//! use writeable::Writeable;
38//!
39//! struct WelcomeMessage<'s> {
40//!     pub name: &'s str,
41//! }
42//!
43//! impl<'s> Writeable for WelcomeMessage<'s> {
44//!     fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
45//!         sink.write_str("Hello, ")?;
46//!         sink.write_str(self.name)?;
47//!         sink.write_char('!')?;
48//!         Ok(())
49//!     }
50//!
51//!     fn writeable_length_hint(&self) -> LengthHint {
52//!         // "Hello, " + '!' + length of name
53//!         LengthHint::exact(8 + self.name.len())
54//!     }
55//! }
56//!
57//! let message = WelcomeMessage { name: "Alice" };
58//! assert_writeable_eq!(&message, "Hello, Alice!");
59//!
60//! // Types implementing `Writeable` are recommended to also implement `fmt::Display`.
61//! // This can be simply done by redirecting to the `Writeable` implementation:
62//! writeable::impl_display_with_writeable!(WelcomeMessage<'_>);
63//! assert_eq!(message.to_string(), "Hello, Alice!");
64//! ```
65//!
66//! [`ICU4X`]: ../icu/index.html
67
68extern crate alloc;
69
70mod cmp;
71#[cfg(feature = "either")]
72mod either;
73mod impls;
74mod ops;
75mod parts_write_adapter;
76mod testing;
77mod to_string_or_borrow;
78mod try_writeable;
79
80use alloc::borrow::Cow;
81use alloc::string::String;
82use core::fmt;
83
84pub use cmp::{cmp_str, cmp_utf8};
85pub use to_string_or_borrow::to_string_or_borrow;
86pub use try_writeable::TryWriteable;
87
88/// Helper types for trait impls.
89pub mod adapters {
90    use super::*;
91
92    pub use parts_write_adapter::CoreWriteAsPartsWrite;
93    pub use parts_write_adapter::WithPart;
94    pub use try_writeable::TryWriteableInfallibleAsWriteable;
95    pub use try_writeable::WriteableAsTryWriteableInfallible;
96
97    #[derive(Debug)]
98    #[allow(clippy::exhaustive_structs)] // newtype
99    pub struct LossyWrap<T>(pub T);
100
101    impl<T: TryWriteable> Writeable for LossyWrap<T> {
102        fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
103            let _ = self.0.try_write_to(sink)?;
104            Ok(())
105        }
106
107        fn writeable_length_hint(&self) -> LengthHint {
108            self.0.writeable_length_hint()
109        }
110    }
111
112    impl<T: TryWriteable> fmt::Display for LossyWrap<T> {
113        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114            let _ = self.0.try_write_to(f)?;
115            Ok(())
116        }
117    }
118}
119
120#[doc(hidden)] // for testing and macros
121pub mod _internal {
122    pub use super::testing::try_writeable_to_parts_for_test;
123    pub use super::testing::writeable_to_parts_for_test;
124    pub use alloc::string::String;
125}
126
127/// A hint to help consumers of `Writeable` pre-allocate bytes before they call
128/// [`write_to`](Writeable::write_to).
129///
130/// This behaves like `Iterator::size_hint`: it is a tuple where the first element is the
131/// lower bound, and the second element is the upper bound. If the upper bound is `None`
132/// either there is no known upper bound, or the upper bound is larger than `usize`.
133///
134/// `LengthHint` implements std`::ops::{Add, Mul}` and similar traits for easy composition.
135/// During computation, the lower bound will saturate at `usize::MAX`, while the upper
136/// bound will become `None` if `usize::MAX` is exceeded.
137#[derive(Debug, PartialEq, Eq, Copy, Clone)]
138#[non_exhaustive]
139pub struct LengthHint(pub usize, pub Option<usize>);
140
141impl LengthHint {
142    pub fn undefined() -> Self {
143        Self(0, None)
144    }
145
146    /// `write_to` will use exactly n bytes.
147    pub fn exact(n: usize) -> Self {
148        Self(n, Some(n))
149    }
150
151    /// `write_to` will use at least n bytes.
152    pub fn at_least(n: usize) -> Self {
153        Self(n, None)
154    }
155
156    /// `write_to` will use at most n bytes.
157    pub fn at_most(n: usize) -> Self {
158        Self(0, Some(n))
159    }
160
161    /// `write_to` will use between `n` and `m` bytes.
162    pub fn between(n: usize, m: usize) -> Self {
163        Self(Ord::min(n, m), Some(Ord::max(n, m)))
164    }
165
166    /// Returns a recommendation for the number of bytes to pre-allocate.
167    /// If an upper bound exists, this is used, otherwise the lower bound
168    /// (which might be 0).
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// use writeable::Writeable;
174    ///
175    /// fn pre_allocate_string(w: &impl Writeable) -> String {
176    ///     String::with_capacity(w.writeable_length_hint().capacity())
177    /// }
178    /// ```
179    pub fn capacity(&self) -> usize {
180        self.1.unwrap_or(self.0)
181    }
182
183    /// Returns whether the `LengthHint` indicates that the string is exactly 0 bytes long.
184    pub fn is_zero(&self) -> bool {
185        self.1 == Some(0)
186    }
187}
188
189/// [`Part`]s are used as annotations for formatted strings.
190///
191/// For example, a string like `Alice, Bob` could assign a `NAME` part to the
192/// substrings `Alice` and `Bob`, and a `PUNCTUATION` part to `, `. This allows
193/// for example to apply styling only to names.
194///
195/// `Part` contains two fields, whose usage is left up to the producer of the [`Writeable`].
196/// Conventionally, the `category` field will identify the formatting logic that produces
197/// the string/parts, whereas the `value` field will have semantic meaning. `NAME` and
198/// `PUNCTUATION` could thus be defined as
199/// ```
200/// # use writeable::Part;
201/// const NAME: Part = Part {
202///     category: "userlist",
203///     value: "name",
204/// };
205/// const PUNCTUATION: Part = Part {
206///     category: "userlist",
207///     value: "punctuation",
208/// };
209/// ```
210///
211/// That said, consumers should not usually have to inspect `Part` internals. Instead,
212/// formatters should expose the `Part`s they produces as constants.
213#[derive(Clone, Copy, Debug, PartialEq)]
214#[allow(clippy::exhaustive_structs)] // stable
215pub struct Part {
216    pub category: &'static str,
217    pub value: &'static str,
218}
219
220impl Part {
221    /// A part that should annotate error segments in [`TryWriteable`] output.
222    ///
223    /// For an example, see [`TryWriteable`].
224    pub const ERROR: Part = Part {
225        category: "writeable",
226        value: "error",
227    };
228}
229
230/// A sink that supports annotating parts of the string with `Part`s.
231pub trait PartsWrite: fmt::Write {
232    type SubPartsWrite: PartsWrite + ?Sized;
233
234    fn with_part(
235        &mut self,
236        part: Part,
237        f: impl FnMut(&mut Self::SubPartsWrite) -> fmt::Result,
238    ) -> fmt::Result;
239}
240
241/// `Writeable` is an alternative to `std::fmt::Display` with the addition of a length function.
242pub trait Writeable {
243    /// Writes a string to the given sink. Errors from the sink are bubbled up.
244    /// The default implementation delegates to `write_to_parts`, and discards any
245    /// `Part` annotations.
246    fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
247        self.write_to_parts(&mut parts_write_adapter::CoreWriteAsPartsWrite(sink))
248    }
249
250    /// Write bytes and `Part` annotations to the given sink. Errors from the
251    /// sink are bubbled up. The default implementation delegates to `write_to`,
252    /// and doesn't produce any `Part` annotations.
253    fn write_to_parts<S: PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result {
254        self.write_to(sink)
255    }
256
257    /// Returns a hint for the number of UTF-8 bytes that will be written to the sink.
258    ///
259    /// Override this method if it can be computed quickly.
260    fn writeable_length_hint(&self) -> LengthHint {
261        LengthHint::undefined()
262    }
263
264    /// Creates a new `String` with the data from this `Writeable`. Like `ToString`,
265    /// but smaller and faster.
266    ///
267    /// The default impl allocates an owned `String`. However, if it is possible to return a
268    /// borrowed string, overwrite this method to return a `Cow::Borrowed`.
269    ///
270    /// To remove the `Cow` wrapper, call `.into_owned()` or `.as_str()` as appropriate.
271    ///
272    /// # Examples
273    ///
274    /// Inspect a `Writeable` before writing it to the sink:
275    ///
276    /// ```
277    /// use core::fmt::{Result, Write};
278    /// use writeable::Writeable;
279    ///
280    /// fn write_if_ascii<W, S>(w: &W, sink: &mut S) -> Result
281    /// where
282    ///     W: Writeable + ?Sized,
283    ///     S: Write + ?Sized,
284    /// {
285    ///     let s = w.write_to_string();
286    ///     if s.is_ascii() {
287    ///         sink.write_str(&s)
288    ///     } else {
289    ///         Ok(())
290    ///     }
291    /// }
292    /// ```
293    ///
294    /// Convert the `Writeable` into a fully owned `String`:
295    ///
296    /// ```
297    /// use writeable::Writeable;
298    ///
299    /// fn make_string(w: &impl Writeable) -> String {
300    ///     w.write_to_string().into_owned()
301    /// }
302    /// ```
303    fn write_to_string(&self) -> Cow<str> {
304        let hint = self.writeable_length_hint();
305        if hint.is_zero() {
306            return Cow::Borrowed("");
307        }
308        let mut output = String::with_capacity(hint.capacity());
309        let _ = self.write_to(&mut output);
310        Cow::Owned(output)
311    }
312}
313
314/// Implements [`Display`](core::fmt::Display) for types that implement [`Writeable`].
315///
316/// It's recommended to do this for every [`Writeable`] type, as it will add
317/// support for `core::fmt` features like [`fmt!`](std::fmt),
318/// [`print!`](std::print), [`write!`](std::write), etc.
319///
320/// This macro also adds a concrete `to_string` function. This function will shadow the
321/// standard library `ToString`, using the more efficient writeable-based code path.
322/// To add only `Display`, use the `@display` macro variant.
323#[macro_export]
324macro_rules! impl_display_with_writeable {
325    (@display, $type:ty) => {
326        /// This trait is implemented for compatibility with [`fmt!`](alloc::fmt).
327        /// To create a string, [`Writeable::write_to_string`] is usually more efficient.
328        impl core::fmt::Display for $type {
329            #[inline]
330            fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
331                $crate::Writeable::write_to(&self, f)
332            }
333        }
334    };
335    ($type:ty) => {
336        $crate::impl_display_with_writeable!(@display, $type);
337        impl $type {
338            /// Converts the given value to a `String`.
339            ///
340            /// Under the hood, this uses an efficient [`Writeable`] implementation.
341            /// However, in order to avoid allocating a string, it is more efficient
342            /// to use [`Writeable`] directly.
343            pub fn to_string(&self) -> $crate::_internal::String {
344                $crate::Writeable::write_to_string(self).into_owned()
345            }
346        }
347    };
348}
349
350/// Testing macros for types implementing [`Writeable`].
351///
352/// Arguments, in order:
353///
354/// 1. The [`Writeable`] under test
355/// 2. The expected string value
356/// 3. [`*_parts_eq`] only: a list of parts (`[(start, end, Part)]`)
357///
358/// Any remaining arguments get passed to `format!`
359///
360/// The macros tests the following:
361///
362/// - Equality of string content
363/// - Equality of parts ([`*_parts_eq`] only)
364/// - Validity of size hint
365///
366/// # Examples
367///
368/// ```
369/// # use writeable::Writeable;
370/// # use writeable::LengthHint;
371/// # use writeable::Part;
372/// # use writeable::assert_writeable_eq;
373/// # use writeable::assert_writeable_parts_eq;
374/// # use std::fmt::{self, Write};
375///
376/// const WORD: Part = Part {
377///     category: "foo",
378///     value: "word",
379/// };
380///
381/// struct Demo;
382/// impl Writeable for Demo {
383///     fn write_to_parts<S: writeable::PartsWrite + ?Sized>(
384///         &self,
385///         sink: &mut S,
386///     ) -> fmt::Result {
387///         sink.with_part(WORD, |w| w.write_str("foo"))
388///     }
389///     fn writeable_length_hint(&self) -> LengthHint {
390///         LengthHint::exact(3)
391///     }
392/// }
393///
394/// writeable::impl_display_with_writeable!(Demo);
395///
396/// assert_writeable_eq!(&Demo, "foo");
397/// assert_writeable_eq!(&Demo, "foo", "Message: {}", "Hello World");
398///
399/// assert_writeable_parts_eq!(&Demo, "foo", [(0, 3, WORD)]);
400/// assert_writeable_parts_eq!(
401///     &Demo,
402///     "foo",
403///     [(0, 3, WORD)],
404///     "Message: {}",
405///     "Hello World"
406/// );
407/// ```
408///
409/// [`*_parts_eq`]: assert_writeable_parts_eq
410#[macro_export]
411macro_rules! assert_writeable_eq {
412    ($actual_writeable:expr, $expected_str:expr $(,)?) => {
413        $crate::assert_writeable_eq!($actual_writeable, $expected_str, "")
414    };
415    ($actual_writeable:expr, $expected_str:expr, $($arg:tt)+) => {{
416        $crate::assert_writeable_eq!(@internal, $actual_writeable, $expected_str, $($arg)*);
417    }};
418    (@internal, $actual_writeable:expr, $expected_str:expr, $($arg:tt)+) => {{
419        let actual_writeable = &$actual_writeable;
420        let (actual_str, actual_parts) = $crate::_internal::writeable_to_parts_for_test(actual_writeable);
421        let actual_len = actual_str.len();
422        assert_eq!(actual_str, $expected_str, $($arg)*);
423        assert_eq!(actual_str, $crate::Writeable::write_to_string(actual_writeable), $($arg)+);
424        let length_hint = $crate::Writeable::writeable_length_hint(actual_writeable);
425        let lower = length_hint.0;
426        assert!(
427            lower <= actual_len,
428            "hint lower bound {lower} larger than actual length {actual_len}: {}",
429            format!($($arg)*),
430        );
431        if let Some(upper) = length_hint.1 {
432            assert!(
433                actual_len <= upper,
434                "hint upper bound {upper} smaller than actual length {actual_len}: {}",
435                format!($($arg)*),
436            );
437        }
438        assert_eq!(actual_writeable.to_string(), $expected_str);
439        actual_parts // return for assert_writeable_parts_eq
440    }};
441}
442
443/// See [`assert_writeable_eq`].
444#[macro_export]
445macro_rules! assert_writeable_parts_eq {
446    ($actual_writeable:expr, $expected_str:expr, $expected_parts:expr $(,)?) => {
447        $crate::assert_writeable_parts_eq!($actual_writeable, $expected_str, $expected_parts, "")
448    };
449    ($actual_writeable:expr, $expected_str:expr, $expected_parts:expr, $($arg:tt)+) => {{
450        let actual_parts = $crate::assert_writeable_eq!(@internal, $actual_writeable, $expected_str, $($arg)*);
451        assert_eq!(actual_parts, $expected_parts, $($arg)+);
452    }};
453}