Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created March 16, 2022 00:11
Show Gist options
  • Save rust-play/5dbf90f3c22fcec9ce0de00cb87f4273 to your computer and use it in GitHub Desktop.
Save rust-play/5dbf90f3c22fcec9ce0de00cb87f4273 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[derive(Debug)]
struct Context<'a> {
child: Ui,
parent: &'a mut Ui,
}
struct ContextManager<'a> {
f: Box<dyn Fn(&mut Context)>,
ctx: Context<'a>,
}
impl<'a> ContextManager<'_> {
fn new(f: impl Fn(&mut Context) + 'static, ctx: Context<'a>) -> ContextManager<'a> {
ContextManager{f: Box::new(f), ctx}
}
fn exit(&mut self) {
(self.f)(&mut self.ctx);
}
fn horizontal(&mut self) -> ContextManager {
self.ctx.child.horizontal()
}
}
impl Drop for ContextManager<'_> {
fn drop(&mut self) {
self.exit();
}
}
use core::fmt::Debug;
impl Debug for ContextManager<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "ContextManager{{ctx={:?}}}", self.ctx)
}
}
#[derive(Debug)]
struct Ui {
id: u64,
parent: u64,
mutable: u64,
}
impl Ui {
fn allocate_ui_with_layout_dyn(&mut self) -> ContextManager {
let child = Ui{id: self.id + 1, parent: self.id, mutable: 0};
ContextManager::new(|ctx| {
println!("deferred exit {:?}", ctx);
ctx.child.mutable = 1;
ctx.parent.mutable = 1;
}, Context{child: child, parent: self})
}
fn horizontal_with_main_wrap_dyn(&mut self, main_wrap: bool) -> ContextManager {
self.allocate_ui_with_layout_dyn()
}
fn horizontal(&mut self) -> ContextManager {
self.horizontal_with_main_wrap_dyn(false)
}
}
fn main() {
let mut root = Ui{parent: 0, id: 0, mutable: 0};
println!("root {:?}", root);
{
let mut ui = root.horizontal();
println!("ui 1 {:?}", ui);
{
let mut ui = ui.horizontal();
println!("ui 2 {:?}", ui);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment