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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use std::fmt::Write;

use super::*;

impl<A: fmt::Display, B: fmt::Display> Attr for (A, B) {
    fn render(self, w: &mut AttrWrite) -> std::fmt::Result {
        let (first, second) = self;
        write!(w.writer(), " {}", first)?;
        w.writer_escapable().write_str("=\"")?;
        write!(w.writer(), "{}", second)?;
        w.writer_escapable().write_str("\"")
    }
}

#[derive(Copy, Clone)]
#[must_use]
pub struct AttrClosure<I> {
    func: I,
}
impl<F: FnOnce(&mut AttrWrite) -> fmt::Result> Attr for AttrClosure<F> {
    fn render(self, w: &mut AttrWrite) -> fmt::Result {
        (self.func)(w)
    }
}
pub fn attr_from_closure<F: FnOnce(&mut AttrWrite) -> fmt::Result>(func: F) -> AttrClosure<F> {
    AttrClosure { func }
}

pub fn raw_escapable<D: fmt::Display>(data: D) -> RawEscapable<D> {
    RawEscapable { data }
}

pub fn from_iter<I: Iterator<Item = R>, R: Elem>(iter: I) -> Iter<I> {
    Iter { iter }
}

#[derive(Copy, Clone)]
#[must_use]
pub struct Closure<I> {
    func: I,
}
pub fn from_closure<F: FnOnce(&mut ElemWrite) -> fmt::Result>(func: F) -> Closure<F> {
    Closure { func }
}
impl<I: FnOnce(&mut ElemWrite) -> fmt::Result> SafeElem for Closure<I> {}

impl<I: FnOnce(&mut ElemWrite) -> fmt::Result> Elem for Closure<I> {
    type Tail = ();
    fn render_head(self, w: &mut ElemWrite) -> Result<Self::Tail, fmt::Error> {
        (self.func)(w)?;
        Ok(())
    }
}

#[derive(Copy, Clone)]
#[must_use]
pub struct Iter<I> {
    iter: I,
}
impl<I: IntoIterator<Item = R>, R: SafeElem> SafeElem for Iter<I> {}

impl<I: IntoIterator<Item = R>, R: Elem> Elem for Iter<I> {
    type Tail = ();
    fn render_head(self, w: &mut ElemWrite) -> Result<Self::Tail, fmt::Error> {
        for i in self.iter {
            w.render_inner(i)?;
        }
        Ok(())
    }
}

#[derive(Copy, Clone)]
#[must_use]
pub struct RawEscapable<D> {
    data: D,
}

impl<D: fmt::Display> Elem for RawEscapable<D> {
    type Tail = ();
    fn render_head(self, w: &mut ElemWrite) -> Result<Self::Tail, fmt::Error> {
        write!(w.writer_escapable(), " {}", self.data)?;
        Ok(())
    }
}

#[derive(Copy, Clone)]
#[must_use]
pub struct Single<D, A, K, Z> {
    tag: D,
    attr: A,
    start: K,
    ending: Z,
}
impl<D: fmt::Display, A: Attr, K: fmt::Display, Z: fmt::Display> SafeElem for Single<D, A, K, Z> {}
impl<D: fmt::Display, A: Attr, K, Z> Single<D, A, K, Z> {
    pub fn with<AA: Attr>(self, attr: AA) -> Single<D, AA, K, Z> {
        Single {
            tag: self.tag,
            attr,
            ending: self.ending,
            start: self.start,
        }
    }
    pub fn with_ending<ZZ: fmt::Display>(self, ending: ZZ) -> Single<D, A, K, ZZ> {
        Single {
            tag: self.tag,
            attr: self.attr,
            ending,
            start: self.start,
        }
    }
    pub fn with_start<KK: fmt::Display>(self, start: KK) -> Single<D, A, KK, Z> {
        Single {
            tag: self.tag,
            attr: self.attr,
            ending: self.ending,
            start,
        }
    }
}
impl<D: fmt::Display, A: Attr, K: fmt::Display, Z: fmt::Display> Elem for Single<D, A, K, Z> {
    type Tail = ();
    fn render_head(self, w: &mut ElemWrite) -> Result<Self::Tail, fmt::Error> {
        let Single {
            tag,
            attr,
            start,
            ending,
        } = self;
        w.writer_escapable().write_char('<')?;
        write!(w.writer(), "{}{}", start, tag)?;
        w.writer().write_char(' ')?;
        attr.render(&mut w.as_attr_write())?;
        write!(w.writer(), " {}", ending)?;
        w.writer_escapable().write_str(">")?;
        Ok(())
    }
}

pub fn single<D: fmt::Display>(tag: D) -> Single<D, (), &'static str, &'static str> {
    Single {
        tag,
        attr: (),
        start: "",
        ending: "/",
    }
}

pub fn elem<D: fmt::Display>(tag: D) -> Element<D, ()> {
    Element { tag, attr: () }
}

#[derive(Copy, Clone)]
#[must_use]
pub struct ElemTail<D> {
    tag: D,
}

impl<D: fmt::Display> RenderTail for ElemTail<D> {
    fn render(self, w: &mut ElemWrite) -> std::fmt::Result {
        w.writer_escapable().write_str("</")?;
        write!(w.writer(), "{}", &self.tag)?;
        w.writer_escapable().write_char('>')
    }
}

#[derive(Copy, Clone)]
#[must_use]
pub struct Element<D, A> {
    tag: D,
    attr: A,
}

impl<D: fmt::Display, A: Attr> SafeElem for Element<D, A> {}

impl<D: fmt::Display, A: Attr> Element<D, A> {
    pub fn with<AA: Attr>(self, attr: AA) -> Element<D, AA> {
        Element {
            tag: self.tag,
            attr,
        }
    }
}
impl<D: fmt::Display, A: Attr> Elem for Element<D, A> {
    type Tail = ElemTail<D>;
    fn render_head(self, w: &mut ElemWrite) -> Result<Self::Tail, fmt::Error> {
        let Element { tag, attr } = self;

        w.writer_escapable().write_char('<')?;
        write!(w.writer(), "{}", tag)?;
        w.writer().write_char(' ')?;
        attr.render(&mut w.as_attr_write())?;
        w.writer_escapable().write_str(" >")?;

        Ok(ElemTail { tag })
    }
}

#[derive(Copy, Clone)]
#[must_use]
pub struct Path<I> {
    iter: I,
}

impl<I: IntoIterator<Item = PathCommand<D>>, D: fmt::Display> Attr for Path<I> {
    fn render(self, w: &mut AttrWrite) -> std::fmt::Result {
        w.writer_escapable().write_str(" d=\"")?;

        for command in self.iter {
            command.write(w.writer())?;
        }
        w.writer_escapable().write_str("\"")
    }
}

pub mod sink {
    use super::*;
    pub struct PathSink<'a, 'b> {
        writer: &'a mut AttrWrite<'b>,
    }

    pub struct PathSink2<'a, 'b, T> {
        writer: &'a mut AttrWrite<'b>,
        _p: std::marker::PhantomData<T>,
    }
    impl<T: fmt::Display> PathSink2<'_, '_, T> {
        pub fn put(&mut self, command: PathCommand<T>) -> fmt::Result {
            command.write(self.writer.writer())
        }
    }
    impl<'a, 'b> PathSink<'a, 'b> {
        pub fn start<T>(self) -> PathSink2<'a, 'b, T> {
            PathSink2 {
                writer: self.writer,
                _p: std::marker::PhantomData,
            }
        }
    }

    pub struct PathFlexible<F> {
        func: F,
    }
    impl<F: FnOnce(PathSink) -> fmt::Result> Attr for PathFlexible<F> {
        fn render(self, w: &mut AttrWrite) -> fmt::Result {
            w.writer_escapable().write_str(" d=\"")?;
            (self.func)(PathSink { writer: w })?;
            w.writer_escapable().write_str("\"")
        }
    }

    pub fn path_ext<F: FnOnce(PathSink) -> fmt::Result>(func: F) -> PathFlexible<F> {
        sink::PathFlexible { func }
    }
    #[test]
    fn test() {
        use PathCommand::*;
        path_ext(|s| {
            let mut s = s.start();
            s.put(M(0, 0))?;
            s.put(L(0, 0))?;
            s.put(Z())?;
            Ok(())
        });
    }
}

pub fn path<I: IntoIterator<Item = PathCommand<D>>, D: fmt::Display>(iter: I) -> Path<I> {
    Path { iter }
}

#[derive(Copy, Clone)]
#[must_use]
pub struct Points<I> {
    iter: I,
}

pub fn points<I: IntoIterator<Item = (D, D)>, D: fmt::Display>(iter: I) -> Points<I> {
    Points { iter }
}

impl<I: IntoIterator<Item = (D, D)>, D: fmt::Display> Attr for Points<I> {
    fn render(self, w: &mut AttrWrite) -> std::fmt::Result {
        w.writer_escapable().write_str(" points=\"")?;
        for (x, y) in self.iter {
            write!(w.writer(), "{},{} ", x, y)?;
        }
        w.writer_escapable().write_str("\"")
    }
}

///
/// Construct and Write a SVG path's data.
///
/// following: [w3 spec](https://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation)
///

#[derive(Copy, Clone)]
#[must_use]
pub enum PathCommand<F> {
    /// move to
    M(F, F),
    /// relative move to
    M_(F, F),
    /// line to
    L(F, F),
    /// relative line to
    L_(F, F),
    /// horizontal to
    H(F),
    /// relative horizontal to
    H_(F),
    /// vertical to
    V(F),
    /// relative vertical to
    V_(F),
    /// curve to
    C(F, F, F, F, F, F),
    /// relative curve to
    C_(F, F, F, F, F, F),
    /// shorthand curve to
    S(F, F, F, F),
    /// relative shorthand curve to
    S_(F, F, F, F),
    /// quadratic bezier curve to
    Q(F, F, F, F),
    /// relative quadratic bezier curve to
    Q_(F, F, F, F),
    /// shorthand quadratic bezier curve to
    T(F, F),
    /// relative shorthand quadratic bezier curve to
    T_(F, F),
    /// elliptical arc
    A(F, F, F, F, F, F, F),
    /// relative elliptical arc
    A_(F, F, F, F, F, F, F),
    /// close path
    Z(),
}

impl<F> PathCommand<F> {
    #[inline(always)]
    fn write<T: fmt::Write>(&self, mut writer: T) -> fmt::Result
    where
        F: fmt::Display,
    {
        use PathCommand::*;
        match self {
            M(x, y) => {
                write!(writer, " M {} {}", x, y)
            }
            M_(x, y) => {
                write!(writer, " m {} {}", x, y)
            }
            L(x, y) => {
                write!(writer, " L {} {}", x, y)
            }
            L_(x, y) => {
                write!(writer, " l {} {}", x, y)
            }
            H(a) => {
                write!(writer, " H {}", a)
            }
            H_(a) => {
                write!(writer, " h {}", a)
            }
            V(a) => {
                write!(writer, " V {}", a)
            }
            V_(a) => {
                write!(writer, " v {}", a)
            }
            C(x1, y1, x2, y2, x, y) => {
                write!(writer, " C {} {}, {} {}, {} {}", x1, y1, x2, y2, x, y)
            }
            C_(dx1, dy1, dx2, dy2, dx, dy) => {
                write!(writer, " c {} {}, {} {}, {} {}", dx1, dy1, dx2, dy2, dx, dy)
            }
            S(x2, y2, x, y) => {
                write!(writer, " S {},{} {} {}", x2, y2, x, y)
            }
            S_(x2, y2, x, y) => {
                write!(writer, " s {},{} {} {}", x2, y2, x, y)
            }
            Q(x1, y1, x, y) => {
                write!(writer, " Q {} {}, {} {}", x1, y1, x, y)
            }
            Q_(dx1, dy1, dx, dy) => {
                write!(writer, " q {} {}, {} {}", dx1, dy1, dx, dy)
            }
            T(x, y) => {
                write!(writer, " T {} {}", x, y)
            }
            T_(x, y) => {
                write!(writer, " t {} {}", x, y)
            }
            A(rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, x, y) => {
                write!(
                    writer,
                    " A {} {} {} {} {} {} {}",
                    rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, x, y
                )
            }
            A_(rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, dx, dy) => {
                write!(
                    writer,
                    " a {} {} {} {} {} {} {}",
                    rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, dx, dy
                )
            }
            Z() => {
                write!(writer, " Z")
            }
        }
    }
}

///
/// If you need to render something over, and over again,
/// you can instead buffer it to a string using this struct
/// for better performance at the cost of more memory.
///
/// Notice that RenderElem is only implemented for a &BufferedElem.
///
pub struct BufferedElem {
    head: String,
    tail: String,
}

impl BufferedElem {
    pub fn new<E: SafeElem>(elem: E) -> Result<Self, fmt::Error> {
        let mut head = String::new();
        let mut tail = String::new();
        let t = elem.render_head(&mut ElemWrite::new(&mut head))?;
        t.render(&mut ElemWrite::new(&mut tail))?;
        head.shrink_to_fit();
        tail.shrink_to_fit();
        Ok(BufferedElem { head, tail })
    }

    pub fn into_parts(self) -> (String, String) {
        (self.head, self.tail)
    }
}

pub struct BufferedTail<'a> {
    tail: &'a str,
}
impl<'a> RenderTail for BufferedTail<'a> {
    fn render(self, w: &mut ElemWrite) -> std::fmt::Result {
        write!(w.writer_escapable(), "{}", self.tail)
    }
}
impl<'a> SafeElem for &'a BufferedElem {}

impl<'a> Elem for &'a BufferedElem {
    type Tail = BufferedTail<'a>;
    fn render_head(self, w: &mut ElemWrite) -> Result<Self::Tail, fmt::Error> {
        write!(w.writer_escapable(), "{}", self.head)?;
        Ok(BufferedTail { tail: &self.tail })
    }
}

// pub struct DisplayEscapable<D, B> {
//     start: D,
//     end: B,
// }
// pub struct DisplayEscapableTail<'a, D> {
//     end: &'a D,
// }
// impl<A: fmt::Display, B: fmt::Display> DisplayEscapable<A, B> {
//     pub fn new(head: A, tail: B) -> Self {
//         DisplayEscapable {
//             start: head,
//             end: tail,
//         }
//     }
// }
// impl<'b, D: fmt::Display> RenderTail for DisplayEscapableTail<'b, D> {
//     fn render(self, w: &mut ElemWrite) -> std::fmt::Result {
//         write!(w.writer_escapable(), "{}", self.end)
//     }
// }
// impl<'a, A: fmt::Display, B: fmt::Display> Elem for &'a DisplayEscapable<A, B> {
//     type Tail = DisplayEscapableTail<'a, B>;
//     fn render_head(self, w: &mut ElemWrite) -> Result<Self::Tail, fmt::Error> {
//         write!(w.writer_escapable(), "{}", self.start)?;
//         Ok(DisplayEscapableTail { end: &self.end })
//     }
// }