Skip to content

Instantly share code, notes, and snippets.

@alicemaz
Last active November 28, 2015 02:35
Show Gist options
  • Save alicemaz/789d7b4c2fe5309c3469 to your computer and use it in GitHub Desktop.
Save alicemaz/789d7b4c2fe5309c3469 to your computer and use it in GitHub Desktop.
//this works
fn hash(data: &[u8], key: &[u8]) {
let mut hmac = Hmac::new(Sha1::new(), key);
hmac.input(data);
let signature = &hmac.result().code().to_base64(B64_STD);
println!("sig:\n{}", signature);
}
//this does not work (compiler error in next file)
fn hash(data: &[u8], key: &[u8]) {
let mut hmac = Hmac::new(Sha1::new(), key);
hmac.input(data);
let result = hmac.result().code();
let signature = &result.to_base64(B64_STD);
println!("sig:\n{}", signature);
}
//but this works
fn hash(data: &[u8], key: &[u8]) {
let mut hmac = Hmac::new(Sha1::new(), key);
hmac.input(data);
let result = hmac.result();
let code = result.code();
let signature = &code.to_base64(B64_STD);
println!("sig:\n{}", signature);
}
//this doesn't work (same error, on `result.code()`)
fn hash<'a>(data: &[u8], key: &[u8]) -> &'a [u8] {
let mut hmac = Hmac::new(Sha1::new(), key);
hmac.input(data);
let result = hmac.result();
let code = result.code();
code
}
//my ultimate goal is something along these lines
//with `let bytes = hash(foo, bar);` in the calling function taking ownership
fn hash<'a>(data: &[u8], key: &[u8]) -> &'a [u8] {
let mut hmac = Hmac::new(Sha1::new(), key);
hmac.input(data);
&hmac.result().code()
}
src/main.rs:48:15: 48:28 error: borrowed value does not live long enough
src/main.rs:48 let result = hmac.result().code();
^~~~~~~~~~~~~
src/main.rs:48:36: 51:2 note: reference must be valid for the block suffix following statement 2 at 48:35...
src/main.rs:48 let result = hmac.result().code();
src/main.rs:49 let signature = &result.to_base64(B64_STD);
src/main.rs:50 println!("sig:\n{}", signature);
src/main.rs:51 }
src/main.rs:48:2: 48:36 note: ...but borrowed value is only valid for the statement at 48:1
src/main.rs:48 let result = hmac.result().code();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/main.rs:48:2: 48:36 help: consider using a `let` binding to increase its lifetime
src/main.rs:48 let result = hmac.result().code();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment