Last active
February 8, 2022 15:00
-
-
Save KillerGoldFisch/3851e5ec76a8fcd1693b8029481cc803 to your computer and use it in GitHub Desktop.
Working with references in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cell::RefCell; | |
use std::rc::Rc; | |
struct InternalWriter { | |
indent_count: u32, | |
stringwriter: String | |
} | |
impl InternalWriter { | |
fn new() -> InternalWriter { | |
InternalWriter { | |
indent_count: 0, | |
stringwriter: String::new() | |
} | |
} | |
} | |
#[derive(Clone)] | |
struct Writer { | |
internalwriter: Rc<RefCell<InternalWriter>> | |
} | |
impl Writer { | |
fn new() -> Writer { | |
Writer { | |
internalwriter: Rc::new(RefCell::new(InternalWriter::new())) | |
} | |
} | |
fn write(&self, s: &str) { | |
let mut writer = self.internalwriter.borrow_mut(); | |
for _ in 0..writer.indent_count { | |
writer.stringwriter.push_str(" "); | |
} | |
writer.stringwriter.push_str(s); | |
} | |
fn writeline(&self, s: &str) { | |
self.write(s); | |
self.write("\n"); | |
// self.write(format!("{}{}", s, "\n").as_str()); | |
} | |
fn indent(&self) { | |
let mut writer = self.internalwriter.borrow_mut(); | |
writer.indent_count += 1; | |
} | |
fn dedent(&self) { | |
let mut writer = self.internalwriter.borrow_mut(); | |
writer.indent_count -= 1; | |
} | |
fn context(&self) -> Context { | |
Context::new(self.clone()) | |
} | |
} | |
struct Context { | |
writer: Writer | |
} | |
impl Context { | |
// Open context | |
fn new(writer: Writer) -> Context { | |
writer.writeline("{"); | |
writer.indent(); | |
Context { | |
writer: writer | |
} | |
} | |
} | |
// Close context | |
impl Drop for Context { | |
fn drop(&mut self) { | |
self.writer.dedent(); | |
self.writer.writeline("}"); | |
} | |
} | |
fn main() { | |
let writer = Writer::new(); | |
writer.writeline("let x = 1;"); | |
writer.writeline("let y = 2;"); | |
{ // Opens context | |
let _context = writer.context(); //Context::new(writer.clone()); | |
writer.writeline("let z = 3;"); | |
} // Closes context | |
{ | |
let iwriter = writer.internalwriter.borrow(); | |
println!("{}", iwriter.stringwriter); | |
// Output: | |
// let x = 1; | |
// let y = 2; | |
// { | |
// let z = 3; | |
// } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment