stack_vm/code/
to_byte_code.rs

1use crate::to_byte_code::ToByteCode;
2use std::io::Write;
3use rmp::encode;
4use std::fmt;
5use super::Code;
6
7impl<T: ToByteCode + fmt::Debug> ToByteCode for Code<T> {
8    /// Create bytecode for this `Code`.
9    ///
10    /// Encodes into a Map of the following format:
11    /// ```json
12    /// {
13    ///     "code" => [ 0, 1, 0, 0, 1, 1, 1, 0 ],
14    ///     "data" => [ 123, 456 ],
15    ///     "symbols" => [ 0, "push", 1, "add" ],
16    ///     "labels" => [ 0, "main" ]
17    /// }
18    /// ```
19    fn to_byte_code(&self, mut buf: &mut Write) {
20        // We're creating a 4-element map.
21        encode::write_map_len(&mut buf, 4).unwrap();
22
23        // First, the code.
24        encode::write_str(&mut buf, "code").unwrap();
25        encode::write_array_len(&mut buf, self.code.len() as u32).unwrap();
26        for operation in self.code() {
27            encode::write_uint(&mut buf, *operation as u64).unwrap();
28        }
29
30        // Next, the data.
31        encode::write_str(&mut buf, "data").unwrap();
32        encode::write_array_len(&mut buf, self.data.len() as u32).unwrap();
33        for operand in self.data() {
34            operand.to_byte_code(&mut buf);
35        }
36
37        // Next, the symbols.
38        encode::write_str(&mut buf, "symbols").unwrap();
39        encode::write_array_len(&mut buf, (self.symbols.len() * 2) as u32).unwrap();
40        for symbol in self.symbols() {
41            encode::write_uint(&mut buf, symbol.0 as u64).unwrap();
42            encode::write_str(&mut buf, &symbol.1).unwrap();
43        }
44
45        // Lastly, the labels.
46        encode::write_str(&mut buf, "labels").unwrap();
47        encode::write_array_len(&mut buf, (self.labels.len() * 2) as u32).unwrap();
48        for label in self.labels() {
49            encode::write_uint(&mut buf, label.0 as u64).unwrap();
50            encode::write_str(&mut buf, &label.1).unwrap();
51        }
52    }
53}