| 1 |
# writeable [](https://crates.io/crates/writeable) |
| 2 |
|
| 3 |
<!-- cargo-rdme start --> |
| 4 |
|
| 5 |
This crate defines [`Writeable`], a trait representing an object that can be written to a |
| 6 |
sink implementing `std::fmt::Write`. It is an alternative to `std::fmt::Display` with the |
| 7 |
addition of a function indicating the number of bytes to be written. |
| 8 |
|
| 9 |
`Writeable` improves upon `std::fmt::Display` in two ways: |
| 10 |
|
| 11 |
1. More efficient, since the sink can pre-allocate bytes. |
| 12 |
2. Smaller code, since the format machinery can be short-circuited. |
| 13 |
|
| 14 |
This crate also exports [`TryWriteable`], a writeable that supports a custom error. |
| 15 |
|
| 16 |
## Benchmarks |
| 17 |
|
| 18 |
The benchmarks to generate the following data can be found in the `benches` directory. |
| 19 |
|
| 20 |
| Case | `Writeable` | `Display` | |
| 21 |
|---|---|---| |
| 22 |
| Create string from single-string message (139 chars) | 15.642 ns | 19.251 ns | |
| 23 |
| Create string from complex message | 35.830 ns | 89.478 ns | |
| 24 |
| Write complex message to buffer | 57.336 ns | 64.408 ns | |
| 25 |
|
| 26 |
## Examples |
| 27 |
|
| 28 |
```rust |
| 29 |
use std::fmt; |
| 30 |
use writeable::assert_writeable_eq; |
| 31 |
use writeable::LengthHint; |
| 32 |
use writeable::Writeable; |
| 33 |
|
| 34 |
struct WelcomeMessage<'s> { |
| 35 |
pub name: &'s str, |
| 36 |
} |
| 37 |
|
| 38 |
impl<'s> Writeable for WelcomeMessage<'s> { |
| 39 |
fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result { |
| 40 |
sink.write_str("Hello, ")?; |
| 41 |
sink.write_str(self.name)?; |
| 42 |
sink.write_char('!')?; |
| 43 |
Ok(()) |
| 44 |
} |
| 45 |
|
| 46 |
fn writeable_length_hint(&self) -> LengthHint { |
| 47 |
// "Hello, " + '!' + length of name |
| 48 |
LengthHint::exact(8 + self.name.len()) |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
let message = WelcomeMessage { name: "Alice" }; |
| 53 |
assert_writeable_eq!(&message, "Hello, Alice!"); |
| 54 |
|
| 55 |
// Types implementing `Writeable` are recommended to also implement `fmt::Display`. |
| 56 |
// This can be simply done by redirecting to the `Writeable` implementation: |
| 57 |
writeable::impl_display_with_writeable!(WelcomeMessage<'_>); |
| 58 |
assert_eq!(message.to_string(), "Hello, Alice!"); |
| 59 |
``` |
| 60 |
|
| 61 |
[`ICU4X`]: ../icu/index.html |
| 62 |
|
| 63 |
<!-- cargo-rdme end --> |
| 64 |
|
| 65 |
## More Information |
| 66 |
|
| 67 |
For more information on development, authorship, contributing etc. please visit [`ICU4X home page`](https://github.com/unicode-org/icu4x). |