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 | use crate::*; |
6 | use alloc::string::String; |
7 | use alloc::vec::Vec; |
8 | |
9 | pub(crate) struct TestWriter { |
10 | pub(crate) string: String, |
11 | pub(crate) parts: Vec<(usize, usize, Part)>, |
12 | } |
13 | |
14 | impl TestWriter { |
15 | pub(crate) fn finish(mut self) -> (String, Vec<(usize, usize, Part)>) { |
16 | // Sort by first open and last closed |
17 | self.parts |
18 | .sort_unstable_by_key(|(begin: &usize, end: &usize, _)| (*begin, end.wrapping_neg())); |
19 | (self.string, self.parts) |
20 | } |
21 | } |
22 | |
23 | impl fmt::Write for TestWriter { |
24 | fn write_str(&mut self, s: &str) -> fmt::Result { |
25 | self.string.write_str(s) |
26 | } |
27 | fn write_char(&mut self, c: char) -> fmt::Result { |
28 | self.string.write_char(c) |
29 | } |
30 | } |
31 | |
32 | impl PartsWrite for TestWriter { |
33 | type SubPartsWrite = Self; |
34 | fn with_part( |
35 | &mut self, |
36 | part: Part, |
37 | mut f: impl FnMut(&mut Self::SubPartsWrite) -> fmt::Result, |
38 | ) -> fmt::Result { |
39 | let start: usize = self.string.len(); |
40 | f(self)?; |
41 | let end: usize = self.string.len(); |
42 | if start < end { |
43 | self.parts.push((start, end, part)); |
44 | } |
45 | Ok(()) |
46 | } |
47 | } |
48 | |
49 | #[allow (clippy::type_complexity)] |
50 | pub fn writeable_to_parts_for_test<W: Writeable>( |
51 | writeable: &W, |
52 | ) -> (String, Vec<(usize, usize, Part)>) { |
53 | let mut writer: TestWriter = TestWriter { |
54 | string: alloc::string::String::new(), |
55 | parts: Vec::new(), |
56 | }; |
57 | #[allow (clippy::expect_used)] // for test code |
58 | writeable |
59 | .write_to_parts(&mut writer) |
60 | .expect(msg:"String writer infallible" ); |
61 | writer.finish() |
62 | } |
63 | |
64 | #[allow (clippy::type_complexity)] |
65 | pub fn try_writeable_to_parts_for_test<W: TryWriteable>( |
66 | writeable: &W, |
67 | ) -> (String, Vec<(usize, usize, Part)>, Option<W::Error>) { |
68 | let mut writer: TestWriter = TestWriter { |
69 | string: alloc::string::String::new(), |
70 | parts: Vec::new(), |
71 | }; |
72 | #[allow (clippy::expect_used)] // for test code |
73 | let result: Result<(), ::Error> = writeable |
74 | .try_write_to_parts(&mut writer) |
75 | .expect(msg:"String writer infallible" ); |
76 | let (actual_str: String, actual_parts: Vec<(usize, usize, Part)>) = writer.finish(); |
77 | (actual_str, actual_parts, result.err()) |
78 | } |
79 | |