From 1e885665c799afd902634d86cdf34da04bbac997 Mon Sep 17 00:00:00 2001 From: Isis Lovecruft Date: Fri, 18 Oct 2019 19:12:57 +0000 Subject: [PATCH] Impl TryFrom<&[u8]> for all compressed point types. This reduces copy-pasta in downstream users to check the length of the slice beforehand. --- src/edwards.rs | 14 +++++++++++++- src/ristretto.rs | 14 +++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/edwards.rs b/src/edwards.rs index e03230b4f..2bc09bc1f 100644 --- a/src/edwards.rs +++ b/src/edwards.rs @@ -327,12 +327,24 @@ impl Default for CompressedEdwardsY { } } +impl TryFrom<&[u8]> for CompressedEdwardsY { + fn try_from(bytes: &[u8]) -> Result { + 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]; diff --git a/src/ristretto.rs b/src/ristretto.rs index 3774c993b..7b69ebad1 100644 --- a/src/ristretto.rs +++ b/src/ristretto.rs @@ -217,6 +217,16 @@ impl ConstantTimeEq for CompressedRistretto { } } +impl TryFrom<&[u8]> for CompressedRistretto { + fn try_from(bytes: &[u8]) -> Result { + 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] { @@ -232,7 +242,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];