From 09c4d146097a4f0fa50c75f7d545bcab3acc2f33 Mon Sep 17 00:00:00 2001 From: Kevin Butler Date: Thu, 5 Nov 2015 17:10:55 +0000 Subject: [PATCH] Weaken parameter requirements for encode --- benches/jwt.rs | 14 ++++++-------- examples/claims.rs | 2 +- src/lib.rs | 6 +++--- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/benches/jwt.rs b/benches/jwt.rs index 92f7d2c..26f1f97 100644 --- a/benches/jwt.rs +++ b/benches/jwt.rs @@ -13,14 +13,12 @@ struct Claims { #[bench] fn bench_encode(b: &mut test::Bencher) { - b.iter(|| encode::( - Claims { - sub: "b@b.com".to_owned(), - company: "ACME".to_owned() - }, - "secret".to_owned(), - Algorithm::HS256 - )); + let claim = Claims { + sub: "b@b.com".to_owned(), + company: "ACME".to_owned() + }; + + b.iter(|| encode(&claim, "secret", Algorithm::HS256)); } #[bench] diff --git a/examples/claims.rs b/examples/claims.rs index 92a56e0..006372d 100644 --- a/examples/claims.rs +++ b/examples/claims.rs @@ -16,7 +16,7 @@ fn main() { company: "ACME".to_owned() }; let key = "secret"; - let token = match encode::(my_claims, key.to_owned(), Algorithm::HS256) { + let token = match encode(&my_claims, key, Algorithm::HS256) { Ok(t) => t, Err(_) => panic!() // in practice you would return the error }; diff --git a/src/lib.rs b/src/lib.rs index 8b96bbf..15856a3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -85,12 +85,12 @@ fn verify(signature: &str, data: &str, secret: &[u8], algorithm: Algorithm) -> b } /// Encode the claims passed and sign the payload using the algorithm and the secret -pub fn encode(claims: T, secret: String, algorithm: Algorithm) -> Result { +pub fn encode>(claims: &T, secret: B, algorithm: Algorithm) -> Result { let encoded_header = try!(Header::new(algorithm).to_base64()); let encoded_claims = try!(claims.to_base64()); // seems to be a tiny bit faster than format!("{}.{}", x, y) let payload = [encoded_header, encoded_claims].join("."); - let signature = sign(&*payload, secret.as_bytes(), algorithm); + let signature = sign(&*payload, secret.as_ref(), algorithm); Ok([payload, signature].join(".")) } @@ -177,7 +177,7 @@ mod tests { sub: "b@b.com".to_owned(), company: "ACME".to_owned() }; - let token = encode::(my_claims.clone(), "secret".to_owned(), Algorithm::HS256).unwrap(); + let token = encode(&my_claims, "secret", Algorithm::HS256).unwrap(); let claims = decode::(token.to_owned(), "secret".to_owned(), Algorithm::HS256).unwrap(); assert_eq!(my_claims, claims); }