mln-rs-engine 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use std::io::{self, Read, Seek, SeekFrom};
use std::path::PathBuf;
use std::sync::Arc;

use crate::storage::response::{Reason, ResourceError, Response};

/// The path bytes as they are (POSIX paths are bytes; on other platforms
/// paths are Unicode, so invalid UTF-8 is an error).
#[cfg_attr(unix, expect(clippy::unnecessary_wraps, reason = "only a non-Unix path can fail to convert"))]
pub(crate) fn path_from_utf8(path: &[u8]) -> Result<PathBuf, String> {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        Ok(PathBuf::from(std::ffi::OsStr::from_bytes(path)))
    }
    #[cfg(not(unix))]
    {
        String::from_utf8(path.to_vec()).map(PathBuf::from).map_err(|_| "Invalid UTF-8 in path".to_owned())
    }
}

/// The file at `path`, read as [`read_range`] reads it.
pub(crate) fn read_file(path: &std::path::Path, data_range: Option<(u64, u64)>) -> io::Result<Vec<u8>> {
    read_range(std::fs::File::open(path)?, data_range)
}

/// All of `file`, or the bytes `first..=last` of `data_range`, as an HTTP
/// range request reads a resource: a range that runs past the end is the
/// bytes up to the end, and one that starts at or past the end, or ends
/// before it starts, fails with [`io::ErrorKind::InvalidInput`]. `file` is
/// an open file, or anything else that reads and seeks like one.
pub(crate) fn read_range(mut file: impl Read + Seek, data_range: Option<(u64, u64)>) -> io::Result<Vec<u8>> {
    let mut data = Vec::new();
    let Some((first, last)) = data_range else {
        file.read_to_end(&mut data)?;
        return Ok(data);
    };
    if last < first {
        return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("the range {first}-{last} is inverted")));
    }
    let len = file.seek(SeekFrom::End(0))?;
    if first >= len {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("the range {first}-{last} starts past the end, {len} bytes"),
        ));
    }
    file.seek(SeekFrom::Start(first))?;
    // The range holds `last - first + 1` bytes, of which the file has the
    // ones before its end.
    file.take((last - first).saturating_add(1)).read_to_end(&mut data)?;
    Ok(data)
}

/// The file at `path`, or `data_range`'s bytes of it, or the error that
/// reading it ran into.
pub(crate) fn local_file_response(path: &[u8], data_range: Option<(u64, u64)>) -> Response {
    let mut response = Response::new();
    let path_display = String::from_utf8_lossy(path).into_owned();
    let path = match path_from_utf8(path) {
        Ok(path) => path,
        Err(message) => {
            response.error = Some(Box::new(ResourceError::new(Reason::Other, message)));
            return response;
        }
    };

    // A failure other than "not found" (e.g. a name that is too long) is
    // neither, and the read reports it.
    let status = std::fs::metadata(&path);
    let not_found = matches!(&status, Err(e) if e.kind() == io::ErrorKind::NotFound);
    let is_directory = matches!(&status, Ok(metadata) if metadata.is_dir());

    if not_found {
        response.error =
            Some(Box::new(ResourceError::new(Reason::NotFound, format!("Cannot find file {path_display}"))));
    } else if is_directory {
        response.error =
            Some(Box::new(ResourceError::new(Reason::NotFound, format!("Cannot read directory {path_display}"))));
    } else {
        match read_file(&path, data_range) {
            Ok(data) => response.data = Some(Arc::new(data)),
            Err(e) => {
                response.error =
                    Some(Box::new(ResourceError::new(Reason::Other, format!("Cannot read file {path_display}: {e}"))));
            }
        }
    }
    response
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;

    /// Reads and seeks as its cursor does, but fails every read after its
    /// first `good` bytes.
    struct Failing {
        cursor: Cursor<Vec<u8>>,
        good: u64,
    }

    impl Read for Failing {
        fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
            let left = self.good.saturating_sub(self.cursor.position());
            if left == 0 {
                return Err(io::Error::other("unreadable"));
            }
            let len = buffer.len().min(usize::try_from(left).unwrap_or(usize::MAX));
            self.cursor.read(&mut buffer[..len])
        }
    }

    impl Seek for Failing {
        fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
            self.cursor.seek(position)
        }
    }

    #[test]
    fn read_errors_fail() {
        let failing = || Failing { cursor: Cursor::new(b"0123456789".to_vec()), good: 4 };
        assert_eq!("unreadable", read_range(failing(), None).unwrap_err().to_string());
        assert_eq!("unreadable", read_range(failing(), Some((2, 8))).unwrap_err().to_string());
        assert_eq!(b"123", &read_range(failing(), Some((1, 3))).unwrap()[..]);
    }

    #[test]
    fn ranges() {
        let file = || Cursor::new(b"0123456789".to_vec());
        assert_eq!(b"0123456789", &read_range(file(), None).unwrap()[..]);
        assert_eq!(b"234", &read_range(file(), Some((2, 4))).unwrap()[..]);
        assert_eq!(b"9", &read_range(file(), Some((9, 9))).unwrap()[..]);
        assert_eq!(b"89", &read_range(file(), Some((8, 20))).unwrap()[..]);
        assert_eq!(b"0123456789", &read_range(file(), Some((0, u64::MAX))).unwrap()[..]);
        for range in [(10, 10), (11, 20), (5, 4)] {
            assert_eq!(io::ErrorKind::InvalidInput, read_range(file(), Some(range)).unwrap_err().kind(), "{range:?}");
        }
        assert_eq!(io::ErrorKind::InvalidInput, read_range(Cursor::new(Vec::new()), Some((0, 0))).unwrap_err().kind());
    }
}