1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
//! This crate provides primitives to build up a html/xml/svg document programatically.
//! Instead of using a templating engine, write data/markup that 'looks like' rust.
//!
//! ### Why so many closures?
//!
//! Unlike Drop, passing closures can be used to force the user to handle errors when
//! something goes out of scope. If we put the writing of end tags in a Drop method
//! it could silently fail, which is not ideal. This can be worked around by adding
//! an explicit function to write the end tag, but there is no way to guarantee
//! that this function gets called at compile time. The best you can do is a runtime
//! panic if the finalizer function isn't called in order to handle the error case.
//! With closures, you can force a compile-time error.
//!
//! ### Examples
//!
//! See it in use in the [poloto crate](https://crates.io/crates/poloto).
//! Also check out the examples at [github](https://github.com/tiby312/tagger/tree/master/examples).
//!
//!

pub mod svg;
use svg::*;

/// Convenience macro to reduce code.
/// Shorthand for 'move |w|write!(w,...)`
/// Create a closure that will use write!() with the formatting arguments.
#[macro_export]
macro_rules! wr {
    ($($arg:tt)*) => {
        move |w|write!(w,$($arg)*)
    }
}

/// [`fmt::Write::write_fmt`] doesn't return itself on success. This version does.
pub fn write_fmt_ret<'a, T: fmt::Write>(
    w: &'a mut T,
    args: fmt::Arguments,
) -> Result<&'a mut T, fmt::Error> {
    w.write_fmt(args)?;
    Ok(w)
}

/// Just like the regular [`write!()`] macro except it returns itself upon success.
#[macro_export]
macro_rules! write_ret {
    ($dst:expr, $($arg:tt)*) => ($crate::write_fmt_ret($dst,format_args!($($arg)*)))
}

///The prelude to import the element manipulation convenience macros.
pub mod prelude {
    pub use super::wr;
    pub use super::write_ret;
    pub use super::WriteAttr;
    pub use core::fmt::Write;
}

use core::fmt;

use fmt::Write;

///Used by [`upgrade`]
pub struct WriterAdaptor<T> {
    pub inner: T,
    pub error: Result<(), std::io::Error>,
}

///Upgrade a [`std::io::Write`] to be a [`std::fmt::Write`]
pub fn upgrade<T: std::io::Write>(inner: T) -> WriterAdaptor<T> {
    WriterAdaptor {
        inner,
        error: Ok(()),
    }
}

impl<T: std::io::Write> fmt::Write for WriterAdaptor<T> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        match self.inner.write_all(s.as_bytes()) {
            Ok(()) => Ok(()),
            Err(e) => {
                self.error = Err(e);
                Err(fmt::Error)
            }
        }
    }
}

///Common tags to be used in [`Element::single_ext`]
pub mod tag_types {
    /// Equivalent to `<{}/>`
    pub static NORMAL: [&str; 2] = ["<", "/>"];
    /// Equivalent to `<!--{}-->`
    pub static COMMENT: [&str; 2] = ["<!--", "-->"];
    /// Equivalent to `<?{}?>`
    pub static PROLOG: [&str; 2] = ["<?", "?>"];
    /// Equivalent to `<!{}>`
    pub static DECL: [&str; 2] = ["<!", ">"];
}

/// Used by [`Element::elem`]
pub struct ElementHeaderWriter<'a, T>(&'a mut Element<T>);

impl<'a, T: Write> ElementHeaderWriter<'a, T> {
    /// Write out the attributes for an element with an ending tag.
    pub fn write<F>(self, func: F) -> Result<&'a mut Element<T>, fmt::Error>
    where
        for<'x, 'y> F: FnOnce(
            &'x mut AttributeWriter<'y, T>,
        ) -> Result<&'x mut AttributeWriter<'y, T>, fmt::Error>,
    {
        let _res = func(&mut AttributeWriter { inner: self.0 });

        write!(self.0, ">")?;
        Ok(self.0)
    }
}

/// Functions the user can call to add attributes.
/// [`AttributeWriter`] could have implemented these, but lets use a trait to simplify lifetimes.
pub trait WriteAttr: Write + Sized {
    ///Write the data attribute for a svg polyline or polygon.
    fn points_data<F>(&mut self, func: F) -> Result<&mut Self, fmt::Error>
    where
        for<'x, 'y> F: FnOnce(
            &'x mut PointsBuilder<'y, Self>,
        ) -> Result<&'x mut PointsBuilder<'y, Self>, fmt::Error>,
    {
        {
            let mut p = PointsBuilder::new(self)?;
            func(&mut p)?;
            p.finish()?;
        }
        Ok(self)
    }

    ///Write the data attribute for a svg path.
    fn path_data<F>(&mut self, func: F) -> Result<&mut Self, fmt::Error>
    where
        for<'x, 'y> F: FnOnce(
            &'x mut PathBuilder<'y, Self>,
        ) -> Result<&'x mut PathBuilder<'y, Self>, fmt::Error>,
    {
        {
            let mut p = PathBuilder::new(self)?;
            func(&mut p)?;
            p.finish()?;
        }
        Ok(self)
    }

    ///Write an attribute where the user can write the value part using [`wr`] macro or the [`write`] macro
    fn with_attr(
        &mut self,
        s: &str,
        func: impl FnOnce(&mut Self) -> core::fmt::Result,
    ) -> Result<&mut Self, core::fmt::Error> {
        write!(self, " {}=", s)?;
        write!(self, "\"")?;
        func(self)?;
        write!(self, "\"")?;
        Ok(self)
    }

    ///Write an attribute with the specified tag and value using the values [`fmt::Display`] trait.
    fn attr(
        &mut self,
        s: &str,
        val: impl core::fmt::Display,
    ) -> Result<&mut Self, core::fmt::Error> {
        write!(self, " {}=\"{}\"", s, val)?;
        Ok(self)
    }
}

///Builder to write out attributes to an element.
pub struct AttributeWriter<'a, T> {
    inner: &'a mut Element<T>,
}

impl<'a, T: fmt::Write> fmt::Write for AttributeWriter<'a, T> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.inner.write_str(s)
    }
}
impl<'a, T: fmt::Write> WriteAttr for AttributeWriter<'a, T> {}

///An element.
pub struct Element<T> {
    writer: T,
}

impl<T: fmt::Write> fmt::Write for Element<T> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.writer.write_str(s)
    }
}

impl<T: fmt::Write> Element<T> {
    /// Create a new element.
    pub fn new(writer: T) -> Self {
        Element { writer }
    }

    /// Write a element that doesnt have an ending tag. i.e. it can only have attributes.
    /// Some common tag types are in [`tag_types`].
    pub fn single_ext<F>(
        &mut self,
        tag: &str,
        tags: [&str; 2],
        func: F,
    ) -> Result<&mut Self, fmt::Error>
    where
        for<'x, 'y> F: FnOnce(
            &'x mut AttributeWriter<'y, T>,
        ) -> Result<&'x mut AttributeWriter<'y, T>, fmt::Error>,
    {
        let [start, end] = tags;
        write!(self.writer, "{}{}", start, tag)?;
        func(&mut AttributeWriter { inner: self })?;
        write!(self.writer, "{}", end)?;
        Ok(self)
    }

    /// Shorthand for [`Element::single_ext`] with [`tag_types::NORMAL`]
    pub fn single<F>(&mut self, tag: &str, func: F) -> Result<&mut Self, fmt::Error>
    where
        for<'x, 'y> F: FnOnce(
            &'x mut AttributeWriter<'y, T>,
        ) -> Result<&'x mut AttributeWriter<'y, T>, fmt::Error>,
    {
        self.single_ext(tag, ["<", "/>"], func)?;
        Ok(self)
    }

    /// Shorthand for [`Element::elem`] with the attribute builder functionality omitted.
    pub fn elem_no_attr<F>(&mut self, tag: &str, func: F) -> Result<&mut Self, fmt::Error>
    where
        for<'x> F: FnOnce(&'x mut Element<T>) -> Result<&'x mut Element<T>, fmt::Error>,
    {
        write!(self.writer, "<{}>", tag)?;
        let _ = func(self)?;
        write!(self.writer, "</{}>", tag)?;
        Ok(self)
    }

    /// Write a element that has an ending tag.
    /// The user is required to feed the element back into this function
    /// thus proving that they called [`ElementHeaderWriter::write`].
    pub fn elem<F>(&mut self, tag: &str, func: F) -> Result<&mut Self, fmt::Error>
    where
        F: FnOnce(ElementHeaderWriter<T>) -> Result<&mut Element<T>, fmt::Error>,
    {
        write!(self.writer, "<{}", tag)?;
        let attr = ElementHeaderWriter(self);

        let _cert = func(attr)?;

        write!(self.writer, "</{}>", tag)?;
        Ok(self)
    }
}