Skip to main content

css_parse/
cursor_to_source_cursor_sink.rs

1use crate::{Cursor, CursorSink, SourceCursor, SourceCursorSink};
2use allocator_api2::alloc::Allocator;
3use std::fmt::Write;
4
5pub struct CursorToSourceCursorSink<'a, T: SourceCursorSink<'a>> {
6	source: &'a str,
7	sink: T,
8}
9
10impl<'a, T: SourceCursorSink<'a>> CursorToSourceCursorSink<'a, T> {
11	pub fn new(source: &'a str, sink: T) -> Self {
12		Self { source, sink }
13	}
14}
15
16impl<'a, T: SourceCursorSink<'a>> CursorSink for CursorToSourceCursorSink<'a, T> {
17	fn append(&mut self, cursor: Cursor) {
18		self.sink.append(SourceCursor::from(cursor, cursor.str_slice(self.source)))
19	}
20}
21
22impl<'a> SourceCursorSink<'a> for String {
23	fn append(&mut self, c: SourceCursor<'a>) {
24		let _ = write!(self, "{c}");
25	}
26}
27
28impl<'a, 'alloc, A: Allocator> SourceCursorSink<'a> for crate::String<'alloc, A> {
29	fn append(&mut self, c: SourceCursor<'a>) {
30		let _ = write!(self, "{c}");
31	}
32}
33
34impl<'a, T: SourceCursorSink<'a>> SourceCursorSink<'a> for &mut T {
35	fn append(&mut self, c: SourceCursor<'a>) {
36		(**self).append(c)
37	}
38}
39
40#[cfg(test)]
41mod test {
42	use super::*;
43	use crate::Arena;
44	use crate::{ComponentValues, EmptyAtomSet, Parser, ToCursors};
45	use css_lexer::Lexer;
46
47	#[test]
48	fn test_source_cursor_sink_for_string() {
49		let source_text = "black white";
50		let alloc = Arena::default();
51		let mut str = String::new();
52		let mut transform = CursorToSourceCursorSink::new(source_text, &mut str);
53		let lexer = Lexer::new(&EmptyAtomSet::ATOMS, source_text);
54		let mut parser = Parser::new(&alloc, source_text, lexer);
55		parser.parse_entirely::<ComponentValues>().output.unwrap().to_cursors(&mut transform);
56		assert_eq!(str, "black white");
57	}
58
59	#[test]
60	fn test_source_cursor_sink_for_arena_string() {
61		let source_text = "black white";
62		let alloc = crate::Arena::default();
63		let mut str = crate::String::new_in(&alloc);
64		{
65			let mut transform = CursorToSourceCursorSink::new(source_text, &mut str);
66			let lexer = Lexer::new(&EmptyAtomSet::ATOMS, source_text);
67			let mut parser = Parser::new(&alloc, source_text, lexer);
68			parser.parse_entirely::<ComponentValues>().output.unwrap().to_cursors(&mut transform);
69		}
70		assert_eq!(str, "black white");
71	}
72}