managed_heap/lib.rs
1//! An implementation of virtual heap, inspired by VMs like the JVM.
2//! It can be used while creating your own virtual machine in Rust.
3//!
4//! To use it, you have to implement the traits in the trace module.
5//!
6//! # Example
7//! ```
8//! extern crate managed_heap;
9//!
10//! use managed_heap::managed::*;
11//! use managed_heap::trace::*;
12//! use managed_heap::address::*;
13//!
14//! struct MockGcRoot {
15//! used_elems: Vec<IntegerObject>,
16//! }
17//!
18//! impl MockGcRoot {
19//! pub fn new(used_elems: Vec<IntegerObject>) -> Self {
20//! MockGcRoot { used_elems }
21//! }
22//!
23//! pub fn clear(&mut self) {
24//! self.used_elems.clear();
25//! }
26//! }
27//!
28//! unsafe impl GcRoot<IntegerObject> for MockGcRoot {
29//! fn children<'a>(&'a mut self) -> Box<Iterator<Item = &'a mut IntegerObject> + 'a> {
30//! Box::new(self.used_elems.iter_mut())
31//! }
32//! }
33//!
34//! #[derive(Debug)]
35//! struct IntegerObject(Address);
36//!
37//! impl IntegerObject {
38//! pub fn new(heap: &mut ManagedHeap, value: isize) -> Self {
39//! // reserve one usize for mark byte
40//! let mut address = heap.alloc(2).unwrap();
41//!
42//! address.write(false as usize);
43//! (address + 1).write(value as usize);
44//!
45//! IntegerObject(address)
46//! }
47//!
48//! pub fn get(&self) -> isize {
49//! *(self.0 + 1) as isize
50//! }
51//! }
52//!
53//! impl From<Address> for IntegerObject {
54//! fn from(address: Address) -> Self {
55//! IntegerObject(address)
56//! }
57//! }
58//!
59//! impl Into<Address> for IntegerObject {
60//! fn into(self) -> Address {
61//! self.0
62//! }
63//! }
64//!
65//! unsafe impl Traceable for IntegerObject {
66//! fn mark(&mut self) {
67//! self.0.write(true as usize);
68//! }
69//!
70//! fn unmark(&mut self) {
71//! self.0.write(false as usize);
72//! }
73//!
74//! fn is_marked(&self) -> bool {
75//! (*self.0) != 0
76//! }
77//! }
78//!
79//! let mut heap = ManagedHeap::new(100);
80//! let mut i = IntegerObject::new(&mut heap, -42);
81//!
82//! assert_eq!(-42, i.get());
83//! assert_eq!(false, i.is_marked());
84//!
85//! i.mark();
86//! assert_eq!(true, i.is_marked());
87//! ```
88
89pub mod address;
90mod block;
91mod heap;
92pub mod managed;
93pub mod trace;
94pub mod types;