Skip to content

Commit f6ffa5c

Browse files
committed
signature: alloc encoding conversions to Vec/Box
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.
1 parent 217a416 commit f6ffa5c

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

signature/src/encoding.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
33
use crate::{Error, Result};
44

5+
#[cfg(feature = "alloc")]
6+
use alloc::{boxed::Box, vec::Vec};
7+
58
/// Support for decoding/encoding signatures as bytes.
69
pub trait SignatureEncoding:
710
Clone + Sized + for<'a> TryFrom<&'a [u8], Error = Error> + Into<Self::Repr>
@@ -18,4 +21,18 @@ pub trait SignatureEncoding:
1821
fn to_bytes(&self) -> Self::Repr {
1922
self.clone().into()
2023
}
24+
25+
/// Encode signature as a byte vector.
26+
#[cfg(feature = "alloc")]
27+
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
28+
fn to_vec(&self) -> Vec<u8> {
29+
self.to_bytes().as_ref().to_vec()
30+
}
31+
32+
/// Encode the signature as a boxed byte slice.
33+
#[cfg(feature = "alloc")]
34+
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
35+
fn to_boxed_slice(&self) -> Box<[u8]> {
36+
self.to_vec().into_boxed_slice()
37+
}
2138
}

signature/src/lib.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,9 @@
130130
//! [`Digest`]: https://docs.rs/digest/latest/digest/trait.Digest.html
131131
//! [Fiat-Shamir heuristic]: https://en.wikipedia.org/wiki/Fiat%E2%80%93Shamir_heuristic
132132
133+
#[cfg(feature = "alloc")]
134+
extern crate alloc;
135+
133136
#[cfg(feature = "std")]
134137
extern crate std;
135138

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

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

152153
mod encoding;

0 commit comments

Comments
 (0)