Impl TryFrom<&[u8]> for all compressed point types.

This reduces copy-pasta in downstream users to check the length of the
slice beforehand.
This commit is contained in:
Isis Lovecruft 2019-10-18 19:12:57 +00:00
parent 82ea371b19
commit a7f317a2b8
No known key found for this signature in database
GPG key ID: AB41313533E8E812
2 changed files with 32 additions and 2 deletions

View file

@ -93,6 +93,7 @@
#![allow(non_snake_case)] #![allow(non_snake_case)]
use core::borrow::Borrow; use core::borrow::Borrow;
use core::convert::TryFrom;
use core::fmt::Debug; use core::fmt::Debug;
use core::iter::Iterator; use core::iter::Iterator;
use core::iter::Sum; use core::iter::Sum;
@ -335,12 +336,26 @@ impl Default for CompressedEdwardsY {
} }
} }
impl TryFrom<&[u8]> for CompressedEdwardsY {
type Error = ();
fn try_from(bytes: &[u8]) -> Result<CompressedEdwardsY, ()> {
if bytes.len() != 32 {
return Err(());
}
Ok(CompressedEdwardsY::from_slice(bytes))
}
}
impl CompressedEdwardsY { impl CompressedEdwardsY {
/// Construct a `CompressedEdwardsY` from a slice of bytes. /// Construct a `CompressedEdwardsY` from a slice of bytes.
/// ///
/// # Panics /// # Panics
/// ///
/// If the input `bytes` slice does not have a length of 32. /// If the input `bytes` slice does not have a length of 32. For
/// a panic-safe version of this API, see the implementation of
/// `TryFrom<&[u8]`.
pub fn from_slice(bytes: &[u8]) -> CompressedEdwardsY { pub fn from_slice(bytes: &[u8]) -> CompressedEdwardsY {
let mut tmp = [0u8; 32]; let mut tmp = [0u8; 32];

View file

@ -158,6 +158,7 @@
//! https://ristretto.group/ //! https://ristretto.group/
use core::borrow::Borrow; use core::borrow::Borrow;
use core::convert::TryFrom;
use core::fmt::Debug; use core::fmt::Debug;
use core::iter::Sum; use core::iter::Sum;
use core::ops::{Add, Neg, Sub}; use core::ops::{Add, Neg, Sub};
@ -217,6 +218,18 @@ impl ConstantTimeEq for CompressedRistretto {
} }
} }
impl TryFrom<&[u8]> for CompressedRistretto {
type Error = ();
fn try_from(bytes: &[u8]) -> Result<CompressedRistretto, ()> {
if bytes.len() != 32 {
return Err(());
}
Ok(CompressedRistretto::from_slice(bytes))
}
}
impl CompressedRistretto { impl CompressedRistretto {
/// Copy the bytes of this `CompressedRistretto`. /// Copy the bytes of this `CompressedRistretto`.
pub fn to_bytes(&self) -> [u8; 32] { pub fn to_bytes(&self) -> [u8; 32] {
@ -232,7 +245,9 @@ impl CompressedRistretto {
/// ///
/// # Panics /// # Panics
/// ///
/// If the input `bytes` slice does not have a length of 32. /// If the input `bytes` slice does not have a length of 32. For a
/// panic-safe version of this API, see the implementation of
/// `TryFrom<&[u8]>`.
pub fn from_slice(bytes: &[u8]) -> CompressedRistretto { pub fn from_slice(bytes: &[u8]) -> CompressedRistretto {
let mut tmp = [0u8; 32]; let mut tmp = [0u8; 32];