stack_vm/to_byte_code.rs
1//! Code serializer.
2//!
3//! If you wish to dump compiled bytecode from your virtual machine for loading
4//! again later then you need to implement this trait for your Operand type.
5
6use std::io::Write;
7
8/// Convert from operands to byte code.
9///
10/// This trait represents the ability to dump your Operands to bytecode.
11/// `stack-vm` uses the [`rmp`](https://crates.io/crates/rmp) crate to store
12/// bytecode as a MsgPack encoded binary. As long as you return a valid vector
13/// of messagepack bytes it'll be inserted into the output during the
14/// serialization run.
15///
16/// See the [`rmp` docs](https://docs.rs/rmp/0.8.7/rmp/) to find out which
17/// functions you can use to write out your types.
18///
19/// Being MsgPack means that you can encode your Operand in any way you require,
20/// for example as a single integer, or a map of keys and values provided that
21/// you write just a single MsgPack value.
22pub trait ToByteCode {
23 /// Convert your type to MsgPack.
24 ///
25 /// This function takes a mutable reference of type `Write` into which you
26 /// write your MsgPack encoded value.
27 ///
28 /// ## Example
29 ///
30 /// ```
31 /// # extern crate rmp;
32 /// # extern crate stack_vm;
33 /// # use stack_vm::ToByteCode;
34 /// # use std::io::Write;
35 ///
36 /// #[derive(PartialEq, Debug)]
37 /// struct Operand(i64);
38 ///
39 /// impl ToByteCode for Operand {
40 /// fn to_byte_code(&self, mut buf: &mut Write) {
41 /// rmp::encode::write_sint(&mut buf, self.0).unwrap();
42 /// }
43 /// }
44 /// # fn main() {
45 /// let op = Operand(13);
46 /// let mut buf: Vec<u8> = vec![];
47 /// op.to_byte_code(&mut buf);
48 /// assert_eq!(&buf[..], [0xd]);
49 /// # }
50 /// ```
51 fn to_byte_code(&self, _: &mut Write);
52}
53
54#[cfg(test)]
55mod test {
56 use super::*;
57 use rmp;
58
59 struct Operand(i64);
60
61 impl ToByteCode for Operand {
62 fn to_byte_code(&self, mut buf: &mut Write) {
63 rmp::encode::write_sint(&mut buf, self.0).unwrap();
64 }
65 }
66
67 #[test]
68 fn to_byte_code() {
69 let op = Operand(13);
70 let mut buf: Vec<u8> = vec![];
71 op.to_byte_code(&mut buf);
72 assert_eq!(&buf[..], [0xd]);
73 }
74}