Skip to content

Commit

Permalink
refactor: use format_args!() when String creation is unnecessary (#262)
Browse files Browse the repository at this point in the history
* refactor: use format_args!() when String creation is unnecessary

* add livetwo generate_digest_response unit test

* cargo fmt

---------

Co-authored-by: a-wing <1@233.email>
  • Loading branch information
Integral-Tech and a-wing authored Dec 21, 2024
1 parent 5b87142 commit 3527ae8
Showing 1 changed file with 55 additions and 20 deletions.
75 changes: 55 additions & 20 deletions livetwo/src/rtspclient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,26 +52,14 @@ impl RtspSession {
}

fn generate_digest_response(&self, realm: &str, nonce: &str, method: &str) -> String {
let ha1 = format!("{:x}", {
let mut hasher = Md5::new();
hasher.update(format!(
"{}:{}:{}",
self.auth_params.username, realm, self.auth_params.password
));
hasher.finalize()
});

let ha2 = format!("{:x}", {
let mut hasher = Md5::new();
hasher.update(format!("{}:{}", method, self.uri));
hasher.finalize()
});

format!("{:x}", {
let mut hasher = Md5::new();
hasher.update(format!("{}:{}:{}", ha1, nonce, ha2));
hasher.finalize()
})
generate_digest_response(
&self.auth_params.username,
&self.auth_params.password,
&self.uri,
realm,
nonce,
method,
)
}

fn generate_authorization_header(&self, realm: &str, nonce: &str, method: &Method) -> String {
Expand Down Expand Up @@ -452,3 +440,50 @@ pub async fn setup_rtsp_session(rtsp_url: &str) -> Result<(u16, u16, Codec, Code

Ok((rtp_port, rtp_audio_port, video_codec, audio_codec))
}

fn generate_digest_response(
username: &str,
password: &str,
uri: &str,
realm: &str,
nonce: &str,
method: &str,
) -> String {
format!("{:x}", {
let mut hasher = Md5::new();
hasher.update(format!(
"{}:{}:{}",
format_args!("{:x}", {
let hasher = Md5::new_with_prefix(format!("{}:{}:{}", username, realm, password));
hasher.finalize()
}),
nonce,
format_args!("{:x}", {
let hasher = Md5::new_with_prefix(format!("{}:{}", method, uri));
hasher.finalize()
})
));
hasher.finalize()
})
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_generate_digest_response() {
let username = "username";
let password = "password";
let uri = "/resource";
let realm = "Realm";
let nonce = "1234567890";
let method = "GET";

let expected_response = "5a8a58beeb78f36ed2c0f0d474288f3d";

let response = generate_digest_response(username, password, uri, realm, nonce, method);

assert_eq!(response, expected_response);
}
}

0 comments on commit 3527ae8

Please # to comment.