Debian Codegraph @

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