diff --git a/src/ffi.rs b/src/ffi.rs index a7bab7d..a61bfad 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -22,6 +22,12 @@ pub struct ada_string { impl ada_string { #[must_use] pub const fn as_str(&self) -> &'static str { + // We need to handle length 0 since data will be `nullptr` + // Not handling will result in a panic due to core::slice::from_raw_parts + // implementation + if self.length == 0 { + return ""; + } unsafe { let slice = core::slice::from_raw_parts(self.data.cast(), self.length); core::str::from_utf8_unchecked(slice) @@ -37,6 +43,12 @@ pub struct ada_owned_string { impl AsRef for ada_owned_string { fn as_ref(&self) -> &str { + // We need to handle length 0 since data will be `nullptr` + // Not handling will result in a panic due to core::slice::from_raw_parts + // implementation + if self.length == 0 { + return ""; + } unsafe { let slice = core::slice::from_raw_parts(self.data.cast(), self.length); core::str::from_utf8_unchecked(slice) diff --git a/src/lib.rs b/src/lib.rs index d944c5f..04bf111 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1079,4 +1079,12 @@ mod test { assert_eq!(first.href(), "https://lemire.me/"); assert_eq!(second.href(), "https://yagiz.co/"); } + + #[test] + fn should_handle_empty_host() { + // Ref: https://github.com/ada-url/rust/issues/74 + let url = Url::parse("file:///C:/Users/User/Documents/example.pdf", None).unwrap(); + assert_eq!(url.host(), ""); + assert_eq!(url.hostname(), ""); + } }