writeable/
testing.rs
1use crate::*;
6use alloc::string::String;
7use alloc::vec::Vec;
8
9pub(crate) struct TestWriter {
10 pub(crate) string: String,
11 pub(crate) parts: Vec<(usize, usize, Part)>,
12}
13
14impl TestWriter {
15 pub(crate) fn finish(mut self) -> (String, Vec<(usize, usize, Part)>) {
16 self.parts
18 .sort_unstable_by_key(|(begin, end, _)| (*begin, end.wrapping_neg()));
19 (self.string, self.parts)
20 }
21}
22
23impl 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
32impl 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#[allow(clippy::type_complexity)]
50pub fn writeable_to_parts_for_test<W: Writeable>(
51 writeable: &W,
52) -> (String, Vec<(usize, usize, Part)>) {
53 let mut writer = TestWriter {
54 string: alloc::string::String::new(),
55 parts: Vec::new(),
56 };
57 #[allow(clippy::expect_used)] writeable
59 .write_to_parts(&mut writer)
60 .expect("String writer infallible");
61 writer.finish()
62}
63
64#[allow(clippy::type_complexity)]
65pub 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 {
69 string: alloc::string::String::new(),
70 parts: Vec::new(),
71 };
72 #[allow(clippy::expect_used)] let result = writeable
74 .try_write_to_parts(&mut writer)
75 .expect("String writer infallible");
76 let (actual_str, actual_parts) = writer.finish();
77 (actual_str, actual_parts, result.err())
78}