parlance 0.1.0

Fundamental text property types
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
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
490
491
492
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! CSS font-family parsing and representation.

extern crate alloc;

use alloc::borrow::Cow;
use alloc::vec::Vec;
use core::fmt;

use crate::GenericFamily;

/// Kinds of errors that can occur when parsing CSS `font-family` strings.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseFontFamilyErrorKind {
    /// The source string does not conform to the supported syntax.
    InvalidSyntax,
    /// A quoted family name was missing a closing quote.
    UnterminatedString,
}

/// Error returned when parsing CSS `font-family` strings.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ParseFontFamilyError {
    kind: ParseFontFamilyErrorKind,
    at: usize,
    span: Option<(usize, usize)>,
}

impl ParseFontFamilyError {
    const fn new(kind: ParseFontFamilyErrorKind, at: usize) -> Self {
        Self {
            kind,
            at,
            span: None,
        }
    }

    const fn with_span(mut self, span: (usize, usize)) -> Self {
        self.span = Some(span);
        self
    }

    /// Returns the error kind.
    pub const fn kind(self) -> ParseFontFamilyErrorKind {
        self.kind
    }

    /// Returns the byte offset into the source where the error was detected.
    pub const fn byte_offset(self) -> usize {
        self.at
    }

    /// Returns the byte span (start, end) for the token associated with this error, if available.
    pub const fn byte_span(self) -> Option<(usize, usize)> {
        self.span
    }
}

impl fmt::Display for ParseFontFamilyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let msg = match self.kind {
            ParseFontFamilyErrorKind::InvalidSyntax => "invalid font-family syntax",
            ParseFontFamilyErrorKind::UnterminatedString => "unterminated string in font-family",
        };
        write!(f, "{msg} at byte {}", self.at)
    }
}

impl core::error::Error for ParseFontFamilyError {}

/// A single named or generic font family.
///
/// This corresponds to one entry in a CSS `font-family` list.
///
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-family>
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum FontFamilyName<'a> {
    /// A named font family.
    Named(Cow<'a, str>),
    /// A generic font family.
    Generic(GenericFamily),
}

impl<'a> FontFamilyName<'a> {
    /// Creates a named font family from a borrowed string.
    pub const fn named(name: &'a str) -> Self {
        Self::Named(Cow::Borrowed(name))
    }

    /// Parses a font family containing a name or a generic family.
    ///
    /// # Example
    /// ```
    /// # extern crate alloc;
    /// use alloc::borrow::Cow;
    /// use parlance::FontFamilyName::{self, *};
    /// use parlance::GenericFamily::*;
    ///
    /// assert_eq!(FontFamilyName::parse("Palatino Linotype"), Some(Named(Cow::Borrowed("Palatino Linotype"))));
    /// assert_eq!(FontFamilyName::parse("monospace"), Some(Generic(Monospace)));
    ///
    /// // Note that you can quote a generic family to capture it as a named family:
    /// assert_eq!(FontFamilyName::parse("'monospace'"), Some(Named(Cow::Borrowed("monospace"))));
    /// ```
    pub fn parse(s: &'a str) -> Option<Self> {
        Self::parse_css_list(s).next()?.ok()
    }

    /// Parses a comma separated list of font families.
    ///
    /// Whitespace is ignored and a trailing comma is permitted, but empty entries (such as `,,`)
    /// are rejected.
    ///
    /// # Example
    /// ```
    /// # extern crate alloc;
    /// use alloc::borrow::Cow;
    /// use alloc::vec::Vec;
    /// use parlance::FontFamilyName::{self, *};
    /// use parlance::ParseFontFamilyError;
    /// use parlance::GenericFamily::*;
    ///
    /// let source = "Arial, 'Times New Roman', serif";
    ///
    /// let parsed_families: Result<Vec<_>, ParseFontFamilyError> =
    ///     FontFamilyName::parse_css_list(source).collect();
    /// let families = [
    ///     Named(Cow::Borrowed("Arial")),
    ///     Named(Cow::Borrowed("Times New Roman")),
    ///     Generic(Serif),
    /// ];
    ///
    /// assert_eq!(parsed_families.unwrap().as_slice(), &families);
    /// ```
    pub fn parse_css_list(
        s: &'a str,
    ) -> impl Iterator<Item = Result<FontFamilyName<'a>, ParseFontFamilyError>> + 'a + Clone {
        ParseCssList {
            source: s.as_bytes(),
            len: s.len(),
            pos: 0,
            done: false,
        }
    }

    /// Returns an owned (`'static`) version of this font family name.
    ///
    /// This is useful when you want to store a `FontFamilyName` without borrowing from an input
    /// string slice.
    ///
    /// This allocates only if the name is a borrowed string (for example, `Named(Cow::Borrowed)`).
    #[must_use]
    #[inline]
    pub fn into_owned(self) -> FontFamilyName<'static> {
        match self {
            Self::Named(name) => FontFamilyName::Named(Cow::Owned(name.into_owned())),
            Self::Generic(g) => FontFamilyName::Generic(g),
        }
    }
}

impl From<GenericFamily> for FontFamilyName<'_> {
    fn from(f: GenericFamily) -> Self {
        FontFamilyName::Generic(f)
    }
}

impl fmt::Display for FontFamilyName<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Named(name) => write!(f, "{name:?}"),
            Self::Generic(family) => write!(f, "{family}"),
        }
    }
}

/// CSS `font-family` property value.
///
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-family>
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum FontFamily<'a> {
    /// Font family list in CSS format.
    Source(Cow<'a, str>),
    /// Single font family.
    Single(FontFamilyName<'a>),
    /// Ordered list of font families.
    List(Cow<'a, [FontFamilyName<'a>]>),
}

impl<'a> FontFamily<'a> {
    /// Creates a `font-family` value consisting of a single named family.
    pub const fn named(name: &'a str) -> Self {
        Self::Single(FontFamilyName::named(name))
    }

    /// Returns an owned (`'static`) version of this `font-family` value.
    ///
    /// This is useful when you want to store a `FontFamily` without borrowing from an input string
    /// slice.
    ///
    /// This allocates only if the value is borrowed (for example, `Source(Cow::Borrowed)` or
    /// `List(Cow::Borrowed)`).
    #[must_use]
    #[inline]
    pub fn into_owned(self) -> FontFamily<'static> {
        match self {
            Self::Source(source) => FontFamily::Source(Cow::Owned(source.into_owned())),
            Self::Single(name) => FontFamily::Single(name.into_owned()),
            Self::List(list) => {
                let out: Vec<FontFamilyName<'static>> = match list {
                    Cow::Borrowed(slice) => slice
                        .iter()
                        .cloned()
                        .map(FontFamilyName::into_owned)
                        .collect(),
                    Cow::Owned(vec) => vec.into_iter().map(FontFamilyName::into_owned).collect(),
                };
                FontFamily::List(Cow::Owned(out))
            }
        }
    }
}

impl From<GenericFamily> for FontFamily<'_> {
    fn from(f: GenericFamily) -> Self {
        FontFamily::Single(f.into())
    }
}

impl<'a> From<FontFamilyName<'a>> for FontFamily<'a> {
    fn from(f: FontFamilyName<'a>) -> Self {
        FontFamily::Single(f)
    }
}

impl<'a> From<&'a str> for FontFamily<'a> {
    fn from(s: &'a str) -> Self {
        FontFamily::Source(Cow::Borrowed(s))
    }
}

impl<'a> From<&'a [FontFamilyName<'a>]> for FontFamily<'a> {
    fn from(fs: &'a [FontFamilyName<'a>]) -> Self {
        FontFamily::List(Cow::Borrowed(fs))
    }
}

#[derive(Clone)]
struct ParseCssList<'a> {
    source: &'a [u8],
    len: usize,
    pos: usize,
    done: bool,
}

impl<'a> Iterator for ParseCssList<'a> {
    type Item = Result<FontFamilyName<'a>, ParseFontFamilyError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        let mut pos = self.pos;
        while pos < self.len && self.source[pos].is_ascii_whitespace() {
            pos += 1;
        }
        self.pos = pos;
        if pos >= self.len {
            self.done = true;
            return None;
        }
        if self.source[pos] == b',' {
            self.done = true;
            return Some(Err(ParseFontFamilyError::new(
                ParseFontFamilyErrorKind::InvalidSyntax,
                pos,
            )));
        }

        let first = self.source[pos];
        let mut start = pos;
        if matches!(first, b'"' | b'\'') {
            let quote = first;
            let opening_quote = pos;
            pos += 1;
            start += 1;
            while pos < self.len {
                if self.source[pos] == quote {
                    let name = match self
                        .source
                        .get(start..pos)
                        .and_then(|bytes| core::str::from_utf8(bytes).ok())
                    {
                        Some(s) => s,
                        None => {
                            self.done = true;
                            return Some(Err(ParseFontFamilyError::new(
                                ParseFontFamilyErrorKind::InvalidSyntax,
                                start,
                            )));
                        }
                    };
                    pos += 1;
                    while pos < self.len && self.source[pos].is_ascii_whitespace() {
                        pos += 1;
                    }
                    if pos < self.len {
                        if self.source[pos] != b',' {
                            self.done = true;
                            return Some(Err(ParseFontFamilyError::new(
                                ParseFontFamilyErrorKind::InvalidSyntax,
                                pos,
                            )));
                        }
                        pos += 1;
                    }
                    self.pos = pos;
                    return Some(Ok(FontFamilyName::Named(Cow::Borrowed(name))));
                }
                pos += 1;
            }
            self.done = true;
            return Some(Err(ParseFontFamilyError::new(
                ParseFontFamilyErrorKind::UnterminatedString,
                opening_quote,
            )
            .with_span((opening_quote, self.len))));
        }
        let mut end = start;
        while pos < self.len {
            if self.source[pos] == b',' {
                pos += 1;
                break;
            }
            pos += 1;
            end += 1;
        }
        self.pos = pos;
        let name = match self
            .source
            .get(start..end)
            .and_then(|bytes| core::str::from_utf8(bytes).ok())
        {
            Some(s) => s.trim(),
            None => {
                self.done = true;
                return Some(Err(ParseFontFamilyError::new(
                    ParseFontFamilyErrorKind::InvalidSyntax,
                    start,
                )));
            }
        };
        Some(Ok(match GenericFamily::parse(name) {
            Some(family) => FontFamilyName::Generic(family),
            _ => FontFamilyName::Named(Cow::Borrowed(name)),
        }))
    }
}

#[cfg(test)]
mod tests {
    extern crate alloc;

    use alloc::borrow::Cow;

    use super::{FontFamily, FontFamilyName, GenericFamily, ParseFontFamilyErrorKind};

    #[test]
    fn parse_generic_family_is_generic_when_unquoted() {
        assert_eq!(
            FontFamilyName::parse("monospace"),
            Some(FontFamilyName::Generic(GenericFamily::Monospace))
        );
    }

    #[test]
    fn parse_generic_family_is_named_when_quoted() {
        assert_eq!(
            FontFamilyName::parse("'monospace'"),
            Some(FontFamilyName::Named(Cow::Borrowed("monospace")))
        );
        assert_eq!(
            FontFamilyName::parse("\"monospace\""),
            Some(FontFamilyName::Named(Cow::Borrowed("monospace")))
        );
    }

    #[test]
    fn parse_css_list_unterminated_string_reports_offset_and_span() {
        let err = FontFamilyName::parse_css_list("'monospace")
            .next()
            .unwrap()
            .unwrap_err();
        assert_eq!(err.kind(), ParseFontFamilyErrorKind::UnterminatedString);
        assert_eq!(err.byte_offset(), 0);
        assert_eq!(err.byte_span(), Some((0, 10)));
    }

    #[test]
    fn parse_css_list_rejects_empty_entries() {
        let err = FontFamilyName::parse_css_list("Arial,,serif")
            .collect::<Result<alloc::vec::Vec<_>, _>>()
            .unwrap_err();
        assert_eq!(err.kind(), ParseFontFamilyErrorKind::InvalidSyntax);
        assert_eq!(err.byte_offset(), 6);
        assert_eq!(err.byte_span(), None);
    }

    #[test]
    fn parse_css_list_rejects_leading_comma() {
        let err = FontFamilyName::parse_css_list(", Arial")
            .next()
            .unwrap()
            .unwrap_err();
        assert_eq!(err.kind(), ParseFontFamilyErrorKind::InvalidSyntax);
        assert_eq!(err.byte_offset(), 0);
        assert_eq!(err.byte_span(), None);
    }

    #[test]
    fn parse_css_list_trailing_comma_is_ok() {
        let families: Result<alloc::vec::Vec<_>, _> =
            FontFamilyName::parse_css_list("Arial,").collect();
        assert_eq!(
            families.unwrap(),
            alloc::vec![FontFamilyName::Named(Cow::Borrowed("Arial"))]
        );
    }

    #[test]
    fn parse_quoted_name_preserves_inner_whitespace() {
        let families: Result<alloc::vec::Vec<_>, _> =
            FontFamilyName::parse_css_list("'  Times New Roman  '").collect();
        assert_eq!(
            families.unwrap(),
            alloc::vec![FontFamilyName::Named(Cow::Borrowed("  Times New Roman  "))]
        );
    }

    #[test]
    fn parse_css_list_requires_commas_between_quoted_and_unquoted() {
        let err = FontFamilyName::parse_css_list(r#""Times New Roman" serif"#)
            .next()
            .unwrap()
            .unwrap_err();
        assert_eq!(err.kind(), ParseFontFamilyErrorKind::InvalidSyntax);
        assert_eq!(err.byte_offset(), 18);
        assert_eq!(err.byte_span(), None);
    }

    #[test]
    fn font_family_name_into_owned_preserves_value() {
        let borrowed = FontFamilyName::named("Arial");
        let owned = borrowed.into_owned();
        assert_eq!(owned, FontFamilyName::Named(Cow::Owned("Arial".into())));

        let borrowed = FontFamilyName::Generic(GenericFamily::Serif);
        let owned = borrowed.into_owned();
        assert_eq!(owned, FontFamilyName::Generic(GenericFamily::Serif));
    }

    #[test]
    fn font_family_into_owned_preserves_value() {
        let borrowed = FontFamily::from("Arial, serif");
        let owned = borrowed.into_owned();
        assert_eq!(owned, FontFamily::Source(Cow::Owned("Arial, serif".into())));

        let borrowed = FontFamily::named("Arial");
        let owned = borrowed.into_owned();
        assert_eq!(
            owned,
            FontFamily::Single(FontFamilyName::Named(Cow::Owned("Arial".into())))
        );

        let list = [
            FontFamilyName::named("Arial"),
            FontFamilyName::Generic(GenericFamily::Serif),
        ];
        let borrowed = FontFamily::from(list.as_slice());
        let owned = borrowed.into_owned();
        assert_eq!(
            owned,
            FontFamily::List(Cow::Owned(alloc::vec![
                FontFamilyName::Named(Cow::Owned("Arial".into())),
                FontFamilyName::Generic(GenericFamily::Serif),
            ]))
        );
    }
}