//! Small encoders the server needs: base64 for image content and the //! percent-encoding of buffer paths in `lutra://buffer/` resource URIs. /// The scheme and authority of buffer resources. pub const BUFFER_URI_PREFIX: &str = "lutra://buffer/"; /// The standard base64 alphabet. const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// Encodes `bytes` as standard base64 with padding. pub fn base64(bytes: &[u8]) -> String { let mut out = String::with_capacity(bytes.len().div_ceil(3).saturating_mul(4)); let symbol = |index: u32| char::from(BASE64.get((index & 63) as usize).copied().unwrap_or(b'A')); for chunk in bytes.chunks(3) { let b = |i: usize| u32::from(chunk.get(i).copied().unwrap_or(0)); let n = (b(0) << 16) | (b(1) << 8) | b(2); out.push(symbol(n >> 18)); out.push(symbol(n >> 12)); out.push(if chunk.len() > 1 { symbol(n >> 6) } else { '=' }); out.push(if chunk.len() > 2 { symbol(n) } else { '=' }); } out } /// Whether `b` stays as it is in a path segment of a buffer URI /// (RFC 3986 unreserved characters). fn unreserved(b: u8) -> bool { b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') } /// The resource URI of the buffer with project-relative `path` /// (`/`-separated): every byte outside the unreserved set is /// percent-encoded, slashes stay. pub fn buffer_uri(path: &str) -> String { let mut uri = String::from(BUFFER_URI_PREFIX); for b in path.bytes() { if unreserved(b) || b == b'/' { uri.push(char::from(b)); } else { uri.push_str(&format!("%{b:02X}")); } } uri } /// The project-relative path named by a buffer resource URI. /// /// # Returns /// `None` for another scheme, an empty path, a bad percent escape, or a /// path that is not UTF-8. pub fn buffer_path(uri: &str) -> Option { let encoded = uri.strip_prefix(BUFFER_URI_PREFIX)?; if encoded.is_empty() { return None; } let mut bytes = Vec::with_capacity(encoded.len()); let mut rest = encoded.bytes(); while let Some(b) = rest.next() { if b == b'%' { let hi = hex(rest.next()?)?; let lo = hex(rest.next()?)?; bytes.push((hi << 4) | lo); } else { bytes.push(b); } } String::from_utf8(bytes).ok() } /// The value of one hex digit. fn hex(b: u8) -> Option { char::from(b) .to_digit(16) .and_then(|d| u8::try_from(d).ok()) } #[cfg(test)] mod tests { use proptest::prelude::*; use super::*; #[test] fn encodes_base64() { assert_eq!(base64(b""), ""); assert_eq!(base64(b"f"), "Zg=="); assert_eq!(base64(b"fo"), "Zm8="); assert_eq!(base64(b"foo"), "Zm9v"); assert_eq!(base64(b"foobar"), "Zm9vYmFy"); assert_eq!(base64(&[0xff, 0xfe, 0x00]), "//4A"); } #[test] fn encodes_buffer_uris() { assert_eq!(buffer_uri("src/a.php"), "lutra://buffer/src/a.php"); assert_eq!( buffer_uri("my dir/ä#?.php"), "lutra://buffer/my%20dir/%C3%A4%23%3F.php" ); assert_eq!( buffer_path("lutra://buffer/my%20dir/%c3%a4.php").as_deref(), Some("my dir/ä.php") ); assert_eq!(buffer_path("lutra://buffer/"), None); assert_eq!(buffer_path("file:///a.php"), None); assert_eq!(buffer_path("lutra://buffer/%zz"), None); assert_eq!(buffer_path("lutra://buffer/%4"), None); assert_eq!(buffer_path("lutra://buffer/%ff"), None); } proptest! { #[test] fn buffer_uris_round_trip(path in "[^\\x00]{1,40}") { prop_assert_eq!(buffer_path(&buffer_uri(&path)), Some(path)); } #[test] fn buffer_path_never_panics(uri in ".{0,60}") { let _ = buffer_path(&uri); let _ = buffer_path(&format!("{BUFFER_URI_PREFIX}{uri}")); } #[test] fn base64_has_the_right_length(bytes in proptest::collection::vec(any::(), 0..100)) { let text = base64(&bytes); prop_assert_eq!(text.len(), bytes.len().div_ceil(3) * 4); } } }