use percent_encoding::{percent_decode_str, percent_encode, AsciiSet, CONTROLS};
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};
const URI_ESC_CHARSET: &AsciiSet = &CONTROLS.add(b' ').add(b'<').add(b'>').add(b'"');
#[cfg(unix)]
fn path_from_bytes(bytes: &[u8]) -> &std::ffi::OsStr {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
OsStr::from_bytes(bytes)
}
#[cfg(not(unix))]
fn path_from_bytes(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
pub fn resolve_uri(uri_path: &str, root: &Path) -> Result<PathBuf, Error> {
let uri_path = uri_path.strip_prefix('/').ok_or(ErrorKind::InvalidInput)?;
let uri_path = uri_path.strip_suffix('/').unwrap_or(uri_path);
let mut path = root.to_path_buf();
for component in uri_path.split('/') {
let decoded = percent_decode_str(component).collect::<Vec<_>>();
path.push(path_from_bytes(&decoded))
}
let path = path.canonicalize()?;
if path.starts_with(root) {
Ok(path)
} else {
Err(ErrorKind::InvalidData.into())
}
}
pub fn path_to_uri(path: &Path, root: &Path) -> Option<String> {
let rel_path = path.strip_prefix(root).ok()?;
let mut uri = String::from('/');
for component in rel_path.components() {
uri.push_str(
&percent_encode(component.as_os_str().as_encoded_bytes(), URI_ESC_CHARSET).to_string(),
);
uri.push('/');
}
if !path.is_dir() && uri.len() > 1 {
uri.pop();
}
Some(uri)
}