README.md
1# writeable [](https://crates.io/crates/writeable)
2
3<!-- cargo-rdme start -->
4
5`writeable` is a utility crate of the [`ICU4X`] project.
6
7It includes [`Writeable`], a core trait representing an object that can be written to a
8sink implementing `std::fmt::Write`. It is an alternative to `std::fmt::Display` with the
9addition of a function indicating the number of bytes to be written.
10
11`Writeable` improves upon `std::fmt::Display` in two ways:
12
131. More efficient, since the sink can pre-allocate bytes.
142. Smaller code, since the format machinery can be short-circuited.
15
16## Examples
17
18```rust
19use std::fmt;
20use writeable::assert_writeable_eq;
21use writeable::LengthHint;
22use writeable::Writeable;
23
24struct WelcomeMessage<'s> {
25 pub name: &'s str,
26}
27
28impl<'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
42let message = WelcomeMessage { name: "Alice" };
43assert_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:
47writeable::impl_display_with_writeable!(WelcomeMessage<'_>);
48assert_eq!(message.to_string(), "Hello, Alice!");
49```
50
51[`ICU4X`]: ../icu/index.html
52
53<!-- cargo-rdme end -->
54
55## More Information
56
57For more information on development, authorship, contributing etc. please visit [`ICU4X home page`](https://github.com/unicode-org/icu4x).
58