Skip to content

Commit

Permalink
fix panic on empty host and hostname entries
Browse files Browse the repository at this point in the history
  • Loading branch information
anonrig committed Dec 3, 2024
1 parent 40c7d01 commit 5f380ec
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -37,6 +43,12 @@ pub struct ada_owned_string {

impl AsRef<str> 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)
Expand Down
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(), "");
}
}

0 comments on commit 5f380ec

Please sign in to comment.