Skip to content

Commit

Permalink
Impl TryFrom<&[u8]> for all compressed point types.
Browse files Browse the repository at this point in the history
This reduces copy-pasta in downstream users to check the length of the
slice beforehand.
  • Loading branch information
isislovecruft committed Oct 18, 2019
1 parent 1f7d48f commit 0840d3a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
17 changes: 16 additions & 1 deletion src/edwards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
#![allow(non_snake_case)]

use core::borrow::Borrow;
use core::convert::TryFrom;
use core::fmt::Debug;
use core::iter::Iterator;
use core::iter::Sum;
Expand Down Expand Up @@ -327,12 +328,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 {
/// Construct a `CompressedEdwardsY` from a slice of bytes.
///
/// # 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 {
let mut tmp = [0u8; 32];

Expand Down
17 changes: 16 additions & 1 deletion src/ristretto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@
//! https://ristretto.group/

use core::borrow::Borrow;
use core::convert::TryFrom;
use core::fmt::Debug;
use core::iter::Sum;
use core::ops::{Add, Neg, Sub};
Expand Down Expand Up @@ -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 {
/// Copy the bytes of this `CompressedRistretto`.
pub fn to_bytes(&self) -> [u8; 32] {
Expand All @@ -232,7 +245,9 @@ impl CompressedRistretto {
///
/// # 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 {
let mut tmp = [0u8; 32];

Expand Down

0 comments on commit 0840d3a

Please sign in to comment.