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

zbraniecki / icu4x / 8611306223

09 Apr 2024 06:09AM UTC coverage: 76.234% (+0.2%) from 75.985%
8611306223

push

github

web-flow
Updating tutorial lock files (#4784)

Needed for https://github.com/unicode-org/icu4x/pull/4776

51696 of 67812 relevant lines covered (76.23%)

512021.21 hits per line

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

98.82
/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
//! ```
64
//!
65
//! [`ICU4X`]: ../icu/index.html
66

67
extern crate alloc;
68

69
mod cmp;
70
#[cfg(feature = "either")]
71
mod either;
72
mod impls;
73
mod ops;
74

75
use alloc::borrow::Cow;
76
use alloc::string::String;
77
use alloc::vec::Vec;
78
use core::fmt;
79

80
/// A hint to help consumers of `Writeable` pre-allocate bytes before they call
81
/// [`write_to`](Writeable::write_to).
82
///
83
/// This behaves like `Iterator::size_hint`: it is a tuple where the first element is the
84
/// lower bound, and the second element is the upper bound. If the upper bound is `None`
85
/// either there is no known upper bound, or the upper bound is larger than `usize`.
86
///
87
/// `LengthHint` implements std`::ops::{Add, Mul}` and similar traits for easy composition.
88
/// During computation, the lower bound will saturate at `usize::MAX`, while the upper
89
/// bound will become `None` if `usize::MAX` is exceeded.
90
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
78✔
91
#[non_exhaustive]
92
pub struct LengthHint(pub usize, pub Option<usize>);
39✔
93

94
impl LengthHint {
95
    pub fn undefined() -> Self {
3,760✔
96
        Self(0, None)
3,760✔
97
    }
3,760✔
98

99
    /// `write_to` will use exactly n bytes.
100
    pub fn exact(n: usize) -> Self {
113,659✔
101
        Self(n, Some(n))
113,659✔
102
    }
113,659✔
103

104
    /// `write_to` will use at least n bytes.
105
    pub fn at_least(n: usize) -> Self {
587✔
106
        Self(n, None)
587✔
107
    }
587✔
108

109
    /// `write_to` will use at most n bytes.
110
    pub fn at_most(n: usize) -> Self {
8✔
111
        Self(0, Some(n))
8✔
112
    }
8✔
113

114
    /// `write_to` will use between `n` and `m` bytes.
115
    pub fn between(n: usize, m: usize) -> Self {
10✔
116
        Self(Ord::min(n, m), Some(Ord::max(n, m)))
10✔
117
    }
10✔
118

119
    /// Returns a recommendation for the number of bytes to pre-allocate.
120
    /// If an upper bound exists, this is used, otherwise the lower bound
121
    /// (which might be 0).
122
    ///
123
    /// # Examples
124
    ///
125
    /// ```
126
    /// use writeable::Writeable;
127
    ///
128
    /// fn pre_allocate_string(w: &impl Writeable) -> String {
129
    ///     String::with_capacity(w.writeable_length_hint().capacity())
130
    /// }
131
    /// ```
132
    pub fn capacity(&self) -> usize {
104,784✔
133
        self.1.unwrap_or(self.0)
104,784✔
134
    }
104,784✔
135

136
    /// Returns whether the `LengthHint` indicates that the string is exactly 0 bytes long.
137
    pub fn is_zero(&self) -> bool {
97,626✔
138
        self.1 == Some(0)
97,626✔
139
    }
97,626✔
140
}
141

142
/// [`Part`]s are used as annotations for formatted strings. For example, a string like
143
/// `Alice, Bob` could assign a `NAME` part to the substrings `Alice` and `Bob`, and a
144
/// `PUNCTUATION` part to `, `. This allows for example to apply styling only to names.
145
///
146
/// `Part` contains two fields, whose usage is left up to the producer of the [`Writeable`].
147
/// Conventionally, the `category` field will identify the formatting logic that produces
148
/// the string/parts, whereas the `value` field will have semantic meaning. `NAME` and
149
/// `PUNCTUATION` could thus be defined as
150
/// ```
151
/// # use writeable::Part;
152
/// const NAME: Part = Part {
153
///     category: "userlist",
154
///     value: "name",
155
/// };
156
/// const PUNCTUATION: Part = Part {
157
///     category: "userlist",
158
///     value: "punctuation",
159
/// };
160
/// ```
161
///
162
/// That said, consumers should not usually have to inspect `Part` internals. Instead,
163
/// formatters should expose the `Part`s they produces as constants.
164
#[derive(Clone, Copy, Debug, PartialEq)]
42✔
165
#[allow(clippy::exhaustive_structs)] // stable
166
pub struct Part {
167
    pub category: &'static str,
21✔
168
    pub value: &'static str,
21✔
169
}
170

171
/// A sink that supports annotating parts of the string with `Part`s.
172
pub trait PartsWrite: fmt::Write {
173
    type SubPartsWrite: PartsWrite + ?Sized;
174

175
    fn with_part(
176
        &mut self,
177
        part: Part,
178
        f: impl FnMut(&mut Self::SubPartsWrite) -> fmt::Result,
179
    ) -> fmt::Result;
180
}
181

182
/// `Writeable` is an alternative to `std::fmt::Display` with the addition of a length function.
183
pub trait Writeable {
184
    /// Writes a string to the given sink. Errors from the sink are bubbled up.
185
    /// The default implementation delegates to `write_to_parts`, and discards any
186
    /// `Part` annotations.
187
    fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
1,402✔
188
        struct CoreWriteAsPartsWrite<W: fmt::Write + ?Sized>(W);
189
        impl<W: fmt::Write + ?Sized> fmt::Write for CoreWriteAsPartsWrite<W> {
190
            fn write_str(&mut self, s: &str) -> fmt::Result {
2,480✔
191
                self.0.write_str(s)
2,480✔
192
            }
2,480✔
193

194
            fn write_char(&mut self, c: char) -> fmt::Result {
1,189✔
195
                self.0.write_char(c)
1,189✔
196
            }
1,189✔
197
        }
198

199
        impl<W: fmt::Write + ?Sized> PartsWrite for CoreWriteAsPartsWrite<W> {
200
            type SubPartsWrite = CoreWriteAsPartsWrite<W>;
201

202
            fn with_part(
2,482✔
203
                &mut self,
204
                _part: Part,
205
                mut f: impl FnMut(&mut Self::SubPartsWrite) -> fmt::Result,
206
            ) -> fmt::Result {
207
                f(self)
2,482✔
208
            }
2,482✔
209
        }
210

211
        self.write_to_parts(&mut CoreWriteAsPartsWrite(sink))
1,402✔
212
    }
1,402✔
213

214
    /// Write bytes and `Part` annotations to the given sink. Errors from the
215
    /// sink are bubbled up. The default implementation delegates to `write_to`,
216
    /// and doesn't produce any `Part` annotations.
217
    fn write_to_parts<S: PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result {
7,359✔
218
        self.write_to(sink)
7,359✔
219
    }
7,359✔
220

221
    /// Returns a hint for the number of UTF-8 bytes that will be written to the sink.
222
    ///
223
    /// Override this method if it can be computed quickly.
224
    fn writeable_length_hint(&self) -> LengthHint {
3,582✔
225
        LengthHint::undefined()
3,582✔
226
    }
3,582✔
227

228
    /// Creates a new `String` with the data from this `Writeable`. Like `ToString`,
229
    /// but smaller and faster.
230
    ///
231
    /// The default impl allocates an owned `String`. However, if it is possible to return a
232
    /// borrowed string, overwrite this method to return a `Cow::Borrowed`.
233
    ///
234
    /// To remove the `Cow` wrapper, call `.into_owned()` or `.as_str()` as appropriate.
235
    ///
236
    /// # Examples
237
    ///
238
    /// Inspect a `Writeable` before writing it to the sink:
239
    ///
240
    /// ```
241
    /// use core::fmt::{Result, Write};
242
    /// use writeable::Writeable;
243
    ///
244
    /// fn write_if_ascii<W, S>(w: &W, sink: &mut S) -> Result
245
    /// where
246
    ///     W: Writeable + ?Sized,
247
    ///     S: Write + ?Sized,
248
    /// {
249
    ///     let s = w.write_to_string();
250
    ///     if s.is_ascii() {
251
    ///         sink.write_str(&s)
252
    ///     } else {
253
    ///         Ok(())
254
    ///     }
255
    /// }
256
    /// ```
257
    ///
258
    /// Convert the `Writeable` into a fully owned `String`:
259
    ///
260
    /// ```
261
    /// use writeable::Writeable;
262
    ///
263
    /// fn make_string(w: &impl Writeable) -> String {
264
    ///     w.write_to_string().into_owned()
265
    /// }
266
    /// ```
267
    fn write_to_string(&self) -> Cow<str> {
97,634✔
268
        let hint = self.writeable_length_hint();
97,634✔
269
        if hint.is_zero() {
97,634✔
270
            return Cow::Borrowed("");
4✔
271
        }
272
        let mut output = String::with_capacity(hint.capacity());
97,630✔
273
        let _ = self.write_to(&mut output);
97,630✔
274
        Cow::Owned(output)
97,630✔
275
    }
97,634✔
276

277
    /// Compares the contents of this `Writeable` to the given bytes
278
    /// without allocating a String to hold the `Writeable` contents.
279
    ///
280
    /// This returns a lexicographical comparison, the same as if the Writeable
281
    /// were first converted to a String and then compared with `Ord`. For a
282
    /// locale-sensitive string ordering, use an ICU4X Collator.
283
    ///
284
    /// # Examples
285
    ///
286
    /// ```
287
    /// use core::cmp::Ordering;
288
    /// use core::fmt;
289
    /// use writeable::Writeable;
290
    ///
291
    /// struct WelcomeMessage<'s> {
292
    ///     pub name: &'s str,
293
    /// }
294
    ///
295
    /// impl<'s> Writeable for WelcomeMessage<'s> {
296
    ///     // see impl in Writeable docs
297
    /// #    fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
298
    /// #        sink.write_str("Hello, ")?;
299
    /// #        sink.write_str(self.name)?;
300
    /// #        sink.write_char('!')?;
301
    /// #        Ok(())
302
    /// #    }
303
    /// }
304
    ///
305
    /// let message = WelcomeMessage { name: "Alice" };
306
    /// let message_str = message.write_to_string();
307
    ///
308
    /// assert_eq!(Ordering::Equal, message.write_cmp_bytes(b"Hello, Alice!"));
309
    ///
310
    /// assert_eq!(Ordering::Greater, message.write_cmp_bytes(b"Alice!"));
311
    /// assert_eq!(Ordering::Greater, (*message_str).cmp("Alice!"));
312
    ///
313
    /// assert_eq!(Ordering::Less, message.write_cmp_bytes(b"Hello, Bob!"));
314
    /// assert_eq!(Ordering::Less, (*message_str).cmp("Hello, Bob!"));
315
    /// ```
316
    fn write_cmp_bytes(&self, other: &[u8]) -> core::cmp::Ordering {
87,763✔
317
        let mut wc = cmp::WriteComparator::new(other);
87,763✔
318
        #[allow(clippy::unwrap_used)] // infallible impl
319
        self.write_to(&mut wc).unwrap();
87,763✔
320
        wc.finish().reverse()
87,763✔
321
    }
87,763✔
322
}
323

324
/// Implements [`Display`](core::fmt::Display) for types that implement [`Writeable`].
325
///
326
/// It's recommended to do this for every [`Writeable`] type, as it will add
327
/// support for `core::fmt` features like [`fmt!`](std::fmt),
328
/// [`print!`](std::print), [`write!`](std::write), etc.
329
#[macro_export]
330
macro_rules! impl_display_with_writeable {
331
    ($type:ty) => {
332
        /// This trait is implemented for compatibility with [`fmt!`](alloc::fmt).
333
        /// To create a string, [`Writeable::write_to_string`] is usually more efficient.
334
        impl core::fmt::Display for $type {
335
            #[inline]
336
            fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
22,563✔
337
                $crate::Writeable::write_to(&self, f)
22,563✔
338
            }
22,563✔
339
        }
340
    };
341
}
342

343
/// Testing macros for types implementing Writeable. The first argument should be a
344
/// `Writeable`, the second argument a string, and the third argument (*_parts_eq only)
345
/// a list of parts (`[(usize, usize, Part)]`).
346
///
347
/// The macros tests for equality of string content, parts (*_parts_eq only), and
348
/// verify the size hint.
349
///
350
/// # Examples
351
///
352
/// ```
353
/// # use writeable::Writeable;
354
/// # use writeable::LengthHint;
355
/// # use writeable::Part;
356
/// # use writeable::assert_writeable_eq;
357
/// # use writeable::assert_writeable_parts_eq;
358
/// # use std::fmt::{self, Write};
359
///
360
/// const WORD: Part = Part {
361
///     category: "foo",
362
///     value: "word",
363
/// };
364
///
365
/// struct Demo;
366
/// impl Writeable for Demo {
367
///     fn write_to_parts<S: writeable::PartsWrite + ?Sized>(
368
///         &self,
369
///         sink: &mut S,
370
///     ) -> fmt::Result {
371
///         sink.with_part(WORD, |w| w.write_str("foo"))
372
///     }
373
///     fn writeable_length_hint(&self) -> LengthHint {
374
///         LengthHint::exact(3)
375
///     }
376
/// }
377
///
378
/// writeable::impl_display_with_writeable!(Demo);
379
///
380
/// assert_writeable_eq!(&Demo, "foo");
381
/// assert_writeable_eq!(&Demo, "foo", "Message: {}", "Hello World");
382
///
383
/// assert_writeable_parts_eq!(&Demo, "foo", [(0, 3, WORD)]);
384
/// assert_writeable_parts_eq!(
385
///     &Demo,
386
///     "foo",
387
///     [(0, 3, WORD)],
388
///     "Message: {}",
389
///     "Hello World"
390
/// );
391
/// ```
392
#[macro_export]
393
macro_rules! assert_writeable_eq {
394
    ($actual_writeable:expr, $expected_str:expr $(,)?) => {
395
        $crate::assert_writeable_eq!($actual_writeable, $expected_str, "");
396
    };
397
    ($actual_writeable:expr, $expected_str:expr, $($arg:tt)+) => {{
398
        let actual_writeable = &$actual_writeable;
399
        let (actual_str, _) = $crate::writeable_to_parts_for_test(actual_writeable).unwrap();
400
        assert_eq!(actual_str, $expected_str, $($arg)*);
401
        assert_eq!(actual_str, $crate::Writeable::write_to_string(actual_writeable), $($arg)+);
402
        let length_hint = $crate::Writeable::writeable_length_hint(actual_writeable);
403
        assert!(
404
            length_hint.0 <= actual_str.len(),
405
            "hint lower bound {} larger than actual length {}: {}",
406
            length_hint.0, actual_str.len(), format!($($arg)*),
407
        );
408
        if let Some(upper) = length_hint.1 {
409
            assert!(
410
                actual_str.len() <= upper,
411
                "hint upper bound {} smaller than actual length {}: {}",
412
                length_hint.0, actual_str.len(), format!($($arg)*),
413
            );
414
        }
415
        assert_eq!(actual_writeable.to_string(), $expected_str);
416
    }};
417
}
418

419
/// See [`assert_writeable_eq`].
420
#[macro_export]
421
macro_rules! assert_writeable_parts_eq {
422
    ($actual_writeable:expr, $expected_str:expr, $expected_parts:expr $(,)?) => {
423
        $crate::assert_writeable_parts_eq!($actual_writeable, $expected_str, $expected_parts, "");
424
    };
425
    ($actual_writeable:expr, $expected_str:expr, $expected_parts:expr, $($arg:tt)+) => {{
426
        let actual_writeable = &$actual_writeable;
427
        let (actual_str, actual_parts) = $crate::writeable_to_parts_for_test(actual_writeable).unwrap();
428
        assert_eq!(actual_str, $expected_str, $($arg)+);
429
        assert_eq!(actual_str, $crate::Writeable::write_to_string(actual_writeable), $($arg)+);
430
        assert_eq!(actual_parts, $expected_parts, $($arg)+);
431
        let length_hint = $crate::Writeable::writeable_length_hint(actual_writeable);
432
        assert!(length_hint.0 <= actual_str.len(), $($arg)+);
433
        if let Some(upper) = length_hint.1 {
434
            assert!(actual_str.len() <= upper, $($arg)+);
435
        }
436
        assert_eq!(actual_writeable.to_string(), $expected_str);
437
    }};
438
}
439

440
#[doc(hidden)]
441
#[allow(clippy::type_complexity)]
442
pub fn writeable_to_parts_for_test<W: Writeable>(
6,388✔
443
    writeable: &W,
444
) -> Result<(String, Vec<(usize, usize, Part)>), fmt::Error> {
445
    struct State {
446
        string: alloc::string::String,
447
        parts: Vec<(usize, usize, Part)>,
448
    }
449

450
    impl fmt::Write for State {
451
        fn write_str(&mut self, s: &str) -> fmt::Result {
9,754✔
452
            self.string.write_str(s)
9,754✔
453
        }
9,754✔
454
        fn write_char(&mut self, c: char) -> fmt::Result {
11,505✔
455
            self.string.write_char(c)
11,505✔
456
        }
11,505✔
457
    }
458

459
    impl PartsWrite for State {
460
        type SubPartsWrite = Self;
461
        fn with_part(
158✔
462
            &mut self,
463
            part: Part,
464
            mut f: impl FnMut(&mut Self::SubPartsWrite) -> fmt::Result,
465
        ) -> fmt::Result {
466
            let start = self.string.len();
158✔
467
            f(self)?;
158✔
468
            let end = self.string.len();
158✔
469
            if start < end {
158✔
470
                self.parts.push((start, end, part));
112✔
471
            }
472
            Ok(())
158✔
473
        }
158✔
474
    }
475

476
    let mut state = State {
6,388✔
477
        string: alloc::string::String::new(),
6,388✔
478
        parts: Vec::new(),
6,388✔
479
    };
×
480
    writeable.write_to_parts(&mut state)?;
6,388✔
481

482
    // Sort by first open and last closed
483
    state
6,388✔
484
        .parts
485
        .sort_unstable_by_key(|(begin, end, _)| (*begin, end.wrapping_neg()));
164✔
486
    Ok((state.string, state.parts))
6,388✔
487
}
6,388✔
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