mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use std::path::{Path, PathBuf};

use super::{answer, fixture, temp_path};
use crate::storage::constants::FILE_PROTOCOL;
use crate::storage::file_source::FileSource;
use crate::storage::local_file_source::LocalFileSource;
use crate::storage::resource::{Kind, Resource};
use crate::storage::response::{Reason, Response};

/// A `file://` URL for `path`, percent-encoding everything but unreserved
/// characters, '/' and ':'.
fn file_url(path: &Path) -> String {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    let bytes = path.as_os_str().as_encoded_bytes();
    let mut encoded = String::new();
    for &byte in bytes {
        if byte.is_ascii_alphanumeric() || b"-._~/:".contains(&byte) {
            encoded.push(byte as char);
        } else {
            encoded.push('%');
            encoded.push(HEX[(byte >> 4) as usize] as char);
            encoded.push(HEX[(byte & 0xF) as usize] as char);
        }
    }

    format!("{FILE_PROTOCOL}{}{encoded}", if encoded.starts_with('/') { "" } else { "/" })
}

fn assets() -> PathBuf {
    fixture("storage/assets")
}

/// The `file://` URL of the asset fixture `file_name`.
fn asset_url(file_name: &str) -> String {
    let mut path = assets().into_os_string();
    path.push("/");
    path.push(file_name);
    file_url(Path::new(&path))
}

fn local_file_source() -> LocalFileSource {
    LocalFileSource::new(super::pool())
}

/// The data of `res`, or its error's reason and message.
fn outcome(res: &Response) -> Result<&[u8], (Reason, &str)> {
    match (&res.error, &res.data) {
        (None, Some(data)) => Ok(data),
        (Some(error), None) => Err((error.reason, &error.message)),
        _ => panic!("{res:?}"),
    }
}

#[test]
fn it_loads_file_urls() {
    let fs = local_file_source();
    for url in ["file://empty", "file:///test"] {
        assert!(fs.can_request(&Resource::style(url)), "{url}");
    }
    for url in ["flie://foo", "file:", "style.json", ""] {
        assert!(!fs.can_request(&Resource::style(url)), "{url}");
    }
}

/// A file's bytes, or the range of them asked for, or an error that says
/// why there are none.
#[test]
fn a_file_url_answers_with_the_files_bytes_or_an_error() {
    type Case<'a> = (String, Option<(u64, u64)>, Result<&'a str, (Reason, &'a str)>);
    let content = "content is here\n";
    let directory = asset_url("directory");
    let missing = asset_url("does_not_exist");
    let percent_encoded = format!("{}%6eonempty", asset_url(""));
    // PATH_MAX on Linux.
    let too_long = asset_url(&"x".repeat(4096 - asset_url("").len()));
    // On Windows invalid UTF-8 fails the path's conversion; elsewhere the
    // path isn't found.
    let invalid_utf8 = "file:///C:/%FF.json".to_owned();
    let cases: [Case<'_>; 13] = [
        (asset_url("empty"), None, Ok("")),
        (asset_url("nonempty"), None, Ok(content)),
        (percent_encoded, None, Ok(content)),
        (asset_url("nonempty"), Some((4, 12)), Ok("ent is he")),
        // A range that runs past the end is the bytes up to the end.
        (asset_url("nonempty"), Some((12, 20)), Ok("ere\n")),
        (asset_url("nonempty"), Some((4, u64::MAX)), Ok("ent is here\n")),
        // One that starts at or past the end, or ends before it starts,
        // fails.
        (asset_url("nonempty"), Some((16, 20)), Err((Reason::Other, "Cannot read file "))),
        (asset_url("nonempty"), Some((12, 4)), Err((Reason::Other, "Cannot read file "))),
        (missing.clone(), None, Err((Reason::NotFound, "Cannot find file "))),
        (directory, None, Err((Reason::NotFound, "Cannot read directory "))),
        ("test://wrong-scheme".to_owned(), None, Err((Reason::Other, "Invalid file URL"))),
        (too_long, None, Err((Reason::Other, ""))),
        (invalid_utf8, None, Err((if cfg!(unix) { Reason::NotFound } else { Reason::Other }, ""))),
    ];
    let fs = local_file_source();
    for (url, range, expected) in cases {
        let mut resource = Resource::new(Kind::Unknown, url.clone());
        resource.data_range = range;
        let res = answer(&fs, &resource);
        match (outcome(&res), expected) {
            (Ok(data), Ok(expected)) => assert_eq!(expected.as_bytes(), data, "{url} {range:?}"),
            (Err((reason, message)), Err((expected, prefix))) => {
                assert_eq!(expected, reason, "{url} {range:?}");
                assert!(message.starts_with(prefix), "{url} {range:?}: {message}");
            }
            (outcome, expected) => panic!("{url} {range:?}: {outcome:?}, not {expected:?}"),
        }
    }
    let res = answer(&fs, &Resource::new(Kind::Unknown, missing));
    assert!(res.error.unwrap().message.ends_with("does_not_exist"));
}

#[test]
fn a_path_of_any_script_loads() {
    let temp = temp_path("non-ascii");
    let directory = PathBuf::from(&*temp).join("ké 地図");
    std::fs::create_dir_all(&directory).unwrap();
    let file = directory.join("スタイル.json");
    std::fs::write(&file, "content is here\n").unwrap();

    let res = answer(&local_file_source(), &Resource::style(&file_url(&file)));
    assert_eq!(Ok(&b"content is here\n"[..]), outcome(&res));
}