mazzaroth_rs/abi/
encoder.rs

1//! Encodes XDR objects into a byte slice.
2
3use xdr_rs_serialize::ser::XDROut;
4
5/// Encoder for returning a number of arguments.
6/// To push a value to the encoder it must implement the Serialize trait for
7/// encoding.
8pub struct Encoder {
9    values: Vec<u8>,
10}
11
12impl Default for Encoder {
13    fn default() -> Self {
14        Encoder { values: Vec::new() }
15    }
16}
17
18impl Encoder {
19    /// Consume `val` to the Encoder
20    pub fn push<T: XDROut>(&mut self, val: T, typ: &'static str) {
21        let mut val_bytes: Vec<u8> = Vec::new();
22        val.write_json(&mut val_bytes).unwrap();
23
24        // Append bytes after the length
25        match typ {
26            "String" | "u64" | "i64" => self
27                .values_mut()
28                .extend_from_slice(&val_bytes[1..val_bytes.len() - 1]),
29            _ => self.values_mut().extend_from_slice(&val_bytes),
30        };
31    }
32
33    /// Mutable reference to the Encoder vector
34    pub fn values_mut(&mut self) -> &mut Vec<u8> {
35        &mut self.values
36    }
37
38    /// return the vector of values
39    pub fn values(self) -> Vec<u8> {
40        self.values
41    }
42}