| 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 |
#[doc(hidden)] |
| 50 |
pub 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 |
#[expect(clippy::expect_used)] // for test code |
| 58 |
writeable |
| 59 |
.write_to_parts(&mut writer) |
| 60 |
.expect("String writer infallible"); |
| 61 |
writer.finish() |
| 62 |
} |
| 63 |
|
| 64 |
#[expect(clippy::type_complexity)] |
| 65 |
#[doc(hidden)] |
| 66 |
pub fn try_writeable_to_parts_for_test<W: TryWriteable>( |
| 67 |
writeable: &W, |
| 68 |
) -> (String, Vec<(usize, usize, Part)>, Option<W::Error>) { |
| 69 |
let mut writer = TestWriter { |
| 70 |
string: alloc::string::String::new(), |
| 71 |
parts: Vec::new(), |
| 72 |
}; |
| 73 |
#[expect(clippy::expect_used)] // for test code |
| 74 |
let result = writeable |
| 75 |
.try_write_to_parts(&mut writer) |
| 76 |
.expect("String writer infallible"); |
| 77 |
let (actual_str, actual_parts) = writer.finish(); |
| 78 |
(actual_str, actual_parts, result.err()) |
| 79 |
} |