oxvg_collections 0.0.5

Collections of data and utilities about SVG
Documentation
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
//! Collection for attributes when specified as a list
use std::ops::Deref;

#[cfg(feature = "parse")]
use oxvg_parse::{error::Error, Parse, Parser};
#[cfg(feature = "serialize")]
use oxvg_serialize::{error::PrinterError, Printer, ToValue};

#[derive(Clone, Debug, PartialEq, Eq)]
/// A `' '` delimiter
pub struct Space;
#[derive(Clone, Debug, PartialEq, Eq)]
/// A `','` delimiter
pub struct Comma;
#[derive(Clone, Debug, PartialEq, Eq)]
/// A `' '` or `','` delimiter
pub struct SpaceOrComma;
#[derive(Clone, Debug, PartialEq, Eq)]
/// A `';'` delimiter
pub struct Semicolon;

#[derive(Clone, Debug, PartialEq, Eq)]
/// A type of well-known delimiter
pub enum Separators {
    /// A `' '` delimiter
    Space,
    /// A `','` delimiter
    Comma,
    /// A `' '` or `','` delimiter
    SpaceOrComma,
    /// A `';'` delimiter
    Semicolon,
}
#[cfg(not(feature = "serialize"))]
trait SeparatorBound {}
#[cfg(feature = "serialize")]
trait SeparatorBound: ToValue {}
#[cfg(not(feature = "serialize"))]
impl<T> SeparatorBound for T {}
#[cfg(feature = "serialize")]
impl<T: ToValue> SeparatorBound for T {}
/// A trait for separators of [`ListOf`]
#[allow(private_bounds)]
pub trait Separator: Clone + SeparatorBound {
    #[cfg(feature = "parse")]
    /// Returns whether whitespace is intrinsic to this separator
    fn maybe_skip_whitespace(_input: &mut Parser<'_>) {}
    /// Constructs this separator
    fn new() -> Self;
    /// Returns an enumerable instance of separators
    fn id(&self) -> Separators;
    #[cfg(feature = "parse")]
    /// Parses the separator
    ///
    /// # Errors
    /// If the parser fails
    fn parse<'input>(input: &mut Parser<'input>) -> Result<(), Error<'input>> {
        input
            .expect_matches("delim", |char| Ok(Self::matches(char)))
            .map(|_| ())
    }
    /// Returns whether the character matches the separator
    fn matches(char: char) -> bool;
}
impl Separator for Space {
    fn id(&self) -> Separators {
        Separators::Space
    }
    fn new() -> Self {
        Self
    }
    fn matches(char: char) -> bool {
        char.is_whitespace()
    }
}
#[cfg(feature = "serialize")]
impl ToValue for Space {
    fn write_value<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
    where
        W: std::fmt::Write,
    {
        dest.write_char(' ')
    }
}
impl Separator for Comma {
    #[cfg(feature = "parse")]
    fn maybe_skip_whitespace(input: &mut Parser<'_>) {
        input.skip_whitespace();
    }
    fn new() -> Self {
        Self
    }
    fn id(&self) -> Separators {
        Separators::Comma
    }
    fn matches<'input>(char: char) -> bool {
        char == ','
    }
}
#[cfg(feature = "serialize")]
impl ToValue for Comma {
    fn write_value<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
    where
        W: std::fmt::Write,
    {
        dest.write_char(',')
    }
}
impl Separator for SpaceOrComma {
    fn id(&self) -> Separators {
        Separators::SpaceOrComma
    }
    fn new() -> Self {
        Self
    }
    #[cfg(feature = "parse")]
    fn parse<'input>(input: &mut Parser<'input>) -> Result<(), Error<'input>> {
        if input.try_parse(Parser::expect_whitespace).is_ok() {
            input.skip_whitespace();
            input.skip_char(',');
            input.skip_whitespace();
            return Ok(());
        }
        Comma::parse(input)?;
        input.skip_whitespace();
        Ok(())
    }
    fn matches<'input>(char: char) -> bool {
        char.is_whitespace() || char == ','
    }
}
#[cfg(feature = "serialize")]
impl ToValue for SpaceOrComma {
    fn write_value<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
    where
        W: std::fmt::Write,
    {
        dest.write_char(' ')
    }
}
impl Separator for Semicolon {
    #[cfg(feature = "parse")]
    fn maybe_skip_whitespace(input: &mut Parser<'_>) {
        input.skip_whitespace();
    }
    fn new() -> Self {
        Self
    }
    fn id(&self) -> Separators {
        Separators::Semicolon
    }
    fn matches<'input>(char: char) -> bool {
        char == ';'
    }
}
#[cfg(feature = "serialize")]
impl ToValue for Semicolon {
    fn write_value<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
    where
        W: std::fmt::Write,
    {
        dest.write_char(';')
    }
}
impl Separator for Separators {
    #[cfg(feature = "parse")]
    fn maybe_skip_whitespace(_input: &mut Parser<'_>) {
        unreachable!()
    }
    fn new() -> Self {
        unreachable!()
    }
    fn id(&self) -> Separators {
        self.clone()
    }
    #[cfg(feature = "parse")]
    fn parse<'input>(_input: &mut Parser<'input>) -> Result<(), Error<'input>> {
        unreachable!()
    }
    fn matches<'input>(_char: char) -> bool {
        unreachable!()
    }
}
#[cfg(feature = "serialize")]
impl ToValue for Separators {
    fn write_value<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
    where
        W: std::fmt::Write,
    {
        match self {
            Self::Space => Space.write_value(dest),
            Self::Comma => Comma.write_value(dest),
            Self::SpaceOrComma => SpaceOrComma.write_value(dest),
            Self::Semicolon => Semicolon.write_value(dest),
        }
    }
}

/// A list of values which are read or written with a specific delimiter
#[derive(Debug, PartialEq)]
pub struct ListOf<T: std::fmt::Debug + PartialEq, S: Separator> {
    /// A list of values separated by a separator
    pub list: Vec<T>,
    /// A delimiter that can be used between each item of the list
    pub separator: S,
}

impl<T: Clone + std::fmt::Debug + PartialEq, S: Separator> Clone for ListOf<T, S> {
    fn clone(&self) -> Self {
        Self {
            list: self.list.clone(),
            separator: self.separator.clone(),
        }
    }
}

impl<T: std::fmt::Debug + PartialEq, S: Separator> Deref for ListOf<T, S> {
    type Target = Vec<T>;

    fn deref(&self) -> &Self::Target {
        &self.list
    }
}

#[cfg(feature = "parse")]
impl<'input, T: Parse<'input> + std::fmt::Debug + PartialEq, S: Separator> Parse<'input>
    for ListOf<T, S>
{
    fn parse<'t>(input: &mut Parser<'input>) -> Result<Self, Error<'input>> {
        let mut start = Parser::new(input.take_matches(|char| !S::matches(char)));
        let mut list = match T::parse(&mut start) {
            Ok(first) if start.is_empty() => vec![first],
            Ok(_) => return Err(Error::ExpectedDone),
            Err(_) if start.is_empty() => {
                return Ok(Self {
                    list: vec![],
                    separator: S::new(),
                })
            }
            Err(e) => return Err(e),
        };
        loop {
            if S::parse(input).is_err() {
                break;
            }
            S::maybe_skip_whitespace(input);
            list.push(T::parse_string(
                input.take_matches(|char| !S::matches(char)),
            )?);
        }
        Ok(Self {
            list,
            separator: S::new(),
        })
    }
}
#[cfg(feature = "serialize")]
impl<T: ToValue + std::fmt::Debug + PartialEq, S: Separator> ListOf<Box<T>, S> {
    /// Serialize self into CSS or an attribute value
    ///
    /// # Errors
    /// If the printer fails.
    pub fn write_value<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
    where
        W: std::fmt::Write,
    {
        let mut iter = self.list.iter();
        if let Some(t) = iter.next() {
            t.write_value(dest)?;
        }
        for t in iter {
            self.separator.write_value(dest)?;
            t.write_value(dest)?;
        }
        Ok(())
    }
}
#[cfg(feature = "serialize")]
impl<T: ToValue + std::fmt::Debug + PartialEq, S: Separator> ToValue for ListOf<T, S> {
    fn write_value<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
    where
        W: std::fmt::Write,
    {
        let mut iter = self.list.iter();
        if let Some(t) = iter.next() {
            t.write_value(dest)?;
        }
        for t in iter {
            self.separator.write_value(dest)?;
            t.write_value(dest)?;
        }
        Ok(())
    }
}

impl<T: std::fmt::Debug + PartialEq, S: Separator> ListOf<T, S> {
    /// Returns self with a new list of items, as applied by the given function over each item
    pub fn map<'a, U: std::fmt::Debug + PartialEq, F>(&'a self, f: F) -> ListOf<U, S>
    where
        F: FnMut(&'a T) -> U,
    {
        ListOf {
            list: self.list.iter().map(f).collect(),
            separator: self.separator.clone(),
        }
    }

    /// Returns self with a new list of mutable items, as applied by the given function over each item
    pub fn map_mut<'a, U: std::fmt::Debug + PartialEq, F>(&'a mut self, f: F) -> ListOf<U, S>
    where
        F: FnMut(&'a mut T) -> U,
    {
        ListOf {
            list: self.list.iter_mut().map(f).collect(),
            separator: self.separator.clone(),
        }
    }

    /// Returns self with a new separator, as applied by the given function
    pub fn map_sep<U: Separator, F>(self, f: F) -> ListOf<T, U>
    where
        F: FnOnce(S) -> U,
    {
        ListOf {
            list: self.list,
            separator: f(self.separator),
        }
    }
}

#[test]
fn list_of() {
    assert_eq!(
        ListOf::<i64, Space>::parse_string(""),
        Ok(ListOf {
            list: vec![],
            separator: Space
        })
    );

    assert_eq!(
        ListOf::<i64, Comma>::parse_string(","),
        Err(Error::ExpectedDone)
    );
    assert_eq!(
        ListOf::<i64, Comma>::parse_string("1,"),
        Err(Error::InvalidNumber)
    );
}

#[test]
fn list_of_space() {
    assert_eq!(
        ListOf::<i64, Space>::parse_string("1 2 3"),
        Ok(ListOf {
            list: vec![1, 2, 3],
            separator: Space
        })
    );

    assert_eq!(
        ListOf::<i64, Space>::parse_string("invalid"),
        Err(Error::InvalidNumber)
    );
    assert_eq!(
        ListOf::<i64, Space>::parse_string("1, 2, 3"),
        Err(Error::ExpectedDone)
    );
}

#[test]
fn list_of_space_or_comma() {
    use crate::attribute::core::{Length, Percentage};
    assert_eq!(
        ListOf::<i64, SpaceOrComma>::parse_string("1, 2, 3"),
        Ok(ListOf {
            list: vec![1, 2, 3],
            separator: SpaceOrComma
        })
    );
    assert_eq!(
        ListOf::<i64, SpaceOrComma>::parse_string("1,2,3"),
        Ok(ListOf {
            list: vec![1, 2, 3],
            separator: SpaceOrComma
        })
    );
    assert_eq!(
        ListOf::<Length, SpaceOrComma>::parse_string("23.2350 20.2268px 0.22356em 80.0005%"),
        Ok(ListOf {
            list: vec![
                Length::Length(lightningcss::values::length::LengthValue::Px(23.235)),
                Length::Length(lightningcss::values::length::LengthValue::Px(20.2268)),
                Length::Length(lightningcss::values::length::LengthValue::Em(0.22356)),
                Length::Percentage(Percentage(0.800_005))
            ],
            separator: SpaceOrComma
        })
    );

    assert_eq!(
        ListOf::<i64, SpaceOrComma>::parse_string("1; 2; 3"),
        Err(Error::ExpectedDone)
    );
}

#[test]
fn list_of_semicolon() {
    use crate::attribute::{
        animation::BeginEnd,
        animation_timing::{ClockValue, Metric},
        core::NumberOptionalNumber,
    };
    assert_eq!(
        ListOf::<NumberOptionalNumber, Semicolon>::parse_string("1, 2; 3"),
        Ok(ListOf {
            list: vec![
                NumberOptionalNumber(1.0, Some(2.0)),
                NumberOptionalNumber(3.0, None)
            ],
            separator: Semicolon
        })
    );
    assert_eq!(
        ListOf::<i64, Semicolon>::parse_string("1;2;3"),
        Ok(ListOf {
            list: vec![1, 2, 3],
            separator: Semicolon
        })
    );
    assert_eq!(
        ListOf::<BeginEnd, Semicolon>::parse_string("0;thing2.end"),
        Ok(ListOf {
            list: vec![
                BeginEnd::OffsetValue(ClockValue::TimecountValue {
                    timecount: 0.0,
                    metric: Metric::Second
                }),
                BeginEnd::SyncbaseValue {
                    id: "thing2".into(),
                    begin: false,
                    offset: None
                }
            ],
            separator: Semicolon
        })
    );

    assert_eq!(
        ListOf::<i64, Semicolon>::parse_string("1,2,3"),
        Err(Error::ExpectedDone)
    );
}