|
| 1 | +mod mermaid { |
| 2 | + struct Data { |
| 3 | + contents: String, |
| 4 | + i: i32, |
| 5 | + } |
| 6 | + pub struct Canvas { |
| 7 | + instance: std::cell::RefCell<Data>, |
| 8 | + } |
| 9 | + pub struct Participant<'a> { |
| 10 | + canvas: &'a Canvas, |
| 11 | + i: i32, |
| 12 | + _name: String, |
| 13 | + } |
| 14 | + impl Canvas { |
| 15 | + pub fn new() -> Self { |
| 16 | + Self { |
| 17 | + instance: std::cell::RefCell::new(Data { |
| 18 | + contents: "sequenceDiagram\n create participant I0 as root\n autonumber\n".to_string(), |
| 19 | + i: 0, |
| 20 | + }), |
| 21 | + } |
| 22 | + } |
| 23 | + pub fn new_participant<S: AsRef<str>>(&self, s: S) -> Participant { |
| 24 | + let mut data = self.instance.borrow_mut(); |
| 25 | + let curr_i = { |
| 26 | + let i: &mut i32 = &mut data.i; |
| 27 | + *i = *i + 1; |
| 28 | + *i |
| 29 | + }; |
| 30 | + Canvas::append_into( |
| 31 | + data, |
| 32 | + &format!(" create participant I{} as {}\n I0-->>I{}: create\n", curr_i, s.as_ref(), curr_i), |
| 33 | + ); |
| 34 | + Participant { canvas: self, i: curr_i, _name: String::from(s.as_ref()) } |
| 35 | + } |
| 36 | + fn append_into<S: AsRef<str>>(mut data: std::cell::RefMut<Data>, s: S) { |
| 37 | + data.contents.push_str(s.as_ref()); |
| 38 | + } |
| 39 | + fn append<S: AsRef<str>>(&self, s: S) { |
| 40 | + Canvas::append_into(self.instance.borrow_mut(), s.as_ref()); |
| 41 | + } |
| 42 | + pub fn output<F>(&self, f: F) |
| 43 | + where |
| 44 | + F: FnOnce(&String), |
| 45 | + { |
| 46 | + f(&self.instance.borrow().contents) |
| 47 | + } |
| 48 | + } |
| 49 | + impl<'a> Participant<'a> { |
| 50 | + pub fn add_arrow_to(&self, rhs: &Participant, text: &str) { |
| 51 | + self.canvas.append(format!(" I{}->>I{}: {}\n", self.i, rhs.i, text)); |
| 52 | + } |
| 53 | + } |
| 54 | + impl<'a> Drop for Participant<'a> { |
| 55 | + fn drop(&mut self) { |
| 56 | + self.canvas.append(format!(" destroy I{}\n I{}-->>I0: destroy\n", self.i, self.i)); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +use mermaid::Canvas; |
| 62 | +//use medmaid::Participant; |
| 63 | + |
| 64 | +fn main() { |
| 65 | + let canvas = Canvas::new(); |
| 66 | + |
| 67 | + { |
| 68 | + canvas.new_participant("foo"); |
| 69 | + } |
| 70 | + { |
| 71 | + let bar = canvas.new_participant("bar"); |
| 72 | + { |
| 73 | + let baz = canvas.new_participant("baz"); |
| 74 | + bar.add_arrow_to(&baz, "Hello!"); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + { |
| 79 | + let meh = canvas.new_participant("meh"); |
| 80 | + { |
| 81 | + let blah = canvas.new_participant("blah"); |
| 82 | + blah.add_arrow_to(&meh, "Whoa!"); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + canvas.output(|s| println!("{}", s)); |
| 87 | +} |
0 commit comments