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
use super::Encoder;
use crate::prelude::*;
use crate::types::Address;
use byteorder::{ByteOrder, LittleEndian};
use super::source::varuint_encode_size;
pub struct Sink {
buf: Vec<u8>,
}
impl Sink {
pub fn new(cap: usize) -> Self {
Sink { buf: Vec::with_capacity(cap) }
}
pub fn write<T: Encoder>(&mut self, val: T) {
val.encode(self)
}
pub(crate) fn write_byte(&mut self, b: u8) {
self.buf.push(b)
}
pub(crate) fn write_bool(&mut self, b: bool) {
if b {
self.write_byte(1)
} else {
self.write_byte(0)
}
}
pub(crate) fn write_bytes(&mut self, data: &[u8]) {
self.buf.extend_from_slice(data)
}
pub(crate) fn write_u16(&mut self, val: u16) {
let mut buf = [0; 2];
LittleEndian::write_u16(&mut buf, val);
self.write_bytes(&buf)
}
pub(crate) fn write_u32(&mut self, val: u32) {
let mut buf = [0; 4];
LittleEndian::write_u32(&mut buf, val);
self.write_bytes(&buf)
}
pub(crate) fn write_u64(&mut self, val: u64) {
let mut buf = [0; 8];
LittleEndian::write_u64(&mut buf, val);
self.write_bytes(&buf)
}
pub(crate) fn write_u128(&mut self, val: u128) {
self.write_bytes(&val.to_le_bytes())
}
#[allow(unused)]
pub(crate) fn write_i128(&mut self, val: i128) {
self.write_bytes(&val.to_le_bytes())
}
pub(crate) fn write_varuint(&mut self, val: u64) {
if val < 0xFD {
self.write_byte(val as u8);
} else if val < 0xFFFF {
self.write_byte(0xFD);
self.write_u16(val as u16);
} else if val <= 0xFFFF_FFFF {
self.write_byte(0xFE);
self.write_u32(val as u32);
} else {
self.write_byte(0xFF);
self.write_u64(val);
}
}
pub(crate) fn write_native_address(&mut self, address: &Address) {
self.write_byte(20);
self.write(address);
}
pub fn write_neovm_address(&mut self, address: &Address) {
self.write_native_address(address)
}
pub fn write_native_varuint(&mut self, val: u64) {
self.write_byte(varuint_encode_size(val) as u8);
self.write_varuint(val);
}
pub fn bytes(&self) -> &[u8] {
&self.buf
}
pub fn into(self) -> Vec<u8> {
self.buf
}
}