stack_vm/from_byte_code.rs
1//! Code deserializer.
2//!
3//! If you wish to be able to load serialized bytecode into your virtual
4//! machine to use again.
5
6use std::io::Read;
7
8/// Convert from byte code to a type.
9///
10/// This trait represents the ability to load your Operands from bytecode.
11/// `stack-vm` uses the [`rmp`](https://crates.io/crates/rmp) crate to load
12/// bytecode from a MsgPack encoded binary.
13///
14/// See the [`rmp` docs](https://docs.rs/rmp/0.8.7/rmp/) to find out which
15/// functions you can use to write out your types.
16pub trait FromByteCode {
17 /// Convert from MsgPack to your type.
18 ///
19 /// This function takes a mutable reference of type `Read` and returns your
20 /// operand type.
21 ///
22 /// ## Example
23 ///
24 /// ```
25 /// # extern crate rmp;
26 /// # extern crate stack_vm;
27 /// # use stack_vm::FromByteCode;
28 /// # use std::io::Read;
29 ///
30 /// #[derive(PartialEq, Debug)]
31 /// struct Operand(i64);
32 ///
33 /// impl FromByteCode for Operand {
34 /// fn from_byte_code(mut buf: &mut Read) -> Operand {
35 /// let value = rmp::decode::read_int(&mut buf).unwrap();
36 /// Operand(value)
37 /// }
38 /// }
39 /// # fn main() {
40 /// let bytecode = [0xd];
41 /// assert_eq!(Operand(13), Operand::from_byte_code(&mut &bytecode[..]));
42 /// # }
43 /// ```
44 fn from_byte_code(_: &mut Read) -> Self;
45}
46
47#[cfg(test)]
48mod test {
49 use super::*;
50 use rmp;
51
52 #[derive(PartialEq, Debug)]
53 struct Operand(i64);
54
55 impl FromByteCode for Operand {
56 fn from_byte_code(mut buf: &mut Read) -> Operand {
57 let i = rmp::decode::read_int(&mut buf).unwrap();
58 Operand(i)
59 }
60 }
61
62 #[test]
63 fn from_byte_code() {
64 let bytecode = [0xd];
65 assert_eq!(Operand(13), Operand::from_byte_code(&mut &bytecode[..]));
66 }
67}