Skip to content
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

perf: reduce allocation for string #49

Merged
merged 1 commit into from
Mar 27, 2024
Merged
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
4 changes: 2 additions & 2 deletions core/lib/src/parser/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ use sha2::Sha256;
/// // NG
/// }
/// ```
pub fn validate_signature(channel_secret: String, signature: String, body: String) -> bool {
pub fn validate_signature(channel_secret: &str, signature: &str, body: &str) -> bool {
type HmacSha256 = Hmac<Sha256>;

let mut mac = HmacSha256::new_from_slice(channel_secret.as_bytes())
.expect("HMAC can take key of any size");
mac.update(body.as_bytes());
let mut buf = String::new();
general_purpose::STANDARD.encode_string(&mac.finalize().into_bytes().to_vec(), &mut buf);
general_purpose::STANDARD.encode_string(mac.finalize().into_bytes(), &mut buf);
buf == signature
}
2 changes: 1 addition & 1 deletion examples/actix_web_example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async fn callback(signature: Signature, bytes: web::Bytes) -> Result<HttpRespons

let body: &str = &String::from_utf8(bytes.to_vec()).unwrap();

if !validate_signature(channel_secret.to_string(), signature.key, body.to_string()) {
if !validate_signature(channel_secret, &signature.key, body) {
return Err(ErrorBadRequest("x-line-signature is invalid."));
}

Expand Down
2 changes: 1 addition & 1 deletion examples/rocket_example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async fn world(signature: Signature, body: String) -> (Status, &'static str) {
println!("{signature:#?}");
println!("{body:#?}");

if !validate_signature(channel_secret.to_string(), signature.key, body.clone()) {
if !validate_signature(channel_secret, &signature.key, &body) {
return (Status::BadRequest, "x-line-signature is invalid.");
}

Expand Down
Loading