Skip to content

feature: make possible to set port number in Uri::builder #422

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 34 additions & 3 deletions src/uri/builder.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use std::convert::{TryFrom, TryInto};
use std::{
convert::{TryFrom, TryInto},
fmt::Write,
};

use super::{Authority, Parts, PathAndQuery, Scheme};
use crate::Uri;
use super::{Authority, ErrorKind, InvalidUriParts, Parts, PathAndQuery, Scheme};
use crate::{byte_str::ByteStr, Uri};

/// A builder for `Uri`s.
///
Expand Down Expand Up @@ -78,6 +81,34 @@ impl Builder {
})
}

/// Set the port number for URI, will be part of `Authority`
pub fn port<P>(self, port: P) -> Self
where
P: Into<u16>,
{
let port: u16 = port.into();
self.map(move |mut parts| {
let prev_auth = match parts.authority.as_ref() {
Some(auth) => {
if auth.port().is_some() {
return Err(InvalidUriParts::from(ErrorKind::InvalidPort).into());
}

auth.as_str()
}
None => "",
};
// 1 for ':', 5 for port number digists
let mut auth = String::with_capacity(prev_auth.len() + 6);
auth.push_str(prev_auth);
auth.push(':');
write!(&mut auth, "{}", port).expect("write to String failed");
let data: ByteStr = auth.into();
parts.authority = Some(Authority { data });
Ok(parts)
})
}

/// Set the `PathAndQuery` for this URI.
///
/// # Examples
Expand Down
34 changes: 34 additions & 0 deletions src/uri/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,3 +517,37 @@ fn test_partial_eq_path_with_terminating_questionmark() {

assert_eq!(uri, a);
}

#[test]
fn test_uri_builder() {
assert_eq!(
"ws://localhost:8000/demo/",
Uri::builder()
.scheme("ws")
.authority("localhost")
.port(8000u16)
.path_and_query("/demo/")
.build()
.unwrap()
);

let uri = Uri::from_str("192.168.1.30:33").unwrap();
assert_eq!(33, uri.port().unwrap());
assert_eq!(
"ws://[2001:db8:1f70::999:de8:7648:6e8]:33/demo/",
Uri::builder()
.scheme("ws")
.authority("[2001:db8:1f70::999:de8:7648:6e8]")
.port(uri.port().unwrap())
.path_and_query("/demo/")
.build()
.unwrap()
);
Uri::builder()
.scheme("ws")
.authority("localhost:8000")
.port(8000u16)
.path_and_query("/demo/")
.build()
.unwrap_err();
}