Debian Codegraph @

third_party/rust/writeable/examples/writeable_message.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
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 // This example illustrates a very simple type implementing Writeable.
6 icu_benchmark_macros::static_setup!();
7
8 use std::fmt;
9 use writeable::*;
10
11 struct WriteableMessage<W: Writeable>(W);
12
13 const GREETING: Part = Part {
14 category: "meaning",
15 value: "greeting",
16 };
17
18 const EMOJI: Part = Part {
19 category: "meaning",
20 value: "emoji",
21 };
22
23 impl<V: Writeable> Writeable for WriteableMessage<V> {
24 fn write_to_parts<W: PartsWrite + ?Sized>(&self, sink: &mut W) -> fmt::Result {
25 use fmt::Write;
26 sink.with_part(GREETING, |g| {
27 g.write_str("Hello")?;
28 g.write_str(" ")?;
29 self.0.write_to(g)
30 })?;
31 sink.write_char(' ')?;
32 sink.with_part(EMOJI, |e| e.write_char('😅'))
33 }
34
35 fn writeable_length_hint(&self) -> LengthHint {
36 LengthHint::exact(11) + self.0.writeable_length_hint()
37 }
38 }
39
40 impl<V: Writeable> fmt::Display for WriteableMessage<V> {
41 #[inline]
42 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43 self.write_to(f)
44 }
45 }
46
47 fn main() {
48 icu_benchmark_macros::main_setup!();
49
50 let (string, parts) =
51 writeable::_internal::writeable_to_parts_for_test(&WriteableMessage("world"));
52
53 assert_eq!(string, "Hello world 😅");
54
55 // Print the greeting only
56 let (start, end, _) = parts
57 .into_iter()
58 .find(|(_, _, part)| part == &GREETING)
59 .unwrap();
60 println!("{}", &string[start..end]);
61 }