Hi all! I'm new to Rust, and I'm trying to learn as quickly as possible but some of the concepts are difficult for me.
I was trying to refactor some code I was working on to pull some common logic into a function. And that led me to write something like this:
// cargo-deps: jsonwebtoken="*", openssl="*", derive_more="*"
use jsonwebtoken::DecodingKey;
use openssl;
use openssl::pkey::PKey;
use openssl::error::ErrorStack;
fn main() {
pub fn decoding_key_for_rsa_public_key(
public_key: &PKey<openssl::pkey::Public>,
) -> Result<DecodingKey, ErrorStack> {
let public_key_der = public_key.rsa()?.public_key_to_der_pkcs1()?;
let key = DecodingKey::from_rsa_der(&public_key_der);
Ok(key)
}
}
Note: jsonwebtoken
isn't on Rust Playground or I would have posted it there. I made the above code usable in rust-script
instead.
Now, I understand the problem here. public_key_der
is a Vec<u8>
, which only lives as long as the function block. key
is going to try to hold a reference to public_key_der
, but it will live on beyond the function block--meaning that it will be holding a reference to data that is no longer around, which is of course a bad idea.
(Note: the actual implementation of from_rsa_der
creates a Cow::Borrowed
of public_key_der
, which makes me think that this is important for me, but I don't exactly understand what Cow
does or why one uses it)
Anyway, I understand why the code as written doesn't compile. What I haven't figured out is, how to actually make it work. Truth be told, what I want is for public_key_der
--the Vec[u8]
created in this function--to last as long as the Ok(key)
returned by this function does. After all, the only point of this vector is to be referenced by the DecodingKey
object. I'd like to try to mark it as having the same lifetime as the object returned, and I'd really like to do so without marking things as having a static
lifetime; but I can't seem to figure out how to do that.
I found a way around writing this method as it is, so answering this is not entirely necessary. But I would like to figure out if and how to do it this way. Can anyone help me out? Thanks!