binary_codec_sv2/datatypes/non_copy_data_types/
mod.rs

1#[cfg(feature = "prop_test")]
2use quickcheck::{Arbitrary, Gen};
3
4mod inner;
5mod seq_inner;
6
7trait IntoOwned {
8    fn into_owned(self) -> Self;
9}
10
11pub use inner::Inner;
12pub use seq_inner::{Seq0255, Seq064K, Sv2Option};
13
14pub type U32AsRef<'a> = Inner<'a, true, 4, 0, 0>;
15pub type U256<'a> = Inner<'a, true, 32, 0, 0>;
16pub type ShortTxId<'a> = Inner<'a, true, 6, 0, 0>;
17pub type PubKey<'a> = Inner<'a, true, 32, 0, 0>;
18pub type Signature<'a> = Inner<'a, true, 64, 0, 0>;
19pub type B032<'a> = Inner<'a, false, 1, 1, 32>;
20pub type B0255<'a> = Inner<'a, false, 1, 1, 255>;
21pub type Str0255<'a> = Inner<'a, false, 1, 1, 255>;
22pub type B064K<'a> = Inner<'a, false, 1, 2, { u16::MAX as usize }>;
23pub type B016M<'a> = Inner<'a, false, 1, 3, { 2_usize.pow(24) - 1 }>;
24
25impl<'decoder> From<[u8; 32]> for U256<'decoder> {
26    fn from(v: [u8; 32]) -> Self {
27        Inner::Owned(v.into())
28    }
29}
30
31#[cfg(not(feature = "with_serde"))]
32#[cfg(feature = "prop_test")]
33impl<'a> U256<'a> {
34    pub fn from_gen(g: &mut Gen) -> Self {
35        let mut inner = Vec::<u8>::arbitrary(g);
36        inner.resize(32, 0);
37        // 32 Bytes arrays are always converted into U256 unwrap never panic
38        let inner: [u8; 32] = inner.try_into().unwrap();
39        inner.into()
40    }
41}
42
43#[cfg(not(feature = "with_serde"))]
44#[cfg(feature = "prop_test")]
45impl<'a> B016M<'a> {
46    pub fn from_gen(g: &mut Gen) -> Self {
47        // This can fail but is used only for tests purposes
48        Vec::<u8>::arbitrary(g).try_into().unwrap()
49    }
50}
51
52use core::convert::{TryFrom, TryInto};
53
54impl<'a> TryFrom<String> for Str0255<'a> {
55    type Error = crate::Error;
56
57    fn try_from(value: String) -> Result<Self, Self::Error> {
58        value.into_bytes().try_into()
59    }
60}
61
62impl<'a> U32AsRef<'a> {
63    pub fn as_u32(&self) -> u32 {
64        let inner = self.inner_as_ref();
65        u32::from_le_bytes([inner[0], inner[1], inner[2], inner[3]])
66    }
67}
68
69impl<'a> From<u32> for U32AsRef<'a> {
70    fn from(v: u32) -> Self {
71        let bytes = v.to_le_bytes();
72        let inner = vec![bytes[0], bytes[1], bytes[2], bytes[3]];
73        U32AsRef::Owned(inner)
74    }
75}
76
77impl<'a> From<&'a U32AsRef<'a>> for u32 {
78    fn from(v: &'a U32AsRef<'a>) -> Self {
79        let b = v.inner_as_ref();
80        u32::from_le_bytes([b[0], b[1], b[2], b[3]])
81    }
82}