• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

zbraniecki / icu4x / 11904027177

19 Nov 2024 12:33AM UTC coverage: 75.477% (+0.3%) from 75.174%
11904027177

push

github

web-flow
Move DateTimePattern into pattern module (#5834)

#1317

Also removes `NeoNeverMarker` and fixes #5689

258 of 319 new or added lines in 6 files covered. (80.88%)

6967 existing lines in 278 files now uncovered.

54522 of 72237 relevant lines covered (75.48%)

655305.49 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.91
/utils/writeable/src/lib.rs
1
// This file is part of ICU4X. For terms of use, please see the file
1✔
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

68
extern crate alloc;
69

70
mod cmp;
71
#[cfg(feature = "either")]
72
mod either;
73
mod impls;
74
mod ops;
75
mod parts_write_adapter;
76
mod testing;
77
mod to_string_or_borrow;
78
mod try_writeable;
79

80
use alloc::borrow::Cow;
81
use alloc::string::String;
82
use core::fmt;
83

84
pub use cmp::{cmp_str, cmp_utf8};
85
pub use to_string_or_borrow::to_string_or_borrow;
86
pub use try_writeable::TryWriteable;
87

88
/// Helper types for trait impls.
89
pub 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
UNCOV
99
    pub struct LossyWrap<T>(pub T);
×
100

101
    impl<T: TryWriteable> Writeable for LossyWrap<T> {
UNCOV
102
        fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
×
UNCOV
103
            let _ = self.0.try_write_to(sink)?;
×
UNCOV
104
            Ok(())
×
UNCOV
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
121
pub 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)]
80✔
138
#[non_exhaustive]
139
pub struct LengthHint(pub usize, pub Option<usize>);
40✔
140

141
impl LengthHint {
142
    pub fn undefined() -> Self {
7,092✔
143
        Self(0, None)
7,092✔
144
    }
7,092✔
145

146
    /// `write_to` will use exactly n bytes.
147
    pub fn exact(n: usize) -> Self {
125,606✔
148
        Self(n, Some(n))
125,606✔
149
    }
125,606✔
150

151
    /// `write_to` will use at least n bytes.
152
    pub fn at_least(n: usize) -> Self {
588✔
153
        Self(n, None)
588✔
154
    }
588✔
155

156
    /// `write_to` will use at most n bytes.
157
    pub fn at_most(n: usize) -> Self {
8✔
158
        Self(0, Some(n))
8✔
159
    }
8✔
160

161
    /// `write_to` will use between `n` and `m` bytes.
162
    pub fn between(n: usize, m: usize) -> Self {
17✔
163
        Self(Ord::min(n, m), Some(Ord::max(n, m)))
17✔
164
    }
17✔
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 {
124,160✔
180
        self.1.unwrap_or(self.0)
124,160✔
181
    }
124,160✔
182

183
    /// Returns whether the `LengthHint` indicates that the string is exactly 0 bytes long.
184
    pub fn is_zero(&self) -> bool {
101,665✔
185
        self.1 == Some(0)
101,665✔
186
    }
101,665✔
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)]
152✔
214
#[allow(clippy::exhaustive_structs)] // stable
215
pub struct Part {
216
    pub category: &'static str,
76✔
217
    pub value: &'static str,
76✔
218
}
219

220
impl 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.
231
pub 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.
242
pub 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 {
1,418✔
247
        self.write_to_parts(&mut parts_write_adapter::CoreWriteAsPartsWrite(sink))
1,418✔
248
    }
1,418✔
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 {
15,844✔
254
        self.write_to(sink)
15,844✔
255
    }
15,844✔
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 {
2,555✔
261
        LengthHint::undefined()
2,555✔
262
    }
2,555✔
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> {
98,139✔
304
        let hint = self.writeable_length_hint();
98,139✔
305
        if hint.is_zero() {
98,139✔
306
            return Cow::Borrowed("");
5✔
307
        }
308
        let mut output = String::with_capacity(hint.capacity());
98,134✔
309
        let _ = self.write_to(&mut output);
98,134✔
310
        Cow::Owned(output)
98,134✔
311
    }
98,139✔
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]
324
macro_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 {
57,219✔
331
                $crate::Writeable::write_to(&self, f)
57,219✔
332
            }
57,219✔
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 {
20,600✔
344
                $crate::Writeable::write_to_string(self).into_owned()
20,600✔
345
            }
20,600✔
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]
411
macro_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]
445
macro_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
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc