Closed not-my-profile closed 2 years ago
I've been playing around with this for a bit. I really like this approach, thanks so much for submitting it. I do have some suggested additions to this (playground link):
This makes SymmetricKey
and co. "wrappers" over the actual key-handling functionality, which has been moved to KeyVersion
. Before, I couldn't implement eg. SymmetricKey
for a V6
, with the same API, because it was already defined for V2orV4
.
Instead of impl gen()
inside of the key-types themselves, this adds a Generate
trait. This way, it's easier to define which keys can be randomly generated, depending on their version as well.
This does add more boilerplate, but doesn't restrict the logic for the key-types as much. Do you have any thoughts/concerns on this @not-my-profile?
Note: I don't expect you to change your PR. I can get a new one set up if needed, that's no problem.
I really like this approach, thanks so much for submitting it.
You're welcome :)
Before, I couldn't implement eg. SymmetricKey for a V6, with the same API, because it was already defined for V2orV4.
I think you are mistaken. The following compiles just fine. (playground) (That's because it is impossible for a crate to implement a foreign trait for a foreign type).
pub struct V2;
pub struct V4;
pub struct V6;
pub trait V2orV4 {}
impl V2orV4 for V2 {}
impl V2orV4 for V4 {}
pub struct SymmetricKey<V> {
bytes: Vec<u8>,
phantom: V,
}
impl<V: V2orV4> SymmetricKey<V> {
pub fn gen() -> Self {
todo!();
}
}
impl SymmetricKey<V6> {
pub fn gen() -> Self {
todo!();
}
}
It's not guaranteed that future keys may be randomly generated, nor can all keys be gen'ed. So we use a separate trait for this.
I'm a bit confused by this, what are examples of keys that cannot be generated?
Sidenote: Did you mean to link a different playground? Yours doesn't compile.
I think you are mistaken. The following compiles just fine. (playground) (That's because it is impossible for a crate to implement a foreign trait for a foreign type).
Strange. I thought it was weird, I must've made a mistake then. Well, in that case, your initial approach is much simpler.
I'm a bit confused by this, what are examples of keys that cannot be generated?
This was before you pointed out me missing something. But, it was to avoid defining gen()
in KeyVersion
which would mean an AsymmetricPublicKey
would have a gen()
function as well.
Sidenote: Did you mean to link a different playground? Yours doesn't compile.
No, but I must've forgotten to remove some invalid imports for playground.
Added in #31
Turns version mismatch errors from runtime errors into compile-time errors, giving us compile-time algorithm lucidity.