use std::path::{Path, PathBuf};
use std::str::FromStr;
use lsp_types::Uri;
pub(super) fn uri_to_path(uri: &Uri) -> Option<PathBuf> {
let s = uri.as_str();
let rest = s.strip_prefix("file://")?;
let path = &rest[rest.find('/')?..];
let decoded = percent_decode(path)?;
let b = decoded.as_bytes();
let decoded = if b.len() >= 3 && b[0] == b'/' && b[1].is_ascii_alphabetic() && b[2] == b':' {
decoded[1..].to_string()
} else {
decoded
};
Some(PathBuf::from(decoded))
}
pub(super) fn path_to_uri(path: &Path) -> Option<Uri> {
let s = path.to_str()?.replace('\\', "/");
let s = if s.starts_with('/') {
s
} else {
format!("/{s}")
};
let mut out = String::from("file://");
for b in s.bytes() {
if b.is_ascii_alphanumeric() || b"/-._~:".contains(&b) {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
Uri::from_str(&out).ok()
}
fn percent_decode(s: &str) -> Option<String> {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
if b[i] == b'%' {
let h = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
out.push(u8::from_str_radix(h, 16).ok()?);
i += 3;
} else {
out.push(b[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}