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
use super::{
constant_store::ConstantStore,
sigma_byte_reader::{SigmaByteRead, SigmaByteReader},
sigma_byte_writer::{SigmaByteWrite, SigmaByteWriter},
};
use io::Cursor;
use sigma_ser::{peekable_reader::PeekableReader, vlq_encode};
use std::io;
use thiserror::Error;
#[derive(Error, Eq, PartialEq, Debug, Clone)]
pub enum SerializationError {
#[error("invalid op code: {0}")]
InvalidOpCode(u8),
#[error("not implemented op error")]
NotImplementedOpCode(u8),
#[error("type parsing error")]
InvalidTypePrefix,
#[error("vlq encode error")]
VlqEncode(vlq_encode::VlqEncodingError),
#[error("io error")]
Io(String),
#[error("misc error")]
Misc(String),
#[error("feature not yet implemented: {0}")]
NotImplementedYet(String),
#[error("Constant with index {0} not found in constant store")]
ConstantForPlaceholderNotFound(u32),
#[error("Value out of bounds: {0}")]
ValueOutOfBounds(String),
#[error("Tuple items out of bounds: {0}")]
TupleItemsOutOfBounds(usize),
}
impl From<vlq_encode::VlqEncodingError> for SerializationError {
fn from(error: vlq_encode::VlqEncodingError) -> Self {
SerializationError::VlqEncode(error)
}
}
impl From<io::Error> for SerializationError {
fn from(error: io::Error) -> Self {
SerializationError::Io(error.to_string())
}
}
pub trait SigmaSerializable: Sized {
fn sigma_serialize<W: SigmaByteWrite>(&self, w: &mut W) -> Result<(), io::Error>;
fn sigma_parse<R: SigmaByteRead>(r: &mut R) -> Result<Self, SerializationError>;
fn sigma_serialize_bytes(&self) -> Vec<u8> {
let mut data = Vec::new();
let mut w = SigmaByteWriter::new(&mut data, None);
self.sigma_serialize(&mut w)
.expect("serialization failed");
data
}
fn sigma_parse_bytes(mut bytes: Vec<u8>) -> Result<Self, SerializationError> {
let cursor = Cursor::new(&mut bytes[..]);
let pr = PeekableReader::new(cursor);
let mut sr = SigmaByteReader::new(pr, ConstantStore::empty());
Self::sigma_parse(&mut sr)
}
}
#[cfg(test)]
pub fn sigma_serialize_roundtrip<T: SigmaSerializable>(v: &T) -> T {
let mut data = Vec::new();
let mut w = SigmaByteWriter::new(&mut data, None);
v.sigma_serialize(&mut w).expect("serialization failed");
let cursor = Cursor::new(&mut data[..]);
let pr = PeekableReader::new(cursor);
let mut sr = SigmaByteReader::new(pr, ConstantStore::empty());
T::sigma_parse(&mut sr).expect("parse failed")
}