forked from recmo/uint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathborsh.rs
151 lines (129 loc) · 4.9 KB
/
borsh.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
//! Support for the [`borsh`](https://crates.io/crates/borsh) crate.
#![cfg(feature = "borsh")]
#![cfg_attr(docsrs, doc(cfg(feature = "borsh")))]
use crate::{Bits, Uint};
use borsh::{io, BorshDeserialize, BorshSerialize};
impl<const BITS: usize, const LIMBS: usize> BorshDeserialize for Uint<BITS, LIMBS> {
#[inline]
fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
// This is a bit of an end-run around missing `generic_const_exprs`
// We cannot declare a `[u8; Self::BYTES]` or `[u8; LIMBS * 8]`,
// so we declare a `[u8; LIMBS]` and use unsafe to write to it.
// TODO: Replace the unsafety with `generic_const_exprs` when
// available
let mut limbs = [0u64; LIMBS];
// SAFETY: `limbs` is known to have identical memory layout and
// alignment to `[u8; LIMBS * 8]`, which is guaranteed to safely
// contain [u8; Self::BYTES]`, as `LIMBS * 8 >= Self::BYTES`.
// Reference:
// https://doc.rust-lang.org/reference/type-layout.html#array-layout
let target = unsafe {
core::slice::from_raw_parts_mut(limbs.as_mut_ptr().cast::<u8>(), Self::BYTES)
};
reader.read_exact(target)?;
// Using `Self::from_limbs(limbs)` would be incorrect here, as the
// inner u64s are encoded in LE, and the platform may be BE.
Self::try_from_le_slice(target).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
"value is too large for the type",
)
})
}
}
impl<const BITS: usize, const LIMBS: usize> BorshSerialize for Uint<BITS, LIMBS> {
#[inline]
fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
// TODO: non-allocating and remove the `alloc` feature requirement
let bytes = self.as_le_bytes();
writer.write_all(&bytes[..Self::BYTES])
}
}
impl<const BITS: usize, const LIMBS: usize> BorshDeserialize for Bits<BITS, LIMBS> {
#[inline]
fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
Uint::<BITS, LIMBS>::deserialize_reader(reader).map(Into::into)
}
}
impl<const BITS: usize, const LIMBS: usize> BorshSerialize for Bits<BITS, LIMBS> {
#[inline]
fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
self.as_uint().serialize(writer)
}
}
#[cfg(test)]
mod test {
use super::*;
#[derive(Debug, BorshDeserialize, BorshSerialize, PartialEq, Eq)]
struct Something {
is_it: bool,
value: Uint<256, 4>,
}
#[test]
fn test_uint() {
let something = Something {
is_it: true,
value: Uint::<256, 4>::from_limbs([1, 2, 3, 4]),
};
let mut buf = [0; 33];
something.serialize(&mut buf.as_mut_slice()).unwrap();
assert_eq!(buf, [
1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0
]);
assert_eq!(&something.value.to_le_bytes::<32>(), &buf[1..]);
assert_eq!(Something::try_from_slice(&mut &buf[..]).unwrap(), something);
}
#[derive(Debug, BorshDeserialize, BorshSerialize, PartialEq, Eq)]
struct AnotherThing {
is_it: bool,
value: Bits<256, 4>,
}
#[test]
fn test_bits() {
let another_thing = AnotherThing {
is_it: true,
value: Bits::<256, 4>::from_limbs([1, 2, 3, 4]),
};
let mut buf = [0; 33];
another_thing.serialize(&mut buf.as_mut_slice()).unwrap();
assert_eq!(buf, [
1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0
]);
assert_eq!(&another_thing.value.to_le_bytes::<32>(), &buf[1..]);
assert_eq!(
AnotherThing::try_from_slice(&mut &buf[..]).unwrap(),
another_thing
);
}
#[test]
fn deser_invalid_value() {
let buf = [0xff; 4];
let mut reader = &mut &buf[..];
let result = Uint::<31, 1>::deserialize_reader(&mut reader);
let err = result.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert_eq!(err.to_string(), "value is too large for the type");
}
#[derive(Debug, BorshDeserialize, BorshSerialize, PartialEq, Eq)]
struct AThirdThing {
value: Uint<64, 1>,
bool_value: bool,
}
#[test]
fn roundtrip_trailing_zeroes() {
let instance = AThirdThing {
value: Uint::<64, 1>::from_limbs([1]),
bool_value: true,
};
let mut buf = [0u8; 9];
instance.serialize(&mut buf.as_mut_slice()).unwrap();
assert_eq!(buf, [1, 0, 0, 0, 0, 0, 0, 0, 1]);
assert_eq!(&instance.value.to_le_bytes::<8>(), &buf[..8]);
assert_eq!(
AThirdThing::try_from_slice(&mut &buf[..]).unwrap(),
instance
);
}
}