Skip to content

Commit

Permalink
feature: make possible to set port number in Uri::builder
Browse files Browse the repository at this point in the history
  • Loading branch information
Dushistov committed May 21, 2020
1 parent 59733e1 commit 4286735
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 3 deletions.
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();
}

0 comments on commit 4286735

Please sign in to comment.