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> {
write_to_parts<W: PartsWrite + ?Sized>(&self, sink: &mut W) -> fmt::Result26     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 
writeable_length_hint(&self) -> LengthHint37     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]
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result44     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45         self.write_to(f)
46     }
47 }
48 
main()49 fn main() {
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 }
62