Debian Codegraph @

third_party/rust/writeable/README.md

raw
1 # writeable [![crates.io](https://img.shields.io/crates/v/writeable)](https://crates.io/crates/writeable)
2
3 <!-- cargo-rdme start -->
4
5 `writeable` is a utility crate of the [`ICU4X`] project.
6
7 It includes [`Writeable`], a core trait representing an object that can be written to a
8 sink implementing `std::fmt::Write`. It is an alternative to `std::fmt::Display` with the
9 addition of a function indicating the number of bytes to be written.
10
11 `Writeable` improves upon `std::fmt::Display` in two ways:
12
13 1. More efficient, since the sink can pre-allocate bytes.
14 2. Smaller code, since the format machinery can be short-circuited.
15
16 ## Examples
17
18 ```rust
19 use std::fmt;
20 use writeable::assert_writeable_eq;
21 use writeable::LengthHint;
22 use writeable::Writeable;
23
24 struct WelcomeMessage<'s> {
25 pub name: &'s str,
26 }
27
28 impl<'s> Writeable for WelcomeMessage<'s> {
29 fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
30 sink.write_str("Hello, ")?;
31 sink.write_str(self.name)?;
32 sink.write_char('!')?;
33 Ok(())
34 }
35
36 fn writeable_length_hint(&self) -> LengthHint {
37 // "Hello, " + '!' + length of name
38 LengthHint::exact(8 + self.name.len())
39 }
40 }
41
42 let message = WelcomeMessage { name: "Alice" };
43 assert_writeable_eq!(&message, "Hello, Alice!");
44
45 // Types implementing `Writeable` are recommended to also implement `fmt::Display`.
46 // This can be simply done by redirecting to the `Writeable` implementation:
47 writeable::impl_display_with_writeable!(WelcomeMessage<'_>);
48 ```
49
50 [`ICU4X`]: ../icu/index.html
51
52 <!-- cargo-rdme end -->
53
54 ## More Information
55
56 For more information on development, authorship, contributing etc. please visit [`ICU4X home page`](https://github.com/unicode-org/icu4x).