From c89ac2540fb207830d78d55326aed48c2e14d0a0 Mon Sep 17 00:00:00 2001 From: Yagiz Nizipli Date: Tue, 3 Dec 2024 15:11:36 -0500 Subject: [PATCH] fix panic on empty host and hostname entries --- src/ffi.rs | 12 ++++++++++++ src/lib.rs | 8 ++++++++ 2 files changed, 20 insertions(+) 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(), ""); + } }