0

I have the following function:

fn hmac_sha1<'a>(_message: &'a str, _key: &'a str) -> &'a [u8] {
    let key: &[u8] = _key.as_bytes();
    let message: &[u8] = _message.as_bytes();

    let mut mac: Hmac<Sha1> = Hmac::new(Sha1::new(), key);
    mac.input(message);

    let mac_result: MacResult = mac.result();

    mac_result.code()
}

In essence, I want to encode my message using SHA1, and return a pointer to the resulting byte array. When compiling this code, I get the following error.

  --> src/main.rs:81:5
   |
81 |     mac_result.code()
   |     ----------^^^^^^^
   |     |
   |     returns a value referencing data owned by the current function
   |     `mac_result` is borrowed here

Now, I understand what is wrong here, I just don't know how to fix it. The mac_result variable's lifetime expires once the function is finished, and a pointer to its internal result will of course not live any longer.

Is there a way extend the lifetime of the mac_result variable so that I can return the byte array it contains, without converting it to a Vec<u8>? That's a workable solution, but I'd rather not convert the array if at all possible.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ben
  • 332
  • 3
  • 16
  • 2
    You can return the *mac_result* to the caller. If you want a prettier interface for that, you could make a wrapper for mac_result, that [derefs](https://doc.rust-lang.org/std/ops/trait.Deref.html) to the hash code. – chpio May 02 '19 at 14:11
  • 1
    You can pass byte array's reference as parameter then you can fill it with `hmac::raw_result` or just return the `MacResult`, only way to increase it's life time is to create it's clone – Ömer Erden May 02 '19 at 14:31
  • Thanks. It makes sense that I wouldn't be able to access a variable outside its scope, but I'm not steady on lifetimes yet, so I wanted to make sure I wasn't missing something obvious. – Ben May 02 '19 at 14:54
  • Another thing is that you do not want or need `_message` and `_key` to have the same lifetime. You can remove any lifetime annotation and it will just work (other than for returning a reference to a local variable, of course). – rodrigo May 02 '19 at 18:31

0 Answers0