Skip to content

Commit

Permalink
signature: alloc encoding conversions to Vec/Box
Browse files Browse the repository at this point in the history
Since signatures all encode to a "bag of bytes" of some form, choosing a
common representation is useful when abstracting over a number of
different signature systems.

These helpers make it easy to use either a `Vec<u8>` or `Box<[u8]>` as
that common type.
  • Loading branch information
tarcieri committed Oct 24, 2022
1 parent 217a416 commit f6ffa5c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
17 changes: 17 additions & 0 deletions signature/src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
use crate::{Error, Result};

#[cfg(feature = "alloc")]
use alloc::{boxed::Box, vec::Vec};

/// Support for decoding/encoding signatures as bytes.
pub trait SignatureEncoding:
Clone + Sized + for<'a> TryFrom<&'a [u8], Error = Error> + Into<Self::Repr>
Expand All @@ -18,4 +21,18 @@ pub trait SignatureEncoding:
fn to_bytes(&self) -> Self::Repr {
self.clone().into()
}

/// Encode signature as a byte vector.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
fn to_vec(&self) -> Vec<u8> {
self.to_bytes().as_ref().to_vec()
}

/// Encode the signature as a boxed byte slice.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
fn to_boxed_slice(&self) -> Box<[u8]> {
self.to_vec().into_boxed_slice()
}
}
5 changes: 3 additions & 2 deletions signature/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@
//! [`Digest`]: https://docs.rs/digest/latest/digest/trait.Digest.html
//! [Fiat-Shamir heuristic]: https://en.wikipedia.org/wiki/Fiat%E2%80%93Shamir_heuristic
#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

Expand All @@ -145,8 +148,6 @@ compile_error!(
Use the `rand-preview` feature instead."
);

#[cfg(feature = "hazmat-preview")]
#[cfg_attr(docsrs, doc(cfg(feature = "hazmat-preview")))]
pub mod hazmat;

mod encoding;
Expand Down

0 comments on commit f6ffa5c

Please sign in to comment.