Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created March 15, 2022 19:38
Show Gist options
  • Save rust-play/c618172551bebd4f93d929f870d4baa4 to your computer and use it in GitHub Desktop.
Save rust-play/c618172551bebd4f93d929f870d4baa4 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[derive(Debug)]
struct UiState {
parent: u64,
id: u64,
}
#[derive(Debug)]
struct Result {
rect: u64,
}
#[derive(Debug)]
struct UiContext {
state: UiState,
result: Result,
}
trait UiContextManager {
fn ctx_mut(&mut self) -> &mut UiContext;
fn ctx(&self) -> &UiContext;
fn state(&mut self) -> &mut UiState { &mut self.ctx_mut().state }
fn result(&mut self) -> &mut Result { &mut self.ctx_mut().result }
fn enter(&mut self);
fn exit(&mut self);
}
use core::fmt::Debug;
impl Debug for dyn UiContextManager {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "UiContextManager{{{:?}}}", self.ctx())
}
}
struct AllocUiContext {
_ctx: UiContext,
}
impl UiContextManager for AllocUiContext {
fn ctx_mut(&mut self) -> &mut UiContext { &mut self._ctx }
fn ctx(&self) -> &UiContext { &self._ctx }
fn enter(&mut self) {
}
fn exit(&mut self) {
}
}
impl Drop for AllocUiContext {
fn drop(&mut self) { self.exit(); }
}
trait Ui {
fn state(&mut self) -> &mut UiState;
fn allocate_ui_with_layout_dyn(&mut self) -> Box<dyn UiContextManager> {
let state = self.state();
let child = UiState{id: state.id + 1, parent: state.id};
let mut ctx = Box::new(AllocUiContext{_ctx: UiContext{state: child, result: Result{rect: 0}}});
ctx.enter();
ctx
}
fn horizontal_with_main_wrap_dyn(&mut self, main_wrap: bool) -> Box<dyn UiContextManager> {
self.allocate_ui_with_layout_dyn()
}
fn horizontal(&mut self) -> Box<dyn UiContextManager> {
self.horizontal_with_main_wrap_dyn(false)
}
}
impl Ui for UiState {
fn state(&mut self) -> &mut UiState { self }
}
impl Ui for dyn UiContextManager {
fn state(&mut self) -> &mut UiState { &mut self.ctx_mut().state }
}
fn main() {
let mut root = UiState{parent: 0, id: 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