Debian Codegraph @

debian/missing-sources/writeable/src/testing.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 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, end, _)| (*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 = self.string.len();
40 f(self)?;
41 let end = self.string.len();
42 if start < end {
43 self.parts.push((start, end, part));
44 }
45 Ok(())
46 }
47 }
48
49 pub fn writeable_to_parts_for_test<W: Writeable>(
50 writeable: &W,
51 ) -> (String, Vec<(usize, usize, Part)>) {
52 let mut writer = TestWriter {
53 string: alloc::string::String::new(),
54 parts: Vec::new(),
55 };
56 #[expect(clippy::expect_used)] // for test code
57 writeable
58 .write_to_parts(&mut writer)
59 .expect("String writer infallible");
60 writer.finish()
61 }
62
63 #[expect(clippy::type_complexity)]
64 pub fn try_writeable_to_parts_for_test<W: TryWriteable>(
65 writeable: &W,
66 ) -> (String, Vec<(usize, usize, Part)>, Option<W::Error>) {
67 let mut writer = TestWriter {
68 string: alloc::string::String::new(),
69 parts: Vec::new(),
70 };
71 #[expect(clippy::expect_used)] // for test code
72 let result = writeable
73 .try_write_to_parts(&mut writer)
74 .expect("String writer infallible");
75 let (actual_str, actual_parts) = writer.finish();
76 (actual_str, actual_parts, result.err())
77 }