Use base64 to fully encode basic auth creds

Change basic_auth to use less allocations
This commit is contained in:
Douman
2018-07-27 22:39:09 +03:00
committed by Sean McArthur
parent 12cfbafc28
commit a25f62f4cb
2 changed files with 14 additions and 10 deletions

View File

@@ -123,12 +123,14 @@ impl RequestBuilder {
/// Enable HTTP basic authentication. /// Enable HTTP basic authentication.
pub fn basic_auth<U, P>(&mut self, username: U, password: Option<P>) -> &mut RequestBuilder pub fn basic_auth<U, P>(&mut self, username: U, password: Option<P>) -> &mut RequestBuilder
where where
U: Into<String>, U: fmt::Display,
P: Into<String>, P: fmt::Display,
{ {
let username = username.into(); let auth = match password {
let password = password.map(|p| p.into()).unwrap_or(String::new()); Some(password) => format!("{}:{}", username, password),
let header_value = format!("basic {}:{}", username, encode(&password)); None => format!("{}:", username)
};
let header_value = format!("basic {}", encode(&auth));
self.header(::header::AUTHORIZATION, HeaderValue::from_str(header_value.as_str()).expect("")) self.header(::header::AUTHORIZATION, HeaderValue::from_str(header_value.as_str()).expect(""))
} }

View File

@@ -162,12 +162,14 @@ impl RequestBuilder {
/// ``` /// ```
pub fn basic_auth<U, P>(&mut self, username: U, password: Option<P>) -> &mut RequestBuilder pub fn basic_auth<U, P>(&mut self, username: U, password: Option<P>) -> &mut RequestBuilder
where where
U: Into<String>, U: fmt::Display,
P: Into<String>, P: fmt::Display,
{ {
let username = username.into(); let auth = match password {
let password = password.map(|p| p.into()).unwrap_or(String::new()); Some(password) => format!("{}:{}", username, password),
let header_value = format!("basic {}:{}", username, encode(&password)); None => format!("{}:", username)
};
let header_value = format!("basic {}", encode(&auth));
self.header(::header::AUTHORIZATION, HeaderValue::from_str(header_value.as_str()).expect("")) self.header(::header::AUTHORIZATION, HeaderValue::from_str(header_value.as_str()).expect(""))
} }