markdoc 0.1.0

Rust implementation of the Markdoc document language (CommonMark plus a {% tag %} extension)
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
//! Port of linkify-it 6.1.0's `src/linkifyit.ts`: the `LinkifyIt` markdown-it keeps as
//! `md.linkify` and its `linkify` rules call (`test`, `match`, `matchAtStart`).
//!
//! linkify-it 6.1.0 is the version markdown-it 15.0.1 depends on (`^6.0.0`) and the one
//! upstream Markdoc 0.5.11 bundles (its `dist/index.js.map` carries `src/linkifyit.ts` and
//! `src/rebuilder.ts`, identical to the 6.1.0 tag). Its defaults differ from 5.x: no fuzzy
//! links (`www.example.com` is not a link), fuzzy e-mails on, and a `maxLength` of 10,000.
//!
//! Text is UTF-16 code units and every position is a UTF-16 index, as in JS. The regexes are
//! hand-written matchers ([`rebuilder`]).
//!
//! # Divergences from upstream
//!
//! - Only what markdown-it uses is ported: the default schemas (`http:`, `https:`, `ftp:`,
//!   `//`, `mailto:`), the options (`fuzzyLink`, `fuzzyEmail`, `fuzzyIP`, `'---'`,
//!   `urlAuth`, `maxLength`; [`LinkifyOptions`]) and the default TLD list. `add()` (schemas
//!   with JS validator functions), `tlds()` (TLDs are regex source there) and a custom
//!   `rebuilder` are not: markdown-it never calls them, and nothing reaches them from a
//!   Markdoc config.
//! - A lone low surrogate after another code unit. uc.micro's `Any` takes it together with
//!   the unit before it, so that unit is a pseudo-letter a second way, two units long
//!   ([`rebuilder::pseudo_letter_len`] gives the first way's length, and the second's where
//!   the first fails); where a regex fails after the first way, V8 backtracks into the
//!   second, and the port's matchers do not. markdown-it never gives linkify-it such a text:
//!   its texts are source slices and whole text-token contents, and the one slice
//!   linkify-it cuts itself, `testSchemaAt`'s `text.slice(0, pos + maxLength)`, can only end
//!   in a lone high surrogate, which the port takes as V8 does; the only lone surrogate a
//!   text token holds when the core linkify rule reads it is the low half that starts the
//!   text after such a cut by the inline linkify rule, which the fourth alternative's `^`
//!   takes alone, as the port does. Only a caller giving these functions such UTF-16 of its
//!   own can see the difference. Test: `tests::a_lone_low_surrogate_is_taken_the_first_way_only`.
//!
//! `maxLength: 0` is exact: V8 rejects the path regex linkify-it builds (`{1,0}`), and
//! [`LinkifyIt::test`], [`LinkifyIt::test_schema_at`], [`LinkifyIt::match_all`] and
//! [`LinkifyIt::match_at_start`] return its `SyntaxError` (message generated from node by
//! `findings/conformance/work/utf16/linkify_max_length_zero.cjs`) where linkify-it builds it.

mod max_length_zero;
pub mod rebuilder;

use crate::markdown_it::{JsError, js};
use rebuilder::{REBuilder, REBuilderOptions, mail_name_validator};

/// `LinkifyOptions` (what `set()` takes), with linkify-it's defaults.
#[derive(Debug, Clone, PartialEq)]
pub struct LinkifyOptions {
    /// `fuzzyLink`: recognize URLs without `http(s)://`. Default `false`.
    pub fuzzy_link: bool,
    /// `fuzzyEmail`: recognize e-mails without `mailto:`. Default `true`.
    pub fuzzy_email: bool,
    /// `fuzzyIP`: allow IPv4 hosts in fuzzy links. Default `false`.
    pub fuzzy_ip: bool,
    /// `'---'`: end a link at `---` (a long dash). Default `false`.
    pub triple_dash: bool,
    /// `urlAuth`: recognize `user:pass@` in URLs. Default `false`.
    pub url_auth: bool,
    /// `maxLength`: how far a link may reach. Default `10000`.
    pub max_length: usize,
}

impl Default for LinkifyOptions {
    fn default() -> Self {
        LinkifyOptions {
            fuzzy_link: false,
            fuzzy_email: true,
            fuzzy_ip: false,
            triple_dash: false,
            url_auth: false,
            max_length: 10000,
        }
    }
}

/// The default schemas' validators (`web_schema` for `http:`, `https:` and `ftp:`, the
/// relative `//` one and `mailto:`); each normalizes with [`LinkifyIt::normalize`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Schema {
    Web,
    Relative,
    Mailto,
}

/// `defaultSchemas`, in their key order.
const DEFAULT_SCHEMAS: [(&str, Schema); 5] = [
    ("http:", Schema::Web),
    ("https:", Schema::Web),
    ("ftp:", Schema::Web),
    ("//", Schema::Relative),
    ("mailto:", Schema::Mailto),
];

// List of 2-character tlds (autogenerated by ./support/tlds_2char_gen.js)
const TLDS_2CH: &str = "a:cdefgilmnoqrstuwxz|b:abdefghijmnorstvwyz|c:acdfghiklmnoruvwxyz|d:ejkmoz|e:cegrstu|f:ijkmor|g:abdefghilmnpqrstuwy|h:kmnrtu|i:delmnoqrst|j:emop|k:eghimnprwyz|l:abcikrstuvy|m:acdeghklmnopqrstuvwxyz|n:acefgilopruz|o:m|p:aefghklmnrstwy|q:a|r:eosuw|s:abcdeghijklmnortuvxyz|t:cdfghjklmnortvwz|u:agksyz|v:aceginu|w:fs|y:et|z:amw";

// DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead
const TLDS_DEFAULT: &str =
    "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф";

/// `unpackTlds()`: the default TLDs, then every two-letter one.
fn unpack_tlds() -> Vec<Vec<u16>> {
    let mut result: Vec<Vec<u16>> = TLDS_DEFAULT.split('|').map(js::to_utf16).collect();

    for item in TLDS_2CH.split('|') {
        let (prefix, suffixes) = item.split_once(':').expect("prefix:suffixes");
        for suffix in suffixes.chars() {
            result.push(js::to_utf16(&format!("{prefix}{suffix}")));
        }
    }

    result
}

/// `Match`: a link found in a text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Match {
    /// Prefix (protocol) for matched string, lower-cased: `''` for fuzzy links, `//` for
    /// protocol-neutral ones.
    pub schema: Vec<u16>,
    /// First position of matched string.
    pub index: usize,
    /// Next position after matched string.
    pub last_index: usize,
    /// Matched string.
    pub raw: Vec<u16>,
    /// Normalized text of matched string.
    pub text: Vec<u16>,
    /// Normalized URL of matched string.
    pub url: Vec<u16>,
}

impl Match {
    /// `new Match(text, schema, index, lastIndex)`
    fn new(text: &[u16], schema: &[u16], index: usize, last_index: usize) -> Self {
        let raw = js::slice_to(text, index, last_index).to_vec();
        Match {
            schema: js::to_lower_case(schema),
            index,
            last_index,
            text: raw.clone(),
            url: raw.clone(),
            raw,
        }
    }
}

/// `MatchCandidate`
#[derive(Debug, Clone)]
struct Candidate {
    schema: Vec<u16>,
    index: usize,
    last_index: usize,
}

/// Whether `a` should be taken before `b`: it starts earlier, or at the same place and ends
/// later.
fn earlier(a: &Candidate, b: &Candidate) -> bool {
    a.index < b.index || (a.index == b.index && a.last_index > b.last_index)
}

/// `LinkifyIt`: a linkifier.
#[derive(Debug, Clone, PartialEq)]
pub struct LinkifyIt {
    opts: LinkifyOptions,
    /// `__schemas__`, in key order.
    schemas: Vec<(Vec<u16>, Schema)>,
    /// `re`: the matchers built from the options.
    pub re: REBuilder,
    /// `linkify.normalize = fn` (see [`LinkifyIt::set_normalizer`]); `None` is the default.
    normalizer: Option<Normalizer>,
}

/// A normalizer of the caller's (compared by address, as JS compares functions).
#[derive(Debug, Clone, Copy)]
struct Normalizer(fn(&mut Match));

impl PartialEq for Normalizer {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::fn_addr_eq(self.0, other.0)
    }
}

impl Default for LinkifyIt {
    fn default() -> Self {
        Self::new()
    }
}

impl LinkifyIt {
    /// `new LinkifyIt()`: the default schemas and options.
    pub fn new() -> Self {
        Self::with_options(LinkifyOptions::default())
    }

    /// `new LinkifyIt(options)`.
    pub fn with_options(options: LinkifyOptions) -> Self {
        let schemas: Vec<(Vec<u16>, Schema)> = DEFAULT_SCHEMAS
            .iter()
            .map(|&(name, schema)| (js::to_utf16(name), schema))
            .collect();
        let re = Self::rebuild(&options, &schemas);
        LinkifyIt {
            opts: options,
            schemas,
            re,
            normalizer: None,
        }
    }

    /// `linkify.normalize = normalizer`: the normalizer every match goes through, in place of
    /// the default one ([`LinkifyIt::normalize`]); `None` puts the default back. linkify-it's
    /// own tests replace it with one that does nothing, to see the raw links.
    pub fn set_normalizer(&mut self, normalizer: Option<fn(&mut Match)>) -> &mut Self {
        self.normalizer = normalizer.map(Normalizer);
        self
    }

    /// `this.normalize(match)`: the caller's normalizer, or the default.
    fn normalize_match(&self, m: &mut Match) {
        match self.normalizer {
            Some(Normalizer(normalize)) => normalize(m),
            None => self.normalize(m),
        }
    }

    /// `set(options)`: new recognition options.
    pub fn set(&mut self, options: LinkifyOptions) -> &mut Self {
        self.opts = options;
        self.re = Self::rebuild(&self.opts, &self.schemas);
        self
    }

    /// The options in use.
    pub fn options(&self) -> &LinkifyOptions {
        &self.opts
    }

    /// `this.re.set({...this.__opts__, schema_names: Object.keys(this.__schemas__)})`
    fn rebuild(opts: &LinkifyOptions, schemas: &[(Vec<u16>, Schema)]) -> REBuilder {
        REBuilder::new(REBuilderOptions {
            triple_dash: opts.triple_dash,
            fuzzy_ip: opts.fuzzy_ip,
            schema_names: schemas.iter().map(|(name, _)| name.clone()).collect(),
            tlds: unpack_tlds(),
            url_auth: opts.url_auth,
            max_length: opts.max_length,
        })
    }

    /// `this.__schemas__[name]`
    fn schema(&self, name: &[u16]) -> Option<Schema> {
        self.schemas
            .iter()
            .find(|(n, _)| n == name)
            .map(|&(_, schema)| schema)
    }

    /// `test(text)`: whether the text holds a link. `Err` where V8 throws (the path regex
    /// with `maxLength: 0`, see `Self::path_regex`).
    pub fn test(&self, text: &[u16]) -> Result<bool, JsError> {
        if text.is_empty() {
            return Ok(false);
        }

        // try to scan for link with schema - that's the most simple rule
        let mut last_index = 0;
        while let Some((m, k)) = self.re.schema_search(text, last_index) {
            last_index = m.end;
            let schema = &text[m.end - self.re.opts.schema_names[k].len()..m.end];
            if self.test_schema_at(text, schema, last_index)? != 0 {
                return Ok(true);
            }
        }

        if self.opts.fuzzy_link && self.schema(&js::to_utf16("http:")).is_some() {
            // guess schemaless links (`get_fuzzy_link_search()` builds the path regex)
            self.path_regex()?;
            if self.re.fuzzy_link_search(text, 0).is_some() {
                return Ok(true);
            }
        }

        if self.opts.fuzzy_email && self.schema(&js::to_utf16("mailto:")).is_some() {
            // guess schemaless emails
            if text.contains(&0x40) {
                // We can't skip this check, because this cases are possible:
                // 192.168.1.1@gmail.com, my.in@example.com
                let mut last_index = 0;
                while let Some(m) = self.re.fuzzy_mail_host_search(text, last_index) {
                    last_index = m.end;
                    let name = &text[m.index.saturating_sub(65)..m.index];
                    if mail_name_validator(name).is_some() {
                        return Ok(true);
                    }
                }
            }
        }

        Ok(false)
    }

    /// `testSchemaAt(text, schema, pos)`: the length of the link tail of `schema` (its key, any
    /// case) at `pos`, or 0.
    /// `Err` where V8 throws (the path regex with `maxLength: 0`, see `Self::path_regex`).
    pub fn test_schema_at(
        &self,
        text: &[u16],
        schema: &[u16],
        pos: usize,
    ) -> Result<usize, JsError> {
        // If not supported schema check requested - terminate
        let Some(kind) = self.schema(&js::to_lower_case(schema)) else {
            return Ok(0);
        };

        // `get_http_validator()` and `get_relative_proto_validator()` build the path regex
        if kind != Schema::Mailto {
            self.path_regex()?;
        }

        // `text.slice(0, pos + this.__opts__.maxLength)`
        let text = &text[..pos.saturating_add(self.opts.max_length).min(text.len())];
        Ok(match kind {
            Schema::Web => self.re.http_validator(text, pos).unwrap_or(0),
            Schema::Relative => match self.re.relative_proto_validator(text, pos) {
                // should not be `://` & `///`, that protects from errors in protocol name
                Some(_) if pos >= 3 && text[pos - 3] == 0x3A => 0,
                Some(_) if pos >= 3 && text[pos - 3] == 0x2F => 0,
                Some(len) => len,
                None => 0,
            },
            Schema::Mailto => self.re.mailto_validator(text, pos).unwrap_or(0),
        })
    }

    /// `this.re.get_path()`: linkify-it builds the path regex with `{1,maxLength}`, which V8
    /// rejects for `maxLength: 0` (`{1,0}`: `SyntaxError: Invalid regular expression: /.../:
    /// numbers out of order in {} quantifier`, the message holding the regex's source); the
    /// cache stays empty, so every call that needs it throws again.
    fn path_regex(&self) -> Result<(), JsError> {
        if self.opts.max_length != 0 {
            return Ok(());
        }
        let dash = if self.opts.triple_dash {
            max_length_zero::DASH_TRIPLE
        } else {
            max_length_zero::DASH_PLAIN
        };
        Err(JsError::new(
            "SyntaxError",
            [
                max_length_zero::BEFORE_DASH,
                dash,
                max_length_zero::AFTER_DASH,
            ]
            .concat(),
        ))
    }

    /// `match(text)`: every link in the text, or `None` (JS `null`) when there is none. `Err`
    /// where V8 throws (the path regex with `maxLength: 0`, see `Self::path_regex`).
    pub fn match_all(&self, text: &[u16]) -> Result<Option<Vec<Match>>, JsError> {
        let mut result: Vec<Match> = Vec::new();
        // `lastIndex` of the three searching regexes
        let mut schema_re_last = 0;
        let mut fuzzy_link_re_last = 0;
        let mut mail_host_re_last = 0;
        let mut fuzzy_link_candidate: Option<Candidate> = None;
        let mut fuzzy_email_candidate: Option<Candidate> = None;
        let mut schema_prefix: Option<Candidate> = None;
        let mut schema_done = false;
        let mut fuzzy_link_done = false;
        let mut fuzzy_email_done = false;
        let mut pos: usize = 0;

        if text.is_empty() {
            return Ok(None);
        }

        let fuzzy_link = self.opts.fuzzy_link && self.schema(&js::to_utf16("http:")).is_some();
        if fuzzy_link {
            // `get_fuzzy_link_search()` builds the path regex
            self.path_regex()?;
        }
        let fuzzy_email = self.opts.fuzzy_email && self.schema(&js::to_utf16("mailto:")).is_some();

        loop {
            let scan_from = pos.saturating_sub(1);

            if fuzzy_email
                && !fuzzy_email_done
                && fuzzy_email_candidate.as_ref().is_none_or(|c| c.index < pos)
            {
                if mail_host_re_last < scan_from {
                    mail_host_re_last = scan_from;
                }

                loop {
                    let Some(m) = self.re.fuzzy_mail_host_search(text, mail_host_re_last) else {
                        fuzzy_email_done = true;
                        fuzzy_email_candidate = None;
                        break;
                    };
                    mail_host_re_last = m.end;

                    let name = &text[m.index.saturating_sub(65)..m.index];
                    let Some(name_start) = mail_name_validator(name) else {
                        continue;
                    };

                    let candidate = Candidate {
                        schema: js::to_utf16("mailto:"),
                        index: m.index - (name.len() - name_start),
                        last_index: m.end,
                    };
                    let index = candidate.index;
                    fuzzy_email_candidate = Some(candidate);

                    if index >= pos {
                        break;
                    }
                    if mail_host_re_last < scan_from {
                        mail_host_re_last = scan_from;
                    }
                }
            }

            if fuzzy_link
                && !fuzzy_link_done
                && fuzzy_link_candidate.as_ref().is_none_or(|c| c.index < pos)
            {
                if fuzzy_link_re_last < scan_from {
                    fuzzy_link_re_last = scan_from;
                }

                loop {
                    let Some(m) = self.re.fuzzy_link_search(text, fuzzy_link_re_last) else {
                        fuzzy_link_done = true;
                        fuzzy_link_candidate = None;
                        break;
                    };
                    fuzzy_link_re_last = m.end;

                    let index = m.index + m.prefix;
                    fuzzy_link_candidate = Some(Candidate {
                        schema: Vec::new(),
                        index,
                        last_index: m.end,
                    });

                    if index >= pos {
                        break;
                    }
                    if fuzzy_link_re_last < scan_from {
                        fuzzy_link_re_last = scan_from;
                    }
                }
            }

            let mut fuzzy_candidate = fuzzy_email_candidate.as_ref();
            if let Some(link) = &fuzzy_link_candidate
                && fuzzy_candidate.is_none_or(|c| earlier(link, c))
            {
                fuzzy_candidate = Some(link);
            }
            let fuzzy_candidate_index = fuzzy_candidate.map(|c| c.index);

            let mut schema_candidate: Option<Candidate> = None;

            if !schema_done {
                loop {
                    let prefix = match schema_prefix.take() {
                        Some(prefix) => prefix,
                        None => {
                            if schema_re_last < scan_from {
                                schema_re_last = scan_from;
                            }

                            let Some((m, k)) = self.re.schema_search(text, schema_re_last) else {
                                schema_done = true;
                                break;
                            };
                            schema_re_last = m.end;

                            let len = self.re.opts.schema_names[k].len();
                            Candidate {
                                schema: text[m.end - len..m.end].to_vec(),
                                index: m.index + m.prefix,
                                last_index: m.end,
                            }
                        }
                    };

                    if prefix.index < pos {
                        continue;
                    }

                    if fuzzy_candidate_index.is_some_and(|index| prefix.index > index) {
                        schema_prefix = Some(prefix);
                        break;
                    }

                    let len = self.test_schema_at(text, &prefix.schema, prefix.last_index)?;
                    if len != 0 {
                        schema_candidate = Some(Candidate {
                            last_index: prefix.last_index + len,
                            ..prefix
                        });
                        break;
                    }
                }
            }

            /// Which candidate `candidate` is (JS compares the objects).
            #[derive(PartialEq)]
            enum Which {
                Schema,
                Email,
                Link,
            }
            let mut candidate = schema_candidate.map(|c| (c, Which::Schema));
            if let Some(email) = &fuzzy_email_candidate
                && candidate.as_ref().is_none_or(|(c, _)| earlier(email, c))
            {
                candidate = Some((email.clone(), Which::Email));
            }
            if let Some(link) = &fuzzy_link_candidate
                && candidate.as_ref().is_none_or(|(c, _)| earlier(link, c))
            {
                candidate = Some((link.clone(), Which::Link));
            }

            let Some((candidate, which)) = candidate else {
                break;
            };

            if which == Which::Email {
                fuzzy_email_candidate = None;
            } else if which == Which::Link {
                fuzzy_link_candidate = None;
            }

            let mut m = Match::new(
                text,
                &candidate.schema,
                candidate.index,
                candidate.last_index,
            );
            // every schema here normalizes with `self.normalize`
            self.normalize_match(&mut m);
            result.push(m);
            pos = candidate.last_index;
        }

        if !result.is_empty() {
            return Ok(Some(result));
        }

        Ok(None)
    }

    /// `matchAtStart(text)`: the fully-formed (not fuzzy) link that starts the text, if any.
    /// `Err` where V8 throws (the path regex with `maxLength: 0`, see `Self::path_regex`).
    pub fn match_at_start(&self, text: &[u16]) -> Result<Option<Match>, JsError> {
        if text.is_empty() {
            return Ok(None);
        }

        let Some((m, k)) = self.re.schema_at_start(text) else {
            return Ok(None);
        };
        let schema = &text[m.end - self.re.opts.schema_names[k].len()..m.end];

        let len = self.test_schema_at(text, schema, m.end)?;
        if len == 0 {
            return Ok(None);
        }

        let mut found = Match::new(text, schema, m.index + m.prefix, m.end + len);

        self.normalize_match(&mut found);
        Ok(Some(found))
    }

    /// `normalize(match)`: the default normalizer.
    pub fn normalize(&self, m: &mut Match) {
        // Do minimal possible changes by default. Need to collect feedback prior
        // to move forward https://github.com/markdown-it/linkify-it/issues/1

        if m.schema.is_empty() {
            let mut url = js::to_utf16("http://");
            url.extend_from_slice(&m.url);
            m.url = url;
        }

        if m.schema == js::to_utf16("mailto:") && !starts_with_mailto(&m.url) {
            let mut url = js::to_utf16("mailto:");
            url.extend_from_slice(&m.url);
            m.url = url;
        }
    }
}

/// `/^mailto:/i.test(url)`
pub(crate) fn starts_with_mailto(url: &[u16]) -> bool {
    let p = js::to_utf16("mailto:");
    url.len() >= p.len() && url.iter().zip(&p).all(|(&c, &p)| rebuilder::eq_ci(c, p))
}

#[cfg(test)]
mod tests;