-
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
base: master
Are you sure you want to change the base?
Changes from 5 commits
e5e45c0
fb394f4
7c71df1
d950d04
4835b7c
52582f9
1a4b509
651e7a6
26143d7
0ce38c5
f622c92
64ab637
6930a0f
f45f7ec
cae31f7
e79316c
a086bcf
cb85630
ee63c2a
68e03b9
967e0b9
1b2a99d
025b823
17a7b54
0cc1667
d5846af
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,156 @@ | ||
use crate::errors::UnknownCryptoError; | ||
use std::{convert::TryFrom, fmt, marker::PhantomData}; | ||
|
||
/// Marker trait for when a type contains some sensitive information. | ||
pub trait Secret {} | ||
|
||
/// Marker trait for when a type contains only non-sensitive information. | ||
/// Be careful if implementing this trait on your own. It cannot | ||
/// cause memory unsafety, and so is not marked `unsafe`. Implementing | ||
/// it can, however, lead to data types containing sensitive data ending | ||
/// up with APIs meant only for types containing only non-sensitive data. | ||
pub trait Public {} | ||
|
||
/// A small trait containing static information about the minimum and | ||
/// maximum size (in bytes) of a type containing data. | ||
pub trait Bounded { | ||
/// The largest number of bytes this type should be allowed to hold. | ||
const MIN: Option<usize> = None; | ||
|
||
/// The smallest number of bytes this type should be allowed to hold. | ||
const MAX: Option<usize> = None; | ||
} | ||
|
||
/// A generic holder for types that are basically just a bag of bytes | ||
/// with extra semantic meaning and restriction on top. We parameterize | ||
/// over the byte storage with parameter `B`. We parameterize over the | ||
/// API-level semantics of the type with phantom type `K`. | ||
#[derive(Clone)] | ||
pub struct Data<B, K> { | ||
bytes: B, | ||
phantom: PhantomData<K>, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This was probably overambitious. It ended up working out fine implementation-wise, but the generated documentation is pretty difficult to parse. By conditionally implementing "secret" methods like As a solution, I think it would be best to split up pub type SecretKey = Secret<Array<32>, Argon2iKey>; There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I agree that splitting |
||
} | ||
|
||
impl<'a, B, K> Data<B, K> | ||
where | ||
B: TryFrom<&'a [u8], Error = UnknownCryptoError>, | ||
K: Bounded, | ||
{ | ||
/// TODO | ||
pub fn from_slice(slice: &'a [u8]) -> Result<Self, B::Error> { | ||
let min = K::MIN.unwrap_or(0); | ||
let max = K::MAX.unwrap_or(usize::MAX); | ||
if slice.len() < min || slice.len() > max { | ||
return Err(UnknownCryptoError); | ||
} | ||
|
||
Ok(Self { | ||
bytes: B::try_from(slice)?, | ||
phantom: PhantomData, | ||
}) | ||
} | ||
} | ||
|
||
impl<'a, B, K> Data<B, K> | ||
where | ||
B: AsRef<[u8]>, | ||
{ | ||
/// Get the length of the contained byte slice. | ||
pub fn len(&self) -> usize { | ||
self.bytes.as_ref().len() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We cannot get length based on the bytes here. If like BLAKE2b, it has valid ranges this will return the upper bound, because that's the array which has been allocated, not the actual length requested. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think I was assuming here that the B's AsRef implementation would take care of returning the correct subset. I was also assuming that B would be slightly more than an array. Something like (ignoring naming and syntax): struct ArrayBytes {
bytes: [u8: MAX],
len: usize,
} Though I think it's definitely possible to just use basic types for B like There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure at the moment, which one would work best tbh. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I thought about this a bit more, and I see two separate use cases: an array of known size, and an array of known maximum size. If we have a function that returns a precise number of bytes, we should probably use an struct ArrayData<const LEN: usize> {
bytes: [u8; LEN]
} and then define a new type like: struct Sha256Ctx;
type Sha256Tag = PublicData<ArrayData<32>, Sha256Ctx>; However, if we only know the maximum number of bytes to hold, maybe we define an struct ArrayData<const MAX: usize> {
bytes: [u8; MAX],
len: usize,
} and then define types like: struct PasswordCtx;
// I don't know why we'd want to restrict the password length but let's pretend.
type Password = SecretData<ArrayVecData<32>, PasswordCtx>;
let pw0 = Password::from_slice(&b"rockyou"); // seven-byte password
let pw1 = Password::from_slice(&b"pa$$word"); // eight-byte password |
||
} | ||
|
||
/// Check if the contained byte slice is empty. | ||
pub fn is_empty(&self) -> bool { | ||
self.bytes.as_ref().is_empty() | ||
} | ||
} | ||
|
||
impl<'a, B, K> AsRef<[u8]> for Data<B, K> | ||
where | ||
B: AsRef<[u8]>, | ||
K: Public, | ||
{ | ||
/// Get a reference to the underlying byte slice. | ||
fn as_ref(&self) -> &[u8] { | ||
self.bytes.as_ref() | ||
} | ||
} | ||
|
||
impl<'a, B, K> Data<B, K> | ||
where | ||
B: AsRef<[u8]>, | ||
K: Secret, | ||
{ | ||
/// TODO: Grab docs for `unprotected_as_bytes` and insert here. | ||
pub fn unprotected_as_bytes(&self) -> &[u8] { | ||
self.bytes.as_ref() | ||
} | ||
} | ||
|
||
// We implement this manually to skip over the PhantomData. | ||
impl<B, K> PartialEq for Data<B, K> | ||
where | ||
B: PartialEq<B>, | ||
{ | ||
fn eq(&self, other: &Self) -> bool { | ||
self.bytes.eq(&other.bytes) | ||
} | ||
} | ||
|
||
// We implement this manually to skip over the PhantomData. | ||
impl<B, K> fmt::Debug for Data<B, K> | ||
where | ||
B: fmt::Debug, | ||
{ | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
self.bytes.fmt(f) | ||
} | ||
} | ||
|
||
/// A convenient type for holding data with a static upper bound on | ||
/// its size. The bytes are held with a static array. | ||
#[derive(Clone, Debug)] | ||
vlmutolo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
pub struct StaticData<const MAX: usize> { | ||
bytes: [u8; MAX], | ||
len: usize, | ||
} | ||
|
||
impl<const MAX: usize> TryFrom<&[u8]> for StaticData<MAX> { | ||
type Error = UnknownCryptoError; | ||
|
||
fn try_from(slice: &[u8]) -> Result<Self, Self::Error> { | ||
if slice.len() > MAX { | ||
return Err(UnknownCryptoError); | ||
} | ||
|
||
let mut bytes = [0u8; MAX]; | ||
|
||
// PANIC: This is ok because we just checked that the length | ||
// was less than MAX above. Violating that condition is the | ||
// only thing that would cause this to panic. | ||
bytes | ||
.get_mut(0..slice.len()) | ||
.unwrap() | ||
.copy_from_slice(slice); | ||
|
||
Ok(Self { | ||
bytes, | ||
len: slice.len(), | ||
}) | ||
} | ||
} | ||
|
||
impl<const MAX: usize> AsRef<[u8]> for StaticData<MAX> { | ||
fn as_ref(&self) -> &[u8] { | ||
// PANIC: This unwrap is ok because the type's len is checked at | ||
// construction time to be less than MAX. | ||
self.bytes.get(..self.len).unwrap() | ||
} | ||
} | ||
|
||
impl<const MAX: usize> PartialEq for StaticData<MAX> { | ||
fn eq(&self, other: &Self) -> bool { | ||
self.bytes.get(..self.len).eq(&other.bytes.get(..other.len)) | ||
} | ||
} |
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.
I see no reason to leave these as Option. Aren't we always going to define a bound over all types?
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.
Yeah I can't think of a case when we'd want no bound. I actually don't remember why I put it there in the first place. At the time I was seven layers deep in thinking about the trait system, so this didn't get a ton of thought haha.