use std::sync::OnceLock;
use crate::markdown_it::common::ucmicro;
use crate::markdown_it::js;
#[derive(Debug, Clone, PartialEq)]
pub struct REBuilderOptions {
pub triple_dash: bool,
pub fuzzy_ip: bool,
pub schema_names: Vec<Vec<u16>>,
pub tlds: Vec<Vec<u16>>,
pub url_auth: bool,
pub max_length: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub struct REBuilder {
pub opts: REBuilderOptions,
tld_list: Vec<Vec<u16>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Found {
pub index: usize,
pub prefix: usize,
pub end: usize,
}
impl REBuilder {
pub fn new(opts: REBuilderOptions) -> Self {
let mut tlds: Vec<Vec<u16>> = Vec::new();
for tld in &opts.tlds {
if !tlds.contains(tld) {
tlds.push(tld.clone());
}
}
tlds.sort();
tlds.reverse();
REBuilder {
opts,
tld_list: tlds,
}
}
fn schema_at(&self, t: &[u16], q: usize) -> Option<(usize, usize)> {
self.opts
.schema_names
.iter()
.enumerate()
.find(|(_, name)| starts_with_ci(t, q, name))
.map(|(k, name)| (k, name.len()))
}
fn schema_prefix_at(t: &[u16], i: usize) -> usize {
match t.get(i) {
None | Some(&0x5F) => 0,
Some(&c) if is_sep(c) => 1,
Some(_) => zpcc_len(t, i),
}
}
pub fn schema_search(&self, t: &[u16], last_index: usize) -> Option<(Found, usize)> {
if last_index > t.len() {
return None;
}
(last_index..=t.len()).find_map(|i| self.schema_search_at(t, i))
}
fn schema_search_at(&self, t: &[u16], i: usize) -> Option<(Found, usize)> {
if i == 0
&& let Some((k, len)) = self.schema_at(t, 0)
{
let found = Found {
index: 0,
prefix: 0,
end: len,
};
return Some((found, k));
}
let prefix = Self::schema_prefix_at(t, i);
if prefix > 0
&& let Some((k, len)) = self.schema_at(t, i + prefix)
{
let found = Found {
index: i,
prefix,
end: i + prefix + len,
};
return Some((found, k));
}
None
}
pub fn schema_at_start(&self, t: &[u16]) -> Option<(Found, usize)> {
self.schema_search_at(t, 0)
}
pub fn http_validator(&self, t: &[u16], pos: usize) -> Option<usize> {
if !(t.get(pos) == Some(&0x2F) && t.get(pos + 1) == Some(&0x2F)) {
return None;
}
let start = pos + 2;
let after_host = |p: usize| self.url_host_port(t, p);
let host_end = self.with_auth(t, start, after_host)?;
Some(self.path(t, host_end) - pos)
}
pub fn relative_proto_validator(&self, t: &[u16], pos: usize) -> Option<usize> {
let host = |p: usize| -> Option<usize> {
if starts_with_ci_str(t, p, "localhost")
&& let Some(end) = self.port_and_terminator(t, p + 9)
{
return Some(end);
}
if let Some(end) = ipv6_url_host(t, p)
&& let Some(end) = self.port_and_terminator(t, end)
{
return Some(end);
}
self.host_labels(t, p, 1, 10, FinalLabel::DomainRoot, |e| {
self.port_and_terminator(t, e)
})
};
let host_end = self.with_auth(t, pos, host)?;
Some(self.path(t, host_end) - pos)
}
pub fn mailto_validator(&self, t: &[u16], pos: usize) -> Option<usize> {
let at = mail_name_end(t, pos)?;
if t.get(at) != Some(&0x40) {
return None;
}
let end = self.mail_host(t, at + 1)?;
Some(end - pos)
}
fn with_auth(
&self,
t: &[u16],
p: usize,
rest: impl Fn(usize) -> Option<usize>,
) -> Option<usize> {
if self.opts.url_auth {
let mut k = 0;
while k < 50
&& t.get(p + k).is_some_and(|&c| {
!is_zcc(c) && !matches!(c, 0x40 | 0x2F | 0x5B | 0x5D | 0x28 | 0x29)
})
{
k += 1;
}
if k >= 1
&& t.get(p + k) == Some(&0x40)
&& let Some(end) = rest(p + k + 1)
{
return Some(end);
}
}
rest(p)
}
fn url_host_port(&self, t: &[u16], p: usize) -> Option<usize> {
if let Some(end) = ipv6_url_host(t, p)
&& let Some(end) = self.port_and_terminator(t, end)
{
return Some(end);
}
self.host_labels(t, p, 0, 10, FinalLabel::Domain, |e| {
self.port_and_terminator(t, e)
})
}
fn mail_host(&self, t: &[u16], p: usize) -> Option<usize> {
if let Some(end) = ipv6_mail_host(t, p)
&& self.host_terminator(t, end)
{
return Some(end);
}
self.host_labels(t, p, 0, 4, FinalLabel::Domain, |e| {
self.host_terminator(t, e).then_some(e)
})
}
fn fuzzy_mail_host(&self, t: &[u16], p: usize) -> Option<usize> {
if let Some(end) = ipv6_mail_host(t, p)
&& self.host_terminator(t, end)
{
return Some(end);
}
self.host_labels(t, p, 1, 4, FinalLabel::DomainRoot, |e| {
self.host_terminator(t, e).then_some(e)
})
}
fn fuzzy_url_host(&self, t: &[u16], p: usize) -> Option<usize> {
if self.opts.fuzzy_ip
&& let Some(end) = ipv4_address(t, p)
&& self.host_terminator(t, end)
{
return Some(end);
}
self.host_labels(t, p, 1, 10, FinalLabel::Tld, |e| {
self.host_terminator(t, e).then_some(e)
})
}
fn host_labels(
&self,
t: &[u16],
p: usize,
min: usize,
max: usize,
last: FinalLabel,
rest: impl Fn(usize) -> Option<usize>,
) -> Option<usize> {
let mut starts = [0usize; 11];
starts[0] = p;
let mut rounds = 0;
while rounds < max {
let a = starts[rounds];
let run = label_run(t, a);
if !run.is_domain(t, a) || t.get(run.end) != Some(&0x2E) {
break;
}
rounds += 1;
starts[rounds] = run.end + 1;
}
if rounds < min {
return None;
}
(min..=rounds)
.rev()
.find_map(|c| self.final_label(t, starts[c], last, &rest))
}
fn final_label(
&self,
t: &[u16],
a: usize,
last: FinalLabel,
rest: &impl Fn(usize) -> Option<usize>,
) -> Option<usize> {
let xn = || xn_label_ends(t, a).find_map(rest);
match last {
FinalLabel::Domain => xn().or_else(|| {
let first = pseudo_letter_len(t, a);
if first == 0 {
return None;
}
rest(a + first).or_else(|| {
let items = label_items(t, a + first, 61);
let next = |j: usize| -> Option<usize> {
let start = if j == 0 { a + first } else { items.ends[j - 1] };
if j < items.count {
items.is_l[j].then_some(items.ends[j])
} else {
match pseudo_letter_len(t, start) {
0 => None,
len => (items.count == 61).then_some(start + len),
}
}
};
(0..=items.count).rev().find_map(|j| next(j).and_then(rest))
})
}),
FinalLabel::DomainRoot => xn().or_else(|| {
let letters = letter_ends(t, a, 63);
letters.iter().rev().find_map(|&e| rest(e))
}),
FinalLabel::Tld => self
.tld_list
.iter()
.filter(|tld| starts_with_ci(t, a, tld))
.find_map(|tld| rest(a + tld.len()))
.or_else(xn),
}
}
fn port_and_terminator(&self, t: &[u16], e: usize) -> Option<usize> {
if t.get(e) == Some(&0x3A) && t.get(e + 1).is_some_and(|&c| is_digit(c)) {
let digits = t[e + 1..]
.iter()
.take(6)
.take_while(|&&c| is_digit(c))
.count();
let end = e + 1 + digits;
return (is_port(&t[e + 1..end]) && self.host_terminator(t, end)).then_some(end);
}
self.host_terminator(t, e).then_some(e)
}
pub fn host_terminator(&self, t: &[u16], e: usize) -> bool {
let n = t.len();
if e >= n {
return true;
}
let c = t[e];
if !(is_sep(c) || zpcc_len(t, e) > 0) {
return false;
}
let at = |k: usize| t.get(e + k).copied();
let dash_ends = if self.opts.triple_dash {
c == 0x2D && !(at(1) == Some(0x2D) && at(2) == Some(0x2D))
} else {
c == 0x2D
};
let dot_continues = c == 0x2E && e + 1 < n && zpcc_len(t, e + 1) == 0;
!(dash_ends
|| c == 0x5F
|| (c == 0x3A && at(1).is_some_and(is_digit))
|| (c == 0x2E && at(1) == Some(0x2D))
|| dot_continues)
}
pub fn path(&self, t: &[u16], p: usize) -> usize {
let Some(&c) = t.get(p) else {
return p;
};
if matches!(c, 0x2F | 0x3F | 0x23) {
let mut q = p + 1;
let mut rounds = 0;
while rounds < self.opts.max_length {
match self.path_round(t, q) {
Some(len) => {
q += len;
rounds += 1;
}
None => break,
}
}
if rounds >= 1 {
return q;
}
}
if c == 0x2F { p + 1 } else { p }
}
fn path_round(&self, t: &[u16], q: usize) -> Option<usize> {
let n = t.len();
let c = *t.get(q)?;
let next = t.get(q + 1).copied();
let next_not_zcc_or_end = next.is_some_and(|d| !is_zcc(d));
for (open, close) in [(0x5B, 0x5D), (0x28, 0x29), (0x7B, 0x7D)] {
if c == open
&& let Some(end) = nested_pair(t, q, open, close, 4)
{
return Some(end - q);
}
}
if (c == 0x22 || c == 0x27)
&& let Some(len) = quoted(t, q, c)
{
return Some(len);
}
if c == 0x27 && (next == Some(0x2D) || pseudo_letter_len(t, q + 1) > 0) {
return Some(1);
}
if c == 0x2E {
let dots = t[q..].iter().take(21).take_while(|&&d| d == 0x2E).count();
if (2..=20).contains(&dots) {
let e = q + dots;
if t.get(e) == Some(&0x3A) && t.get(e + 1).is_some_and(|&d| is_path_class(d)) {
return Some(dots + 2);
}
if t.get(e).is_some_and(|&d| is_path_class(d)) {
return Some(dots + 1);
}
}
if next_not_zcc_or_end && next != Some(0x2E) {
return Some(1);
}
}
if c == 0x2D {
let dashes = t[q..].iter().take(21).take_while(|&&d| d == 0x2D).count();
if self.opts.triple_dash {
let long_dash = dashes == 3;
if !long_dash {
return Some(dashes.min(20));
}
} else {
return Some(dashes.min(20));
}
}
if (c == 0x2C || c == 0x3B) && next_not_zcc_or_end {
return Some(1);
}
if c == 0x21 {
let bangs = t[q..].iter().take(21).take_while(|&&d| d == 0x21).count();
if bangs <= 20 && t.get(q + bangs).is_some_and(|&d| !is_zcc(d)) {
return Some(bangs);
}
}
if c == 0x3F && next_not_zcc_or_end && next != Some(0x3F) {
return Some(1);
}
if matches!(
c,
0x5C | 0x2F | 0x3A | 0x25 | 0x40 | 0x23 | 0x26 | 0x3D | 0x5F | 0x7E | 0x2A
) {
return Some(1);
}
if q < n && !is_sep(c) && zpcc_len(t, q) == 0 {
return Some(1);
}
None
}
pub fn fuzzy_mail_host_search(&self, t: &[u16], last_index: usize) -> Option<Found> {
let mut i = last_index;
while i < t.len() {
let at = i + t[i..].iter().position(|&c| c == 0x40)?;
if let Some(end) = self.fuzzy_mail_host(t, at + 1) {
return Some(Found {
index: at,
prefix: 0,
end,
});
}
i = at + 1;
}
None
}
pub fn fuzzy_link_search(&self, t: &[u16], last_index: usize) -> Option<Found> {
if last_index > t.len() {
return None;
}
(last_index..=t.len()).find_map(|i| {
let mut prefixes = [None, None];
if i == 0 {
prefixes[0] = Some(0);
}
if let Some(&c) = t.get(i)
&& !matches!(c, 0x2E | 0x3A | 0x2F | 0x2D | 0x5F | 0x40)
{
let len = if is_fuzzy_prefix_symbol(c) {
1
} else {
zpcc_len(t, i)
};
if len > 0 {
prefixes[1] = Some(len);
}
}
prefixes.into_iter().flatten().find_map(|prefix| {
let h = i + prefix;
if t.get(h).is_some_and(|&c| is_fuzzy_prefix_symbol(c)) {
return None;
}
let host_end = self.fuzzy_url_host(t, h)?;
Some(Found {
index: i,
prefix,
end: self.path(t, host_end),
})
})
})
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum FinalLabel {
Domain,
DomainRoot,
Tld,
}
struct LabelRun {
end: usize,
items: usize,
first_l: bool,
last_l: bool,
too_long: bool,
}
fn label_run(t: &[u16], a: usize) -> LabelRun {
let mut run = LabelRun {
end: a,
items: 0,
first_l: false,
last_l: false,
too_long: false,
};
loop {
let (len, is_l) = if t.get(run.end) == Some(&0x2D) {
(1, false)
} else {
match pseudo_letter_len(t, run.end) {
0 => break,
len => (len, true),
}
};
if run.items == 63 {
run.too_long = true;
break;
}
if run.items == 0 {
run.first_l = is_l;
}
run.last_l = is_l;
run.items += 1;
run.end += len;
}
run
}
impl LabelRun {
fn is_domain(&self, t: &[u16], a: usize) -> bool {
!self.too_long
&& self.items >= 1
&& ((self.first_l && self.last_l) || is_xn_label(t, a, self.end))
}
}
struct LabelItems {
count: usize,
ends: [usize; 61],
is_l: [bool; 61],
}
fn label_items(t: &[u16], p: usize, max: usize) -> LabelItems {
let mut items = LabelItems {
count: 0,
ends: [0; 61],
is_l: [false; 61],
};
let mut e = p;
while items.count < max {
let (len, is_l) = if t.get(e) == Some(&0x2D) {
(1, false)
} else {
match pseudo_letter_len(t, e) {
0 => break,
len => (len, true),
}
};
e += len;
items.ends[items.count] = e;
items.is_l[items.count] = is_l;
items.count += 1;
}
items
}
fn letter_ends(t: &[u16], p: usize, max: usize) -> Vec<usize> {
let mut ends = Vec::new();
let mut e = p;
while ends.len() < max {
match pseudo_letter_len(t, e) {
0 => break,
len => {
e += len;
ends.push(e);
}
}
}
ends
}
fn xn_label_ends(t: &[u16], a: usize) -> impl Iterator<Item = usize> {
let tail = if starts_with_ci_str(t, a, "xn--") {
t[a + 4..]
.iter()
.take(59)
.take_while(|&&c| c == 0x2D || (c < 0x80 && (c as u8).is_ascii_alphanumeric()))
.count()
} else {
0
};
(1..=tail).rev().map(move |k| a + 4 + k)
}
fn is_xn_label(t: &[u16], a: usize, end: usize) -> bool {
starts_with_ci_str(t, a, "xn--")
&& (a + 5..=a + 63).contains(&end)
&& t[a + 4..end]
.iter()
.all(|&c| c == 0x2D || (c < 0x80 && (c as u8).is_ascii_alphanumeric()))
}
fn nested_pair(t: &[u16], q: usize, open: u16, close: u16, depth: u32) -> Option<usize> {
let mut i = q + 1;
let mut rounds = 0;
while rounds < 1000 {
let Some(&c) = t.get(i) else {
break;
};
if is_zcc(c) || c == close {
break;
}
if c == open {
match (depth > 1).then(|| nested_pair(t, i, open, close, depth - 1)) {
Some(Some(end)) => i = end,
_ => break,
}
} else {
i += 1;
}
rounds += 1;
}
(t.get(i) == Some(&close)).then_some(i + 1)
}
fn quoted(t: &[u16], q: usize, quote: u16) -> Option<usize> {
let run = t[q + 1..]
.iter()
.take(100)
.take_while(|&&c| !is_zcc(c) && c != quote)
.count();
(run >= 1 && t.get(q + 1 + run) == Some("e)).then_some(run + 2)
}
fn mail_name_end(t: &[u16], p: usize) -> Option<usize> {
if !t.get(p).is_some_and(|&c| is_mail_char(c)) {
return None;
}
let mut e = p + 1;
for _ in 0..63 {
match t.get(e) {
Some(&c) if is_mail_char(c) => e += 1,
Some(&0x2E) if t.get(e + 1).is_some_and(|&c| is_mail_char(c)) => e += 1,
_ => break,
}
}
Some(e)
}
pub fn mail_name_validator(name: &[u16]) -> Option<usize> {
let n = name.len();
let mut ok = vec![true; n + 1];
for i in (0..n).rev() {
let c = name[i];
let round =
is_mail_char(c) || (c == 0x2E && name.get(i + 1).is_some_and(|&d| is_mail_char(d)));
ok[i] = round && ok[i + 1];
}
let name_from = |x: usize| x < n && is_mail_char(name[x]) && ok[x + 1] && n - x <= 64;
(0..=n).find_map(|i| {
if i == 0 && name_from(0) {
return Some(0);
}
let prefix = name
.get(i)
.is_some_and(|&c| is_sep(c) || c == 0x22 || c == 0x28 || is_zcc(c));
(prefix && name_from(i + 1)).then_some(i + 1)
})
}
fn ipv6_url_host(t: &[u16], p: usize) -> Option<usize> {
if t.get(p) != Some(&0x5B) {
return None;
}
ipv6_then_bracket(t, p + 1)
}
fn ipv6_mail_host(t: &[u16], p: usize) -> Option<usize> {
if t.get(p) != Some(&0x5B) || !starts_with_ci_str(t, p + 1, "IPv6:") {
return None;
}
ipv6_then_bracket(t, p + 6)
}
fn ipv6_then_bracket(t: &[u16], p: usize) -> Option<usize> {
let run = t[p.min(t.len())..]
.iter()
.take(46)
.take_while(|&&c| c == 0x3A || c == 0x2E || (c < 0x80 && (c as u8).is_ascii_hexdigit()))
.count();
let end = p + run;
if run > 45 || t.get(end) != Some(&0x5D) {
return None;
}
let text: String = t[p..end].iter().map(|&c| char::from(c as u8)).collect();
ipv6_address(&text).then_some(end + 1)
}
pub fn ipv6_address(text: &str) -> bool {
static RE: OnceLock<regex::Regex> = OnceLock::new();
RE.get_or_init(|| {
let h16 = "[0-9A-Fa-f]{1,4}";
let ls32 = format!("(?:(?:{h16}:{h16})|{IPV4})");
let source = format!(
"^(?:(?:{h16}:){{6}}{ls32}|::(?:{h16}:){{5}}{ls32}|(?:{h16})?::(?:{h16}:){{4}}{ls32}|(?:(?:{h16}:){{0,1}}{h16})?::(?:{h16}:){{3}}{ls32}|(?:(?:{h16}:){{0,2}}{h16})?::(?:{h16}:){{2}}{ls32}|(?:(?:{h16}:){{0,3}}{h16})?::{h16}:{ls32}|(?:(?:{h16}:){{0,4}}{h16})?::{ls32}|(?:(?:{h16}:){{0,5}}{h16})?::{h16}|(?:(?:{h16}:){{0,6}}{h16})?::)$"
);
regex::Regex::new(&source).expect("the IPv6 regex is valid")
})
.is_match(text)
}
const IPV4: &str = "(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])[.]){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
fn ipv4_address(t: &[u16], p: usize) -> Option<usize> {
let mut e = p;
for k in 0..4 {
let digits = t[e.min(t.len())..]
.iter()
.take(4)
.take_while(|&&c| is_digit(c))
.count();
let octet = &t[e..e + digits];
let valid = match digits {
1 => true,
2 => octet[0] != 0x30,
3 => {
let v = octet
.iter()
.fold(0u32, |v, &d| v * 10 + u32::from(d - 0x30));
octet[0] != 0x30 && v <= 255
}
_ => false,
};
if !valid {
return None;
}
e += digits;
if k < 3 {
if t.get(e) != Some(&0x2E) {
return None;
}
e += 1;
}
}
Some(e)
}
fn is_port(digits: &[u16]) -> bool {
match digits.len() {
1..=4 => true,
5 => match digits[0] {
0x31..=0x35 => true,
0x36 => {
digits
.iter()
.fold(0u32, |v, &d| v * 10 + u32::from(d - 0x30))
<= 65535
}
_ => false,
},
_ => false,
}
}
fn is_digit(c: u16) -> bool {
(0x30..=0x39).contains(&c)
}
pub fn is_sep(c: u16) -> bool {
c == 0x3E || c == 0x3C || c == 0xFF5C
}
fn is_z(c: u16) -> bool {
matches!(
c,
0x20 | 0xA0 | 0x1680 | 0x2000..=0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000
)
}
fn is_cc(c: u16) -> bool {
c <= 0x1F || (0x7F..=0x9F).contains(&c)
}
pub fn is_zcc(c: u16) -> bool {
is_z(c) || is_cc(c)
}
fn is_high(c: u16) -> bool {
(0xD800..=0xDBFF).contains(&c)
}
fn is_low(c: u16) -> bool {
(0xDC00..=0xDFFF).contains(&c)
}
pub fn zpcc_len(t: &[u16], p: usize) -> usize {
let Some(&c) = t.get(p) else {
return 0;
};
if is_z(c) || is_cc(c) {
return 1;
}
if is_high(c) {
return match t.get(p + 1) {
Some(&d) if is_low(d) => {
let cp = 0x10000 + ((u32::from(c) - 0xD800) << 10) + (u32::from(d) - 0xDC00);
if ucmicro::is_p(cp) { 2 } else { 0 }
}
_ => 0,
};
}
if !is_low(c) && ucmicro::is_p(u32::from(c)) {
1
} else {
0
}
}
pub fn pseudo_letter_len(t: &[u16], p: usize) -> usize {
let Some(&c) = t.get(p) else {
return 0;
};
let low_follows = t.get(p + 1).is_some_and(|&d| is_low(d));
if is_high(c) {
return if low_follows { 2 } else { 1 };
}
if !is_low(c) && !is_sep(c) && zpcc_len(t, p) == 0 {
return 1;
}
if low_follows {
2
} else if is_low(c) && p == 0 {
1
} else {
0
}
}
fn is_mail_char(c: u16) -> bool {
c < 0x80 && {
let b = c as u8;
b.is_ascii_alphanumeric() || b"-!#$%&'*+/=?^_`{|}~".contains(&b)
}
}
fn is_path_class(c: u16) -> bool {
c < 0x80 && {
let b = c as u8;
b.is_ascii_alphanumeric() || b == b'%' || b == b'/' || b == b'&'
}
}
fn is_fuzzy_prefix_symbol(c: u16) -> bool {
matches!(
c,
0x24 | 0x2B | 0x3C | 0x3D | 0x3E | 0x5E | 0x60 | 0x7C | 0xFF5C
)
}
pub fn canon(c: u16) -> u16 {
if c < 0x80 {
return (c as u8).to_ascii_uppercase().into();
}
if is_high(c) || is_low(c) {
return c;
}
match js::to_upper_case(&[c])[..] {
[u] if u >= 0x80 => u,
_ => c,
}
}
pub fn eq_ci(c: u16, p: u16) -> bool {
c == p
|| (p < 0x80 && c < 0x80 && canon(c) == canon(p))
|| (p >= 0x80 && c >= 0x80 && canon(c) == canon(p))
}
fn starts_with_ci(t: &[u16], q: usize, s: &[u16]) -> bool {
q.checked_add(s.len())
.and_then(|end| t.get(q..end))
.is_some_and(|w| w.iter().zip(s).all(|(&c, &p)| eq_ci(c, p)))
}
fn starts_with_ci_str(t: &[u16], q: usize, s: &str) -> bool {
q.checked_add(s.len())
.and_then(|end| t.get(q..end))
.is_some_and(|w| w.iter().zip(s.bytes()).all(|(&c, p)| eq_ci(c, p.into())))
}