Skip to content

Commit 4624d60

Browse files
committed
refactor(hyperlink): Pull out path encoding
1 parent 289ce2a commit 4624d60

1 file changed

Lines changed: 19 additions & 15 deletions

File tree

  • crates/anstyle-hyperlink/src

crates/anstyle-hyperlink/src/file.rs

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,21 +25,7 @@ pub fn file_to_url(hostname: Option<&str>, path: &std::path::Path) -> Option<Str
2525
url.push_str(hostname);
2626
}
2727

28-
// skip the root component
29-
let mut is_path_empty = true;
30-
for component in path.components().skip(1) {
31-
is_path_empty = false;
32-
url.push_str(URL_PATH_SEP);
33-
let component = component.as_os_str().to_str()?;
34-
url.extend(percent_encoding::percent_encode(
35-
component.as_bytes(),
36-
SPECIAL_PATH_SEGMENT,
37-
));
38-
}
39-
if is_path_empty {
40-
// An URL's path must not be empty
41-
url.push_str(URL_PATH_SEP);
42-
}
28+
encode_path(path, &mut url);
4329

4430
Some(url)
4531
}
@@ -75,3 +61,21 @@ const PATH_SEGMENT: &percent_encoding::AsciiSet = &PATH.add(b'/').add(b'%');
7561
// The backslash (\) character is treated as a path separator in special URLs
7662
// so it needs to be additionally escaped in that case.
7763
const SPECIAL_PATH_SEGMENT: &percent_encoding::AsciiSet = &PATH_SEGMENT.add(b'\\');
64+
65+
fn encode_path(path: &std::path::Path, url: &mut String) {
66+
// skip the root component
67+
let mut is_path_empty = true;
68+
for component in path.components().skip(1) {
69+
is_path_empty = false;
70+
url.push_str(URL_PATH_SEP);
71+
let component = component.as_os_str().to_str()?;
72+
url.extend(percent_encoding::percent_encode(
73+
component.as_bytes(),
74+
SPECIAL_PATH_SEGMENT,
75+
));
76+
}
77+
if is_path_empty {
78+
// An URL's path must not be empty
79+
url.push_str(URL_PATH_SEP);
80+
}
81+
}

0 commit comments

Comments
 (0)