Skip to content

Commit c07cf37

Browse files
authored
Merge pull request #3 from trueaywee/main
Making it Rusty
2 parents e40474e + b5fd9db commit c07cf37

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

step03_mermaid/code/src/main.rs

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
mod mermaid {
2+
use std::cell::RefCell;
3+
use std::fmt;
24
struct Data {
35
contents: String,
46
i: i32,
57
}
68
pub struct Canvas {
7-
instance: std::cell::RefCell<Data>,
9+
instance: RefCell<Data>,
810
}
911
pub struct Participant<'a> {
1012
canvas: &'a Canvas,
@@ -14,30 +16,34 @@ mod mermaid {
1416
impl Canvas {
1517
pub fn new() -> Self {
1618
Self {
17-
instance: std::cell::RefCell::new(Data {
19+
instance: RefCell::new(Data {
1820
contents: "sequenceDiagram\n create participant I0 as root\n autonumber\n".to_string(),
1921
i: 0,
2022
}),
2123
}
2224
}
23-
pub fn new_participant<S: AsRef<str>>(&self, s: S) -> Participant {
25+
26+
pub fn new_participant<S: Into<String>>(&self, s: S) -> Participant {
27+
let s = s.into();
2428
let mut data = self.instance.borrow_mut();
2529
data.i += 1;
26-
let i = data.i; // or can just use data.i later on, doesn't matter
30+
let i = data.i;
2731
drop(data);
28-
self.append(&format!(" create participant I{} as {}\n I0-->>I{}: create\n", i, s.as_ref(), i));
29-
Participant { canvas: self, i, _name: String::from(s.as_ref()) }
32+
self.append(format!(" create participant I{} as {}\n I0-->>I{}: create\n", i, s, i));
33+
Participant { canvas: self, i, _name: s }
3034
}
35+
3136
fn append<S: AsRef<str>>(&self, s: S) {
3237
self.instance.borrow_mut().contents.push_str(s.as_ref());
3338
}
34-
pub fn output<F>(&self, f: F)
35-
where
36-
F: FnOnce(&String),
37-
{
38-
f(&self.instance.borrow().contents)
39+
}
40+
41+
impl fmt::Display for Canvas {
42+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43+
write!(f, "{}", self.instance.borrow().contents)
3944
}
4045
}
46+
4147
impl Participant<'_> {
4248
pub fn add_arrow_to(&self, rhs: &Participant, text: &str) {
4349
self.canvas.append(format!(" I{}->>I{}: {}\n", self.i, rhs.i, text));
@@ -75,5 +81,5 @@ fn main() {
7581
}
7682
}
7783

78-
canvas.output(|s| println!("{}", s));
84+
println!("{}", canvas);
7985
}

0 commit comments

Comments
 (0)