Skip to content

Commit 5f380ec

Browse files
committed
fix panic on empty host and hostname entries
1 parent 40c7d01 commit 5f380ec

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

src/ffi.rs

+12
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ pub struct ada_string {
2222
impl ada_string {
2323
#[must_use]
2424
pub const fn as_str(&self) -> &'static str {
25+
// We need to handle length 0 since data will be `nullptr`
26+
// Not handling will result in a panic due to core::slice::from_raw_parts
27+
// implementation
28+
if self.length == 0 {
29+
return "";
30+
}
2531
unsafe {
2632
let slice = core::slice::from_raw_parts(self.data.cast(), self.length);
2733
core::str::from_utf8_unchecked(slice)
@@ -37,6 +43,12 @@ pub struct ada_owned_string {
3743

3844
impl AsRef<str> for ada_owned_string {
3945
fn as_ref(&self) -> &str {
46+
// We need to handle length 0 since data will be `nullptr`
47+
// Not handling will result in a panic due to core::slice::from_raw_parts
48+
// implementation
49+
if self.length == 0 {
50+
return "";
51+
}
4052
unsafe {
4153
let slice = core::slice::from_raw_parts(self.data.cast(), self.length);
4254
core::str::from_utf8_unchecked(slice)

src/lib.rs

+8
Original file line numberDiff line numberDiff line change
@@ -1079,4 +1079,12 @@ mod test {
10791079
assert_eq!(first.href(), "https://lemire.me/");
10801080
assert_eq!(second.href(), "https://yagiz.co/");
10811081
}
1082+
1083+
#[test]
1084+
fn should_handle_empty_host() {
1085+
// Ref: https://github.com/ada-url/rust/issues/74
1086+
let url = Url::parse("file:///C:/Users/User/Documents/example.pdf", None).unwrap();
1087+
assert_eq!(url.host(), "");
1088+
assert_eq!(url.hostname(), "");
1089+
}
10821090
}

0 commit comments

Comments
 (0)