lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! Close local SVG/CSS resource references while each referring document's
//! location is still known. Nothing in the retained value can reopen a file.

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::ops::Range;
use std::path::{Path, PathBuf};

use roxmltree::{Document, Node};
use url::Url;

use super::{data_uri, read_data_uri};
use crate::{Error, Result};

const SVG_NS: &str = "http://www.w3.org/2000/svg";
const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";

fn invalid(message: impl Into<String>) -> Error {
    Error::Data(message.into().into())
}

pub(crate) fn parse(source: &str) -> Result<Document<'_>> {
    let doc = Document::parse(source)
        .map_err(|error| invalid(format!("invalid static SVG XML: {error}")))?;
    if !doc.root_element().has_tag_name((SVG_NS, "svg")) {
        return Err(invalid("asset requires an SVG document root"));
    }
    Ok(doc)
}

pub(super) fn utf8(bytes: &[u8]) -> Result<&str> {
    std::str::from_utf8(bytes).map_err(|error| invalid(format!("SVG/CSS requires UTF-8: {error}")))
}

pub(super) fn escape(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

pub(super) fn apply_edits(source: &str, mut edits: Vec<(Range<usize>, String)>) -> Result<String> {
    edits.sort_by_key(|(range, _)| (range.start, range.end));
    let mut result = String::new();
    let mut cursor = 0;
    for (range, replacement) in edits {
        if range.start < cursor || range.end > source.len() {
            return Err(invalid("overlapping SVG resource edits"));
        }
        crate::data::source::reserve_source_string(
            &mut result,
            range.start - cursor + replacement.len(),
        )?;
        result.push_str(&source[cursor..range.start]);
        result.push_str(&replacement);
        cursor = range.end;
    }
    crate::data::source::reserve_source_string(&mut result, source.len() - cursor)?;
    result.push_str(&source[cursor..]);
    Ok(result)
}

pub(super) fn opening_end(source: &str, node: Node<'_, '_>) -> usize {
    let mut quote = None;
    for (index, ch) in source[node.range().start..].char_indices() {
        match (quote, ch) {
            (Some(q), ch) if q == ch => quote = None,
            (None, '\'' | '"') => quote = Some(ch),
            (None, '>') => return node.range().start + index,
            _ => {}
        }
    }
    unreachable!("validated XML start tag")
}

struct Resource {
    mime: String,
    bytes: Vec<u8>,
    base: Option<Url>,
    path: Option<PathBuf>,
    fragment: Option<String>,
}

#[derive(Default)]
struct Closure {
    files: HashMap<PathBuf, Vec<u8>>,
    active: HashSet<PathBuf>,
}

pub(super) fn close(bytes: &[u8], path: Option<&Path>) -> Result<String> {
    let mut closure = Closure::default();
    let base = path.map(file_url).transpose()?;
    if let Some(path) = path {
        closure.active.insert(std::fs::canonicalize(path)?);
    }
    closure.svg(utf8(bytes)?, base.as_ref())
}

fn file_url(path: &Path) -> Result<Url> {
    let absolute = std::path::absolute(path)?;
    Url::from_file_path(&absolute).map_err(|()| {
        invalid(format!(
            "cannot resolve local SVG resource {}",
            path.display()
        ))
    })
}

fn resolve_url(reference: &str, base: Option<&Url>) -> Result<Url> {
    let base = base.ok_or_else(|| {
        invalid(format!(
            "SVG byte input must be self-contained: {reference}"
        ))
    })?;
    #[cfg(windows)]
    let absolute_reference = if Path::new(reference).is_absolute() {
        format!("file:///{}", reference.replace('\\', "/"))
    } else {
        reference.to_owned()
    };
    #[cfg(windows)]
    let reference = absolute_reference.as_str();
    let url = base
        .join(reference)
        .map_err(|error| invalid(format!("invalid SVG resource {reference:?}: {error}")))?;
    if url.scheme() != "file" || url.host_str().is_some_and(|host| host != "localhost") {
        return Err(invalid(format!("SVG resource must be local: {reference}")));
    }
    Ok(url)
}

fn mime_type(path: &Path) -> Result<&'static str> {
    match path
        .extension()
        .and_then(|value| value.to_str())
        .map(str::to_ascii_lowercase)
        .as_deref()
    {
        Some("svg") => Ok("image/svg+xml"),
        Some("png") => Ok("image/png"),
        Some("jpg" | "jpeg") => Ok("image/jpeg"),
        Some("gif") => Ok("image/gif"),
        Some("webp") => Ok("image/webp"),
        Some("css") => Ok("text/css"),
        Some("ttf") => Ok("font/ttf"),
        Some("otf") => Ok("font/otf"),
        Some("ttc") => Ok("font/collection"),
        Some("woff") => Ok("font/woff"),
        Some("woff2") => Ok("font/woff2"),
        _ => Err(invalid(format!(
            "unrecognized local SVG resource type: {}",
            path.display()
        ))),
    }
}

impl Closure {
    fn load(&mut self, reference: &str, base: Option<&Url>) -> Result<Resource> {
        crate::operation::checkpoint()?;
        if reference
            .get(..5)
            .is_some_and(|s| s.eq_ignore_ascii_case("data:"))
        {
            let (mime, bytes) = read_data_uri(reference)?;
            return Ok(Resource {
                mime,
                bytes,
                base: None,
                path: None,
                fragment: reference
                    .split_once('#')
                    .map(|(_, fragment)| fragment.to_owned()),
            });
        }
        let url = resolve_url(reference, base)?;
        let path = url
            .to_file_path()
            .map_err(|()| invalid(format!("invalid local resource path: {reference}")))?;
        let path_key = crate::operation::external(|| std::fs::canonicalize(&path))?;
        if self.active.contains(&path_key) {
            return Err(invalid(format!(
                "cyclic SVG/CSS resource reference: {}",
                path.display()
            )));
        }
        let mime = mime_type(&path)?.to_owned();
        if !self.files.contains_key(&path_key) {
            let bytes = crate::operation::external(|| std::fs::read(&path))?;
            self.files.insert(path_key.clone(), bytes);
        }
        let fragment = url.fragment().map(str::to_owned);
        Ok(Resource {
            mime,
            bytes: self.files[&path_key].clone(),
            base: Some(url),
            path: Some(path_key),
            fragment,
        })
    }

    fn with_document<T>(
        &mut self,
        resource: &Resource,
        f: impl FnOnce(&mut Self, &str, Option<&Url>) -> Result<T>,
    ) -> Result<T> {
        if let Some(path) = &resource.path {
            self.active.insert(path.clone());
        }
        let result = utf8(&resource.bytes)
            .and_then(|source| f(self, source, resource.base.as_ref()))
            .map_err(|error| {
                error.with_prefix(
                    &resource
                        .base
                        .as_ref()
                        .map_or_else(|| "embedded SVG resource".to_owned(), Url::to_string),
                )
            });
        if let Some(path) = &resource.path {
            self.active.remove(path);
        }
        result
    }

    fn resource_uri(&mut self, reference: &str, base: Option<&Url>) -> Result<String> {
        if reference.starts_with('#') || reference.is_empty() {
            return Ok(reference.to_owned());
        }
        let resource = self.load(reference, base)?;
        let fragment = resource
            .fragment
            .as_ref()
            .map_or_else(String::new, |id| format!("#{id}"));
        if resource.mime == "image/svg+xml" {
            let svg = self.with_document(&resource, Self::svg)?;
            return Ok(data_uri("image/svg+xml", svg.as_bytes()) + &fragment);
        }
        if resource.mime == "text/css" {
            let css = self.with_document(&resource, Self::css)?;
            return Ok(data_uri("text/css", css.as_bytes()));
        }
        if resource.mime == "image/png" {
            super::png::metadata(&resource.bytes)?;
        }
        if !resource.mime.starts_with("image/")
            && !resource.mime.starts_with("font/")
            && !matches!(
                resource.mime.as_str(),
                "application/font-woff"
                    | "application/font-sfnt"
                    | "application/octet-stream"
                    | "application/x-font-ttf"
                    | "application/x-font-opentype"
            )
        {
            return Err(invalid(format!(
                "unsupported SVG drawing resource MIME type {}",
                resource.mime
            )));
        }
        Ok(data_uri(&resource.mime, &resource.bytes) + &fragment)
    }

    fn stylesheet(&mut self, reference: &str, base: Option<&Url>) -> Result<String> {
        let resource = self.load(reference, base)?;
        if resource.mime != "text/css" {
            return Err(invalid(format!("SVG stylesheet {reference:?} is not CSS")));
        }
        self.with_document(&resource, Self::css)
    }

    fn fragment(
        &mut self,
        reference: &str,
        base: Option<&Url>,
        namespace: &str,
    ) -> Result<(String, String)> {
        let resource = self.load(reference, base)?;
        let id = resource
            .fragment
            .as_deref()
            .filter(|id| !id.is_empty())
            .ok_or_else(|| {
                invalid(format!(
                    "external SVG use requires a fragment ID: {reference}"
                ))
            })?;
        if resource.mime != "image/svg+xml" {
            return Err(invalid(format!(
                "external use source is not SVG: {reference}"
            )));
        }
        let id = percent_encoding::percent_decode_str(id)
            .decode_utf8()
            .map_err(|_| invalid("external SVG fragment ID is not UTF-8"))?;
        let source = super::css::inline_static_styles(&self.with_document(&resource, Self::svg)?)?;
        let document = parse(&source)?;
        if document
            .descendants()
            .filter(|node| node.attribute("id") == Some(id.as_ref()))
            .count()
            != 1
        {
            return Err(invalid(format!(
                "external SVG fragment {reference:?} is missing or ambiguous"
            )));
        }
        let root = document.root_element();
        let mut edits = Vec::new();
        for node in root.descendants().filter(Node::is_element) {
            for attr in node.attributes() {
                let value = attr.value();
                let replacement = if attr.name() == "id" {
                    Some(format!("{namespace}{value}"))
                } else if attr.name() == "href" && value.starts_with('#') {
                    Some(format!("#{namespace}{}", &value[1..]))
                } else if contains_url(value) {
                    Some(namespace_urls(value, namespace)?)
                } else {
                    None
                };
                if let Some(replacement) = replacement {
                    edits.push((attr.range_value(), escape(&replacement)));
                }
            }
        }
        // Keep the source document's SVG namespace and its actual definitions,
        // including each local clip, gradient and referenced symbol. Hidden
        // source children are reachable through the single rewritten use.
        let source = apply_edits(&source, edits)?;
        let document = parse(&source)?;
        Ok((
            source[document.root_element().range()].to_owned(),
            format!("#{namespace}{id}"),
        ))
    }

    #[expect(
        clippy::too_many_lines,
        reason = "one pass seals XML resources and records disjoint source edits"
    )]
    fn svg(&mut self, source: &str, base: Option<&Url>) -> Result<String> {
        let doc = parse(source)?;
        let mut edits = Vec::new();
        let mut definitions = String::new();
        let mut fragments = String::new();
        for (index, node) in doc.descendants().enumerate() {
            if index.is_multiple_of(64) {
                crate::operation::checkpoint()?;
            }
            if let Some(pi) = node.pi().filter(|pi| pi.target == "xml-stylesheet") {
                let attributes = format!("<stylesheet {}/>", pi.value.unwrap_or(""));
                let pi_doc = Document::parse(&attributes)
                    .map_err(|error| invalid(format!("invalid xml-stylesheet: {error}")))?;
                let stylesheet = pi_doc.root_element();
                let href = stylesheet
                    .attribute("href")
                    .ok_or_else(|| invalid("xml-stylesheet lacks href"))?;
                let css = self.stylesheet(href, base)?;
                // Insert the sheet as the first child, before author style
                // elements, and remove the now consumed processing instruction.
                definitions.push_str(&style_element(&css, stylesheet.attribute("media")));
                edits.push((node.range(), String::new()));
                continue;
            }
            if !node.is_element() || node.tag_name().namespace() != Some(SVG_NS) {
                continue;
            }
            let tag = node.tag_name().name();
            if tag == "script"
                || tag.starts_with("animate")
                || matches!(tag, "set" | "discard" | "foreignObject")
            {
                return Err(invalid(format!(
                    "SVG asset is static; unsupported element {tag}"
                )));
            }
            let effective = node_base(node, base)?;
            if tag == "style" {
                let css: String = node.children().filter_map(|child| child.text()).collect();
                let css = self.css(&css, effective.as_ref())?;
                edits.push((node.range(), style_element(&css, node.attribute("media"))));
                continue;
            }
            if tag == "link" && node.attribute("rel") == Some("stylesheet") {
                let href = node
                    .attribute("href")
                    .ok_or_else(|| invalid("SVG stylesheet link lacks href"))?;
                let css = self.stylesheet(href, effective.as_ref())?;
                edits.push((node.range(), style_element(&css, node.attribute("media"))));
                continue;
            }
            for attribute in node.attributes() {
                let name = attribute.name();
                let value = attribute.value();
                if name.starts_with("on") && attribute.namespace().is_none() {
                    return Err(invalid(format!(
                        "SVG asset contains an event handler {name}"
                    )));
                }
                if name == "base" && attribute.namespace() == Some(XML_NS) {
                    edits.push((attribute.range(), String::new()));
                    continue;
                }
                if name == "href" && tag != "a" {
                    if value.starts_with('#') || value.is_empty() {
                        continue;
                    }
                    if matches!(
                        tag,
                        "use"
                            | "linearGradient"
                            | "radialGradient"
                            | "pattern"
                            | "textPath"
                            | "mpath"
                    ) {
                        let mut namespace = format!("__lichtung_resource_{index}_");
                        while doc.descendants().any(|node| {
                            node.attribute("id")
                                .is_some_and(|id| id.starts_with(&namespace))
                        }) {
                            namespace.push('_');
                        }
                        let (fragment, href) =
                            self.fragment(value, effective.as_ref(), &namespace)?;
                        let _ = write!(fragments, "<defs xmlns=\"{SVG_NS}\">{fragment}</defs>");
                        edits.push((attribute.range_value(), escape(&href)));
                        continue;
                    }
                    if !matches!(tag, "image" | "feImage") {
                        return Err(invalid(format!("external SVG fragment reference {value:?} on {tag} cannot yet be sealed")));
                    }
                    let uri = self.resource_uri(value, effective.as_ref())?;
                    edits.push((attribute.range_value(), escape(&uri)));
                } else if name == "style" || contains_url(value) {
                    let css = self.css(value, effective.as_ref())?;
                    if css != value {
                        edits.push((attribute.range_value(), escape(&css)));
                    }
                }
            }
        }
        insert_definitions(source, doc.root_element(), definitions, &mut edits);
        let source = apply_edits(source, edits)?;
        if fragments.is_empty() {
            return Ok(source);
        }
        let source = super::css::inline_static_styles(&source)?;
        let doc = parse(&source)?;
        let mut edits = Vec::new();
        insert_definitions(&source, doc.root_element(), fragments, &mut edits);
        apply_edits(&source, edits)
    }

    fn css(&mut self, source: &str, base: Option<&Url>) -> Result<String> {
        let mut output = String::new();
        let mut rest = source;
        while !rest.is_empty() {
            crate::operation::check()?;
            if rest.starts_with("/*") {
                let end = rest
                    .find("*/")
                    .ok_or_else(|| invalid("unterminated CSS comment"))?
                    + 2;
                output.push_str(&rest[..end]);
                rest = &rest[end..];
            } else if rest.starts_with(['"', '\'']) {
                let (_, tail) = quoted(rest)?;
                output.push_str(&rest[..rest.len() - tail.len()]);
                rest = tail;
            } else if let Some(tail) = keyword(rest, "@import") {
                let tail = tail.trim_start();
                let (reference, tail) = if let Some(url) = url_function(tail) {
                    url_value(url)?
                } else {
                    quoted(tail)?
                };
                let end = tail
                    .find(';')
                    .ok_or_else(|| invalid("CSS @import requires a terminating semicolon"))?;
                let qualifier = tail[..end].trim();
                let css = self.stylesheet(&reference, base)?;
                if qualifier.is_empty() || qualifier.eq_ignore_ascii_case("all") {
                    output.push_str(&css);
                } else {
                    let _ = write!(output, "@media {qualifier} {{ {css} }}");
                }
                rest = &tail[end + 1..];
            } else if let Some(tail) = url_function(rest) {
                let (reference, tail) = url_value(tail)?;
                let uri = self.resource_uri(&reference, base)?;
                write_css_url(&mut output, &uri);
                rest = tail;
            } else {
                let ch = rest.chars().next().expect("nonempty CSS remainder");
                if ch == '\\' {
                    return Err(invalid(
                        "escaped CSS identifiers are not supported in static SVG resources",
                    ));
                }
                // Skip a complete identifier so 'myurl(' is not misread as url().
                let len = if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
                    rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_')
                        .unwrap_or(rest.len())
                } else {
                    ch.len_utf8()
                };
                output.push_str(&rest[..len]);
                rest = &rest[len..];
            }
        }
        Ok(output)
    }
}

fn insert_definitions(
    source: &str,
    root: Node<'_, '_>,
    definitions: String,
    edits: &mut Vec<(Range<usize>, String)>,
) {
    if definitions.is_empty() {
        return;
    }
    let end = opening_end(source, root);
    if source.as_bytes()[end - 1] == b'/' {
        let tag = &source[root.range().start + 1..end - 1];
        let name = tag.split_whitespace().next().unwrap_or(tag);
        edits.push((end - 1..end + 1, format!(">{definitions}</{name}>")));
    } else {
        edits.push((end + 1..end + 1, definitions));
    }
}

fn namespace_urls(value: &str, namespace: &str) -> Result<String> {
    let mut output = String::new();
    let mut rest = value;
    while let Some(start) = rest.find("url(") {
        output.push_str(&rest[..start]);
        let (reference, tail) = url_value(&rest[start + 4..])?;
        let uri = if let Some(id) = reference.strip_prefix('#') {
            format!("#{namespace}{id}")
        } else {
            reference
        };
        write_css_url(&mut output, &uri);
        rest = tail;
    }
    output.push_str(rest);
    Ok(output)
}

fn write_css_url(output: &mut String, uri: &str) {
    // A local FuncIRI has the same CSS meaning without quotes. In particular,
    // the device's filter-list parser requires the unquoted representation.
    if uri.starts_with('#')
        && !uri.chars().any(|ch| {
            ch.is_whitespace() || ch.is_control() || matches!(ch, '"' | '\'' | '(' | ')' | '\\')
        })
    {
        let _ = write!(output, "url({uri})");
    } else {
        let _ = write!(
            output,
            r#"url("{}")"#,
            uri.replace('\\', "\\\\").replace('"', "\\\"")
        );
    }
}

fn node_base(node: Node<'_, '_>, base: Option<&Url>) -> Result<Option<Url>> {
    let mut bases: Vec<&str> = node
        .ancestors()
        .filter_map(|node| node.attribute((XML_NS, "base")))
        .collect();
    let mut base = base.cloned();
    while let Some(relative) = bases.pop() {
        base = Some(resolve_url(relative, base.as_ref())?);
    }
    Ok(base)
}

pub(super) fn style_element(css: &str, media: Option<&str>) -> String {
    let media = media.map_or_else(String::new, |media| format!(" media=\"{}\"", escape(media)));
    format!("<style xmlns=\"{SVG_NS}\"{media}>{}</style>", escape(css))
}

fn contains_url(value: &str) -> bool {
    value
        .as_bytes()
        .windows(3)
        .any(|part| part.eq_ignore_ascii_case(b"url"))
}

fn keyword<'a>(text: &'a str, name: &str) -> Option<&'a str> {
    let start = text.get(..name.len())?;
    if !start.eq_ignore_ascii_case(name) {
        return None;
    }
    let tail = &text[name.len()..];
    if tail.starts_with(|ch: char| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_') {
        return None;
    }
    Some(tail)
}

fn url_function(text: &str) -> Option<&str> {
    keyword(text, "url")?.trim_start().strip_prefix('(')
}

fn url_value(text: &str) -> Result<(String, &str)> {
    let text = text.trim_start();
    if text.starts_with(['"', '\'']) {
        let (value, tail) = quoted(text)?;
        let tail = tail
            .trim_start()
            .strip_prefix(')')
            .ok_or_else(|| invalid("invalid CSS url()"))?;
        return Ok((value, tail));
    }
    let mut rest = text;
    let mut value = String::new();
    while let Some(ch) = rest.chars().next() {
        rest = &rest[ch.len_utf8()..];
        match ch {
            ')' => return Ok((value, rest)),
            '\\' => {
                let (decoded, tail) = css_escape(rest)?;
                value.extend(decoded);
                rest = tail;
            }
            '\'' | '"' | '(' => return Err(invalid("invalid unquoted CSS url()")),
            ch if ch.is_ascii_whitespace() => {
                let tail = rest
                    .trim_start()
                    .strip_prefix(')')
                    .ok_or_else(|| invalid("whitespace inside unquoted CSS url()"))?;
                return Ok((value, tail));
            }
            _ => value.push(ch),
        }
    }
    Err(invalid("unterminated CSS url()"))
}

fn quoted(text: &str) -> Result<(String, &str)> {
    let quote = text
        .chars()
        .next()
        .filter(|ch| matches!(ch, '"' | '\''))
        .ok_or_else(|| invalid("CSS resource URL must be quoted or use url()"))?;
    let mut value = String::new();
    let mut rest = &text[1..];
    while let Some(ch) = rest.chars().next() {
        rest = &rest[ch.len_utf8()..];
        if ch == quote {
            return Ok((value, rest));
        }
        if ch == '\\' {
            let (decoded, tail) = css_escape(rest)?;
            value.extend(decoded);
            rest = tail;
        } else {
            value.push(ch);
        }
    }
    Err(invalid("unterminated CSS string"))
}

fn css_escape(text: &str) -> Result<(Option<char>, &str)> {
    let ch = text
        .chars()
        .next()
        .ok_or_else(|| invalid("unterminated CSS escape"))?;
    let digits = text
        .bytes()
        .take(6)
        .take_while(u8::is_ascii_hexdigit)
        .count();
    if digits > 0 {
        let scalar = u32::from_str_radix(&text[..digits], 16)
            .map_err(|_| invalid("invalid CSS hexadecimal escape"))?;
        let mut tail = &text[digits..];
        if let Some(ch) = tail.chars().next().filter(char::is_ascii_whitespace) {
            tail = &tail[ch.len_utf8()..];
        }
        return Ok((
            Some(
                char::from_u32(scalar)
                    .filter(|ch| *ch != '\0')
                    .unwrap_or('\u{fffd}'),
            ),
            tail,
        ));
    }
    let tail = &text[ch.len_utf8()..];
    Ok(((!matches!(ch, '\n' | '\r' | '\u{c}')).then_some(ch), tail))
}