-
Notifications
You must be signed in to change notification settings - Fork 30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
convert newtypes to const generics #274
Draft
vlmutolo
wants to merge
26
commits into
orion-rs:master
Choose a base branch
from
vlmutolo:const-generics
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 2 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
e5e45c0
convert blake2b::Digest to const generics
fb394f4
simplified and documented const generics impls
7c71df1
remove duplicate docs on PublicVec
d950d04
move to marker types and traits
4835b7c
Merge branch 'master' into const-generics
52582f9
squash me
1a4b509
split Data into PublicData and SecretData
651e7a6
remove optional bounds and fix some cfgs
26143d7
move/fix docs, remove unnecessary lifetimes
0ce38c5
broaden PartialEq impls for {Secret,Public}Data
f622c92
base: better module docs
64ab637
rename to ArrayVecData and add actual ArrayData
6930a0f
rename PublicData and SecretData to Public and Secret
f45f7ec
change blake2b Digest to use ArrayVecData
cae31f7
restrict PartialEq to exact same type
e79316c
fix base docs line in hazardous module docs
a086bcf
move to core::fmt::Debug for Secret and Public
cb85630
add omitted_debug tests to base types
ee63c2a
clean up docs
68e03b9
add generate_with_size method to Public and Secret
967e0b9
simplify to Context and Data super traits
1b2a99d
begin base test_framework
025b823
remove safe_api bound on as_bytes base tests
17a7b54
add base tests for blake2b Digest
0cc1667
move per-type base test impl to macro
d5846af
move aead::SecretKey to const generics
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,180 @@ | ||
use crate::errors::UnknownCryptoError; | ||
|
||
/// This trait holds most of the behavior of types whose data are | ||
/// meant to be public. This is what users are expected to import | ||
/// in order to work with various Orion types that represent | ||
/// non-secret data. | ||
pub trait Public<D>: Sized { | ||
/// Construct from a given byte slice. | ||
/// | ||
/// ## Errors | ||
/// `UnknownCryptoError` will be returned if: | ||
/// - `slice` is empty | ||
/// - TODO: figure out how to express max length in the docs | ||
fn from_slice(slice: &[u8]) -> Result<Self, UnknownCryptoError>; | ||
|
||
/// Return a byte slice representing the underlying data. | ||
fn as_ref(&self) -> &[u8]; | ||
|
||
/// Get the length of the underlying data in bytes. | ||
fn len(&self) -> usize { | ||
self.as_ref().len() | ||
} | ||
|
||
/// Check if the length of the underlying data is 0. | ||
fn is_empty(&self) -> bool { | ||
self.len() == 0 | ||
} | ||
} | ||
|
||
/// This is a trait used to express the fact that a type can be interpreted | ||
/// as or converted from another type. It's used primarily to let us | ||
/// reinterpret simple wrappers over [`PublicArray`][0] as the `PublicArray` | ||
/// itself. | ||
/// | ||
/// [0]: crate::hazardous::base::PublicArray | ||
pub trait Wrapper<T> { | ||
/// This allows us to require that `Self` can return a reference to | ||
/// the underlying `T`. It's functionally equivalent to `AsRef<T>` | ||
fn data(&self) -> &T; | ||
|
||
/// This allows us to require that `Self` can be constructed from | ||
/// its underlying type without possibility of failure. It's | ||
/// functionally equivalent to `From<T>`. | ||
fn from(data: T) -> Self; | ||
} | ||
|
||
// TODO: Do we want to redefine Wrapper<T> as: | ||
// `trait Wrapper<T>: AsRef<T> + From<T> {}` ? It seems equivalent. If | ||
// we're going to use a macro to generate these `Wrapper` impls anyway, we | ||
// might as well just use the standard traits (?). | ||
|
||
/// `PublicArray` is a convenient type for storing public bytes in an array. | ||
/// It implements [`Public`](crate::hazardous::base::Public), so creating | ||
/// a newtype around it that also implements `Public` is fairly simple. | ||
/// | ||
/// ```rust | ||
/// use orion::hazardous::base::{Public, PublicArray, Wrapper}; | ||
/// | ||
/// // Create a type that must be exactly 32 bytes long (32..=32). | ||
/// type ShaArray = PublicArray<32, 32>; | ||
/// struct ShaDigest(ShaArray); | ||
/// | ||
/// // Implement Wrapper (only has to be imported for newtype creation). | ||
/// // This is the block we may want to have a macro derive for us. | ||
/// impl Wrapper<ShaArray> for ShaDigest { | ||
/// fn data(&self) -> &ShaArray { &self.0 } | ||
/// fn from(data: ShaArray) -> Self { Self(data) } | ||
/// } | ||
/// | ||
/// // Thanks to an auto-impl, `ShaDigest` now implements `Public`. | ||
/// let digest = ShaDigest::from_slice(&[42; 32]); | ||
/// assert!(digest.is_ok()); | ||
/// ``` | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct PublicArray<const MIN: usize, const MAX: usize> { | ||
value: [u8; MAX], | ||
original_length: usize, | ||
} | ||
|
||
impl<const MIN: usize, const MAX: usize> Public<Self> for PublicArray<MIN, MAX> { | ||
fn from_slice(slice: &[u8]) -> Result<Self, UnknownCryptoError> { | ||
let slice_len = slice.len(); | ||
|
||
if !(MIN..=MAX).contains(&slice_len) { | ||
return Err(UnknownCryptoError); | ||
} | ||
|
||
let mut value = [0u8; MAX]; | ||
value[..slice_len].copy_from_slice(slice); | ||
|
||
Ok(Self { | ||
value, | ||
original_length: slice_len, | ||
}) | ||
} | ||
|
||
fn as_ref(&self) -> &[u8] { | ||
self.value.get(..self.original_length).unwrap() | ||
} | ||
} | ||
|
||
/// Anything that can be converted to/from a `PublicArray` will | ||
/// implement `Public` thanks to this auto implementation. The | ||
/// ability to be converted to/from a PublicArray is expressed | ||
/// using the `PublicData<Data = PublicArray<_,_>` trait bound. | ||
impl<T, const MIN: usize, const MAX: usize> Public<PublicArray<MIN, MAX>> for T | ||
where | ||
T: Wrapper<PublicArray<MIN, MAX>>, | ||
{ | ||
fn from_slice(bytes: &[u8]) -> Result<Self, UnknownCryptoError> { | ||
let a = PublicArray::from_slice(bytes)?; | ||
Ok(Self::from(a)) | ||
} | ||
|
||
fn as_ref(&self) -> &[u8] { | ||
self.data().as_ref() | ||
} | ||
} | ||
|
||
/// `PublicVec` is a convenient type for storing public bytes in an `Vec`. | ||
/// It implements [`Public`](crate::hazardous::base::Public), so creating | ||
/// a newtype around it that also implements `Public` is fairly simple. | ||
/// | ||
/// ```rust | ||
/// use orion::hazardous::base::{Public, PublicVec, Wrapper}; | ||
/// | ||
/// // Maybe you want your public key to be variable-sized. | ||
/// struct PublicKey(PublicVec); | ||
/// | ||
/// // Implement Wrapper (only has to be imported for newtype creation). | ||
/// // This is the block we may want to have a macro derive for us. | ||
/// impl Wrapper<PublicVec> for PublicKey { | ||
/// fn data(&self) -> &PublicVec { &self.0 } | ||
/// fn from(data: PublicVec) -> Self { Self(data) } | ||
/// } | ||
/// | ||
/// // Thanks to an auto-impl, `PublicKey` now implements `Public`. | ||
/// let digest = PublicKey::from_slice(&[42; 32]); | ||
/// assert!(digest.is_ok()); | ||
/// ``` | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct PublicVec { | ||
value: Vec<u8>, | ||
original_length: usize, | ||
} | ||
|
||
/// Anything that can be converted to/from a `PublicVec` will | ||
/// implement `Public` thanks to this auto implementation. The | ||
/// ability to be converted to/from a PublicAVecis expressed | ||
/// using the `PublicDynamic<Data = PublicVec<_,_>` trait bound. | ||
impl Public<Self> for PublicVec { | ||
fn from_slice(slice: &[u8]) -> Result<Self, UnknownCryptoError> { | ||
Ok(Self { | ||
value: Vec::from(slice), | ||
original_length: slice.len(), | ||
}) | ||
} | ||
|
||
fn as_ref(&self) -> &[u8] { | ||
self.value.get(..self.original_length).unwrap() | ||
} | ||
} | ||
|
||
/// Anything that can be converted to/from a `PublicVec` will | ||
/// implement `Public` thanks to this auto implementation. The | ||
/// ability to be converted to/from a PublicArray is expressed | ||
/// using the `Wrapper<PublicVec>` trait bound. | ||
impl<T> Public<PublicVec> for T | ||
where | ||
T: Wrapper<PublicVec>, | ||
{ | ||
fn from_slice(bytes: &[u8]) -> Result<Self, UnknownCryptoError> { | ||
let a = PublicVec::from_slice(bytes)?; | ||
Ok(Self::from(a)) | ||
} | ||
|
||
fn as_ref(&self) -> &[u8] { | ||
self.data().as_ref() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we choose not to use macros anywhere, we will incur this cost of extra boilerplate code for each newtype we want to add. It's not that much boilerplate, but it may add up. The simple solution here is to have a single small macro (
impl_wrapper
) that just does theWrapper<T>
implementation, and let the traits take care of the rest.