logparse_pretty_print/render/
write_fmt.rs1use crate::{Render, RenderAnnotated, Text, render::Annotation};
2use alloc::rc::Rc;
3use color_ansi::AnsiStyle;
4use core::fmt::{Debug, Error, Formatter};
5
6pub struct FmtWrite<W> {
8 upstream: W,
9}
10#[derive(Debug)]
12pub struct BufferWrite<T> {
13 buffer: Vec<T>,
14 annotations: Vec<(usize, Annotation<AnsiStyle>)>,
15}
16
17impl<'a, T: Text<'a>> BufferWrite<T> {
18 pub fn new(capacity: usize) -> Self {
20 BufferWrite { buffer: Vec::with_capacity(capacity), annotations: Vec::new() }
21 }
22 pub fn render<W>(&mut self, render: &mut W) -> Result<(), W::Error>
24 where
25 W: RenderAnnotated<'a, T>,
26 W: ?Sized,
27 {
28 let mut start = 0;
29 for (end, annotation) in &self.annotations {
30 let s = &self.buffer[start..*end];
31 if !s.is_empty() {
32 render.write_all(s)?;
33 }
34 start = *end;
35 match annotation {
36 Annotation::Push(a) => render.push_annotation(a.clone())?,
37 Annotation::Pop => render.pop_annotation()?,
38 }
39 }
40 let s = &self.buffer[start..];
41 if !s.is_empty() {
42 render.write_all(s)?;
43 }
44 Ok(())
45 }
46}
47
48impl<'a, T: Clone> Render<'a, T> for BufferWrite<T> {
49 type Error = Error;
50
51 fn write_all(&mut self, s: &[T]) -> Result<(), Self::Error> {
52 self.buffer.extend(s.iter().cloned());
53 Ok(())
54 }
55
56 fn fail_doc(&self) -> Self::Error {
57 Error
58 }
59}
60
61impl<'a, W, T: Text<'a>> RenderAnnotated<'a, T> for FmtWrite<W>
62where
63 W: core::fmt::Write,
64{
65 fn push_annotation(&mut self, _: Rc<AnsiStyle>) -> Result<(), Self::Error> {
66 Ok(())
67 }
68
69 fn pop_annotation(&mut self) -> Result<(), Self::Error> {
70 Ok(())
71 }
72}
73
74impl<'a, T: Clone> RenderAnnotated<'a, T> for BufferWrite<T> {
75 fn push_annotation(&mut self, annotation: Rc<AnsiStyle>) -> Result<(), Self::Error> {
76 self.annotations.push((self.buffer.len(), Annotation::Push(annotation)));
77 Ok(())
78 }
79
80 fn pop_annotation(&mut self) -> Result<(), Self::Error> {
81 self.annotations.push((self.buffer.len(), Annotation::Pop));
82 Ok(())
83 }
84}
85
86impl<W> Debug for FmtWrite<W> {
87 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
88 f.debug_struct("IoWrite").finish()
89 }
90}
91
92impl<W> FmtWrite<W> {
93 pub fn new(upstream: W) -> FmtWrite<W> {
95 FmtWrite { upstream }
96 }
97}
98
99impl<'a, W, T: Text<'a>> Render<'a, T> for FmtWrite<W>
100where
101 W: core::fmt::Write,
102{
103 type Error = Error;
104
105 fn write_all(&mut self, s: &[T]) -> core::fmt::Result {
106 for i in s {
107 self.upstream.write_str(i.as_str().as_ref())?
108 }
109 Ok(())
110 }
111
112 fn fail_doc(&self) -> Self::Error {
113 Error
114 }
115}