use crate::markdown_it::js;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Url {
pub protocol: Option<Vec<u16>>,
pub slashes: Option<bool>,
pub auth: Option<Vec<u16>>,
pub port: Option<Vec<u16>>,
pub hostname: Option<Vec<u16>>,
pub hash: Option<Vec<u16>>,
pub search: Option<Vec<u16>>,
pub pathname: Option<Vec<u16>>,
}
const NON_HOST_CHARS: [u8; 20] = [
b'%', b'/', b'?', b';', b'#', b'\'', b'{', b'}', b'|', b'\\', b'^', b'`', b'<', b'>', b'"', b'`', b' ', b'\r', b'\n', b'\t', ];
const HOST_ENDING_CHARS: [u8; 3] = *b"/?#";
const HOSTNAME_MAX_LEN: usize = 255;
fn hostless_protocol(proto: Option<&[u16]>) -> bool {
proto.is_some_and(|p| ["javascript", "javascript:"].iter().any(|k| eq(p, k)))
}
fn slashed_protocol(proto: Option<&[u16]>) -> bool {
proto.is_some_and(|p| {
[
"http", "https", "ftp", "gopher", "file", "http:", "https:", "ftp:", "gopher:", "file:",
]
.iter()
.any(|k| eq(p, k))
})
}
fn eq(s: &[u16], ascii: &str) -> bool {
s.len() == ascii.len() && s.iter().zip(ascii.bytes()).all(|(&a, b)| a == u16::from(b))
}
fn is(c: u16, ascii: u8) -> bool {
c == u16::from(ascii)
}
fn is_hostname_char(c: u16) -> bool {
c < 0x80 && {
let b = c as u8;
b.is_ascii_alphanumeric() || b == b'+' || b == b'_' || b == b'-'
}
}
fn is_line_terminator(c: u16) -> bool {
matches!(c, 0x0A | 0x0D | 0x2028 | 0x2029)
}
fn protocol_pattern(rest: &[u16]) -> Option<&[u16]> {
let n = rest
.iter()
.take_while(|&&c| {
c < 0x80 && {
let b = c as u8;
b.is_ascii_alphanumeric() || b == b'.' || b == b'+' || b == b'-'
}
})
.count();
if n >= 1 && rest.get(n).is_some_and(|&c| is(c, b':')) {
Some(&rest[..n + 1])
} else {
None
}
}
fn port_pattern(host: &[u16]) -> Option<&[u16]> {
let colon = host.iter().rposition(|&c| is(c, b':'))?;
if host[colon + 1..]
.iter()
.all(|&c| c < 0x80 && (c as u8).is_ascii_digit())
{
Some(&host[colon..])
} else {
None
}
}
fn simple_path_pattern(rest: &[u16]) -> Option<(&[u16], Option<&[u16]>)> {
if !rest.first().is_some_and(|&c| is(c, b'/')) {
return None;
}
let mut k = 1;
if rest.get(1).is_some_and(|&c| is(c, b'/')) {
if rest.get(2).is_some_and(|&c| is(c, b'/')) {
return None;
}
k = 2;
}
let e = k + rest[k..]
.iter()
.take_while(|&&c| !is(c, b'?') && !js::is_js_space(u32::from(c)))
.count();
if e == rest.len() {
return Some((&rest[..e], None));
}
if is(rest[e], b'?')
&& rest[e + 1..]
.iter()
.all(|&c| !js::is_js_space(u32::from(c)))
{
return Some((&rest[..e], Some(&rest[e..])));
}
None
}
fn slashes_auth_pattern(rest: &[u16]) -> bool {
if !(rest.len() >= 2 && is(rest[0], b'/') && is(rest[1], b'/')) {
return false;
}
let not_at_or_slash = |c: u16| !is(c, b'@') && !is(c, b'/');
let a = 2 + rest[2..]
.iter()
.take_while(|&&c| not_at_or_slash(c))
.count();
a > 2
&& rest.get(a).is_some_and(|&c| is(c, b'@'))
&& rest.get(a + 1).is_some_and(|&c| not_at_or_slash(c))
}
fn hostname_part_pattern(part: &[u16]) -> bool {
part.len() <= 63 && part.iter().all(|&c| is_hostname_char(c))
}
fn hostname_part_start(part: &[u16]) -> Option<(&[u16], &[u16])> {
if part.iter().any(|&c| is_line_terminator(c)) {
return None;
}
let n = part
.iter()
.take(63)
.take_while(|&&c| is_hostname_char(c))
.count();
Some((&part[..n], &part[n..]))
}
fn index_of(s: &[u16], c: u8) -> i64 {
js::index_of(s, &[u16::from(c)], 0).map_or(-1, |i| i as i64)
}
fn last_index_of(s: &[u16], c: u8, from: Option<usize>) -> i64 {
js::last_index_of(s, &[u16::from(c)], from).map_or(-1, |i| i as i64)
}
fn join_dots(parts: &[Vec<u16>]) -> Vec<u16> {
let mut out = Vec::new();
for (i, part) in parts.iter().enumerate() {
if i > 0 {
out.push(u16::from(b'.'));
}
out.extend_from_slice(part);
}
out
}
pub fn parse(url: &[u16], slashes_denote_host: bool) -> Url {
let mut u = Url::default();
u.parse(url, slashes_denote_host);
u
}
impl Url {
fn parse(&mut self, url: &[u16], slashes_denote_host: bool) -> &mut Self {
let mut lower_proto: Option<Vec<u16>> = None;
let mut slashes = false;
let mut rest: Vec<u16> = url.to_vec();
rest = js::trim(&rest).to_vec();
if !slashes_denote_host && js::split(url, &[u16::from(b'#')]).len() == 1 {
let simple_path = simple_path_pattern(&rest);
if let Some((path, search)) = simple_path {
self.pathname = Some(path.to_vec());
if let Some(search) = search.filter(|s| !s.is_empty()) {
self.search = Some(search.to_vec());
}
return self;
}
}
let proto: Option<Vec<u16>> = protocol_pattern(&rest).map(<[u16]>::to_vec);
if let Some(proto) = &proto {
lower_proto = Some(js::to_lower_case(proto));
self.protocol = Some(proto.clone());
rest = js::substr(&rest, proto.len() as i64, None).to_vec();
}
let proto = proto.as_deref();
if slashes_denote_host || proto.is_some() || slashes_auth_pattern(&rest) {
slashes = js::substr(&rest, 0, Some(2)) == js::to_utf16("//").as_slice();
if slashes && !(proto.is_some() && hostless_protocol(proto)) {
rest = js::substr(&rest, 2, None).to_vec();
self.slashes = Some(true);
}
}
if !hostless_protocol(proto) && (slashes || (proto.is_some() && !slashed_protocol(proto))) {
let mut host_end: i64 = -1;
for i in 0..HOST_ENDING_CHARS.len() {
let hec = index_of(&rest, HOST_ENDING_CHARS[i]);
if hec != -1 && (host_end == -1 || hec < host_end) {
host_end = hec;
}
}
let at_sign: i64;
if host_end == -1 {
at_sign = last_index_of(&rest, b'@', None);
} else {
at_sign = last_index_of(&rest, b'@', Some(host_end as usize));
}
if at_sign != -1 {
let auth = js::slice(&rest, 0, Some(at_sign)).to_vec();
rest = js::slice(&rest, at_sign + 1, None).to_vec();
self.auth = Some(auth);
}
host_end = -1;
for i in 0..NON_HOST_CHARS.len() {
let hec = index_of(&rest, NON_HOST_CHARS[i]);
if hec != -1 && (host_end == -1 || hec < host_end) {
host_end = hec;
}
}
if host_end == -1 {
host_end = rest.len() as i64;
}
if host_end >= 1 && is(rest[(host_end - 1) as usize], b':') {
host_end -= 1;
}
let host = js::slice(&rest, 0, Some(host_end)).to_vec();
rest = js::slice(&rest, host_end, None).to_vec();
self.parse_host(&host);
let mut hostname: Vec<u16> = self.hostname.take().unwrap_or_default();
let ipv6_hostname = hostname.first().is_some_and(|&c| is(c, b'['))
&& hostname.last().is_some_and(|&c| is(c, b']'));
if !ipv6_hostname {
let hostparts: Vec<Vec<u16>> = js::split(&hostname, &[u16::from(b'.')])
.into_iter()
.map(<[u16]>::to_vec)
.collect();
let l = hostparts.len();
for i in 0..l {
let part = &hostparts[i];
if part.is_empty() {
continue;
}
if !hostname_part_pattern(part) {
let mut newpart: Vec<u16> = Vec::new();
let k = part.len();
for j in 0..k {
if part[j] > 127 {
newpart.push(u16::from(b'x'));
} else {
newpart.push(part[j]);
}
}
if !hostname_part_pattern(&newpart) {
let mut valid_parts: Vec<Vec<u16>> = hostparts[..i].to_vec();
let mut not_host: Vec<Vec<u16>> = hostparts[i + 1..].to_vec();
let bit = hostname_part_start(part);
if let Some((bit1, bit2)) = bit {
valid_parts.push(bit1.to_vec());
not_host.insert(0, bit2.to_vec());
}
if !not_host.is_empty() {
let mut joined = join_dots(¬_host);
joined.extend_from_slice(&rest);
rest = joined;
}
hostname = join_dots(&valid_parts);
break;
}
}
}
}
if hostname.len() > HOSTNAME_MAX_LEN {
hostname = Vec::new();
}
if ipv6_hostname {
hostname = js::substr(&hostname, 1, Some(hostname.len() as i64 - 2)).to_vec();
}
self.hostname = Some(hostname);
}
let hash = index_of(&rest, b'#');
if hash != -1 {
self.hash = Some(js::substr(&rest, hash, None).to_vec());
rest = js::slice(&rest, 0, Some(hash)).to_vec();
}
let qm = index_of(&rest, b'?');
if qm != -1 {
self.search = Some(js::substr(&rest, qm, None).to_vec());
rest = js::slice(&rest, 0, Some(qm)).to_vec();
}
if !rest.is_empty() {
self.pathname = Some(rest);
}
if slashed_protocol(lower_proto.as_deref())
&& self.hostname.as_ref().is_some_and(|h| !h.is_empty())
&& self.pathname.as_ref().is_none_or(|p| p.is_empty())
{
self.pathname = Some(Vec::new());
}
self
}
fn parse_host(&mut self, host: &[u16]) {
let mut host = host;
let port = port_pattern(host);
if let Some(port) = port {
if !eq(port, ":") {
self.port = Some(js::substr(port, 1, None).to_vec());
}
host = js::substr(host, 0, Some((host.len() - port.len()) as i64));
}
if !host.is_empty() {
self.hostname = Some(host.to_vec());
}
}
}