Skip to content

Commit ef1a33d

Browse files
committed
Replace () error types in several functions.
This is an initial pass at #299. It does not change `ParseError` to the more idiomatic `Error` name, or change `with_default_port`'s return type.
1 parent 788dffb commit ef1a33d

File tree

4 files changed

+45
-41
lines changed

4 files changed

+45
-41
lines changed

src/lib.rs

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1467,10 +1467,10 @@ impl Url {
14671467
/// # }
14681468
/// # run().unwrap();
14691469
/// ```
1470-
pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
1470+
pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ParseError> {
14711471
// has_host implies !cannot_be_a_base
14721472
if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
1473-
return Err(())
1473+
return Err(ParseError::EmptyHost)
14741474
}
14751475
if port.is_some() && port == parser::default_port(self.scheme()) {
14761476
port = None
@@ -1697,9 +1697,9 @@ impl Url {
16971697
/// # run().unwrap();
16981698
/// ```
16991699
///
1700-
pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
1700+
pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ParseError> {
17011701
if self.cannot_be_a_base() {
1702-
return Err(())
1702+
return Err(ParseError::SetHostOnCannotBeABaseUrl)
17031703
}
17041704

17051705
let address = match address {
@@ -1736,10 +1736,10 @@ impl Url {
17361736
/// # }
17371737
/// # run().unwrap();
17381738
/// ```
1739-
pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
1739+
pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ParseError> {
17401740
// has_host implies !cannot_be_a_base
17411741
if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
1742-
return Err(())
1742+
return Err(ParseError::EmptyHost)
17431743
}
17441744
if let Some(password) = password {
17451745
let host_and_after = self.slice(self.host_start..).to_owned();
@@ -1818,10 +1818,10 @@ impl Url {
18181818
/// # }
18191819
/// # run().unwrap();
18201820
/// ```
1821-
pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
1821+
pub fn set_username(&mut self, username: &str) -> Result<(), ParseError> {
18221822
// has_host implies !cannot_be_a_base
18231823
if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
1824-
return Err(())
1824+
return Err(ParseError::EmptyHost)
18251825
}
18261826
let username_start = self.scheme_end + 3;
18271827
debug_assert!(self.slice(self.scheme_end..username_start) == "://");
@@ -1922,12 +1922,12 @@ impl Url {
19221922
/// # }
19231923
/// # run().unwrap();
19241924
/// ```
1925-
pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
1925+
pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ParseError> {
19261926
let mut parser = Parser::for_setter(String::new());
19271927
let remaining = parser.parse_scheme(parser::Input::new(scheme))?;
19281928
if !remaining.is_empty() ||
19291929
(!self.has_host() && SchemeType::from(&parser.serialization).is_special()) {
1930-
return Err(())
1930+
return Err(ParseError::InvalidScheme)
19311931
}
19321932
let old_scheme_end = self.scheme_end;
19331933
let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
@@ -1962,7 +1962,7 @@ impl Url {
19621962
/// # if cfg!(unix) {
19631963
/// use url::Url;
19641964
///
1965-
/// # fn run() -> Result<(), ()> {
1965+
/// # fn run() -> Result<(), url::ParseError> {
19661966
/// let url = Url::from_file_path("/tmp/foo.txt")?;
19671967
/// assert_eq!(url.as_str(), "file:///tmp/foo.txt");
19681968
///
@@ -1977,7 +1977,7 @@ impl Url {
19771977
/// # }
19781978
/// ```
19791979
#[cfg(any(unix, windows, target_os="redox"))]
1980-
pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
1980+
pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ParseError> {
19811981
let mut serialization = "file://".to_owned();
19821982
let host_start = serialization.len() as u32;
19831983
let (host_end, host) = path_to_file_url_segments(path.as_ref(), &mut serialization)?;
@@ -2013,7 +2013,7 @@ impl Url {
20132013
/// Note that `std::path` does not consider trailing slashes significant
20142014
/// and usually does not include them (e.g. in `Path::parent()`).
20152015
#[cfg(any(unix, windows, target_os="redox"))]
2016-
pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
2016+
pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ParseError> {
20172017
let mut url = Url::from_file_path(path)?;
20182018
if !url.serialization.ends_with('/') {
20192019
url.serialization.push('/')
@@ -2088,26 +2088,26 @@ impl Url {
20882088
/// let path = url.to_file_path();
20892089
/// ```
20902090
///
2091-
/// Returns `Err` if the host is neither empty nor `"localhost"` (except on Windows, where
2091+
/// Returns `Err(ParseError::InvalidLocalPath)` if the host is neither empty nor `"localhost"` (except on Windows, where
20922092
/// `file:` URLs may have a non-local host),
20932093
/// or if `Path::new_opt()` returns `None`.
20942094
/// (That is, if the percent-decoded path contains a NUL byte or,
20952095
/// for a Windows path, is not UTF-8.)
20962096
#[inline]
20972097
#[cfg(any(unix, windows, target_os="redox"))]
2098-
pub fn to_file_path(&self) -> Result<PathBuf, ()> {
2098+
pub fn to_file_path(&self) -> Result<PathBuf, ParseError> {
20992099
if let Some(segments) = self.path_segments() {
21002100
let host = match self.host() {
21012101
None | Some(Host::Domain("localhost")) => None,
21022102
Some(_) if cfg!(windows) && self.scheme() == "file" => {
21032103
Some(&self.serialization[self.host_start as usize .. self.host_end as usize])
21042104
},
2105-
_ => return Err(())
2105+
_ => return Err(ParseError::InvalidLocalPath)
21062106
};
21072107

21082108
return file_url_segments_to_pathbuf(host, segments);
21092109
}
2110-
Err(())
2110+
Err(ParseError::InvalidLocalPath)
21112111
}
21122112

21132113
// Private helper methods:
@@ -2268,10 +2268,10 @@ impl serde::Deserialize for Url {
22682268

22692269
#[cfg(any(unix, target_os = "redox"))]
22702270
fn path_to_file_url_segments(path: &Path, serialization: &mut String)
2271-
-> Result<(u32, HostInternal), ()> {
2271+
-> Result<(u32, HostInternal), ParseError> {
22722272
use std::os::unix::prelude::OsStrExt;
22732273
if !path.is_absolute() {
2274-
return Err(())
2274+
return Err(ParseError::PathNotAbsolute)
22752275
}
22762276
let host_end = to_u32(serialization.len()).unwrap();
22772277
let mut empty = true;
@@ -2343,13 +2343,13 @@ fn path_to_file_url_segments_windows(path: &Path, serialization: &mut String)
23432343

23442344

23452345
#[cfg(any(unix, target_os = "redox"))]
2346-
fn file_url_segments_to_pathbuf(host: Option<&str>, segments: str::Split<char>) -> Result<PathBuf, ()> {
2346+
fn file_url_segments_to_pathbuf(host: Option<&str>, segments: str::Split<char>) -> Result<PathBuf, ParseError> {
23472347
use std::ffi::OsStr;
23482348
use std::os::unix::prelude::OsStrExt;
23492349
use std::path::PathBuf;
23502350

23512351
if host.is_some() {
2352-
return Err(());
2352+
return Err(ParseError::InvalidLocalPath);
23532353
}
23542354

23552355
let mut bytes = if cfg!(target_os = "redox") {

src/parser.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,16 @@ simple_enum_error! {
5656
EmptyHost => "empty host",
5757
IdnaError => "invalid international domain name",
5858
InvalidPort => "invalid port number",
59+
InvalidScheme => "invalid scheme",
5960
InvalidIpv4Address => "invalid IPv4 address",
6061
InvalidIpv6Address => "invalid IPv6 address",
6162
InvalidDomainCharacter => "invalid domain character",
6263
RelativeUrlWithoutBase => "relative URL without a base",
6364
RelativeUrlWithCannotBeABaseBase => "relative URL with a cannot-be-a-base base",
6465
SetHostOnCannotBeABaseUrl => "a cannot-be-a-base URL doesn’t have a host to set",
6566
Overflow => "URLs more than 4 GB are not supported",
67+
InvalidLocalPath => "the url is not a valid local path",
68+
PathNotAbsolute => "path component of url is not absolute",
6669
}
6770

6871
#[cfg(feature = "heapsize")]
@@ -372,9 +375,9 @@ impl<'a> Parser<'a> {
372375
}
373376
}
374377

375-
pub fn parse_scheme<'i>(&mut self, mut input: Input<'i>) -> Result<Input<'i>, ()> {
378+
pub fn parse_scheme<'i>(&mut self, mut input: Input<'i>) -> Result<Input<'i>, ParseError> {
376379
if input.is_empty() || !input.starts_with(ascii_alpha) {
377-
return Err(())
380+
return Err(ParseError::InvalidScheme)
378381
}
379382
debug_assert!(self.serialization.is_empty());
380383
while let Some(c) = input.next() {
@@ -385,7 +388,7 @@ impl<'a> Parser<'a> {
385388
':' => return Ok(input),
386389
_ => {
387390
self.serialization.clear();
388-
return Err(())
391+
return Err(ParseError::InvalidScheme)
389392
}
390393
}
391394
}
@@ -394,7 +397,7 @@ impl<'a> Parser<'a> {
394397
Ok(input)
395398
} else {
396399
self.serialization.clear();
397-
Err(())
400+
Err(ParseError::InvalidScheme)
398401
}
399402
}
400403

src/quirks.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ pub fn protocol(url: &Url) -> &str {
5656
}
5757

5858
/// Setter for https://url.spec.whatwg.org/#dom-url-protocol
59-
pub fn set_protocol(url: &mut Url, mut new_protocol: &str) -> Result<(), ()> {
59+
pub fn set_protocol(url: &mut Url, mut new_protocol: &str) -> Result<(), ParseError> {
6060
// The scheme state in the spec ignores everything after the first `:`,
6161
// but `set_scheme` errors if there is more.
6262
if let Some(position) = new_protocol.find(':') {
@@ -72,7 +72,7 @@ pub fn username(url: &Url) -> &str {
7272
}
7373

7474
/// Setter for https://url.spec.whatwg.org/#dom-url-username
75-
pub fn set_username(url: &mut Url, new_username: &str) -> Result<(), ()> {
75+
pub fn set_username(url: &mut Url, new_username: &str) -> Result<(), ParseError> {
7676
url.set_username(new_username)
7777
}
7878

@@ -83,7 +83,7 @@ pub fn password(url: &Url) -> &str {
8383
}
8484

8585
/// Setter for https://url.spec.whatwg.org/#dom-url-password
86-
pub fn set_password(url: &mut Url, new_password: &str) -> Result<(), ()> {
86+
pub fn set_password(url: &mut Url, new_password: &str) -> Result<(), ParseError> {
8787
url.set_password(if new_password.is_empty() { None } else { Some(new_password) })
8888
}
8989

tests/unit.rs

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use std::borrow::Cow;
1616
use std::cell::{Cell, RefCell};
1717
use std::net::{Ipv4Addr, Ipv6Addr};
1818
use std::path::{Path, PathBuf};
19-
use url::{Host, HostAndPort, Url, form_urlencoded};
19+
use url::{Host, HostAndPort, Url, form_urlencoded, ParseError};
2020

2121
#[test]
2222
fn size() {
@@ -39,14 +39,14 @@ macro_rules! assert_from_file_path {
3939
#[test]
4040
fn new_file_paths() {
4141
if cfg!(unix) {
42-
assert_eq!(Url::from_file_path(Path::new("relative")), Err(()));
43-
assert_eq!(Url::from_file_path(Path::new("../relative")), Err(()));
42+
assert_eq!(Url::from_file_path(Path::new("relative")), Err(ParseError::PathNotAbsolute));
43+
assert_eq!(Url::from_file_path(Path::new("../relative")), Err(ParseError::PathNotAbsolute));
4444
}
4545
if cfg!(windows) {
46-
assert_eq!(Url::from_file_path(Path::new("relative")), Err(()));
47-
assert_eq!(Url::from_file_path(Path::new(r"..\relative")), Err(()));
48-
assert_eq!(Url::from_file_path(Path::new(r"\drive-relative")), Err(()));
49-
assert_eq!(Url::from_file_path(Path::new(r"\\ucn\")), Err(()));
46+
assert_eq!(Url::from_file_path(Path::new("relative")), Err(ParseError::PathNotAbsolute));
47+
assert_eq!(Url::from_file_path(Path::new(r"..\relative")), Err(ParseError::PathNotAbsolute));
48+
assert_eq!(Url::from_file_path(Path::new(r"\drive-relative")), Err(ParseError::PathNotAbsolute));
49+
assert_eq!(Url::from_file_path(Path::new(r"\\ucn\")), Err(ParseError::PathNotAbsolute));
5050
}
5151

5252
if cfg!(unix) {
@@ -89,19 +89,20 @@ fn new_path_windows_fun() {
8989

9090
#[test]
9191
fn new_directory_paths() {
92+
use url::ParseError;
9293
if cfg!(unix) {
93-
assert_eq!(Url::from_directory_path(Path::new("relative")), Err(()));
94-
assert_eq!(Url::from_directory_path(Path::new("../relative")), Err(()));
94+
assert_eq!(Url::from_directory_path(Path::new("relative")), Err(ParseError::PathNotAbsolute));
95+
assert_eq!(Url::from_directory_path(Path::new("../relative")), Err(ParseError::PathNotAbsolute));
9596

9697
let url = Url::from_directory_path(Path::new("/foo/bar")).unwrap();
9798
assert_eq!(url.host(), None);
9899
assert_eq!(url.path(), "/foo/bar/");
99100
}
100101
if cfg!(windows) {
101-
assert_eq!(Url::from_directory_path(Path::new("relative")), Err(()));
102-
assert_eq!(Url::from_directory_path(Path::new(r"..\relative")), Err(()));
103-
assert_eq!(Url::from_directory_path(Path::new(r"\drive-relative")), Err(()));
104-
assert_eq!(Url::from_directory_path(Path::new(r"\\ucn\")), Err(()));
102+
assert_eq!(Url::from_directory_path(Path::new("relative")), Err(ParseError::PathNotAbsolute));
103+
assert_eq!(Url::from_directory_path(Path::new(r"..\relative")), Err(ParseError::PathNotAbsolute));
104+
assert_eq!(Url::from_directory_path(Path::new(r"\drive-relative")), Err(ParseError::PathNotAbsolute));
105+
assert_eq!(Url::from_directory_path(Path::new(r"\\ucn\")), Err(ParseError::PathNotAbsolute));
105106

106107
let url = Url::from_directory_path(Path::new(r"C:\foo\bar")).unwrap();
107108
assert_eq!(url.host(), None);

0 commit comments

Comments
 (0)