refactor: fine-grained interior mutability for scenegraph

This commit is contained in:
Nova
2022-06-06 21:34:42 -04:00
parent bb26038030
commit 2c27e5728c
5 changed files with 55 additions and 76 deletions

View File

@@ -1,14 +1,14 @@
use crate::core::client::Client;
use crate::nodes::spatial::Spatial;
use anyhow::{anyhow, ensure, Result};
use rccell::{RcCell, WeakCell};
use anyhow::{anyhow, Result};
use std::rc::{Rc, Weak};
use std::{collections::HashMap, vec::Vec};
pub type Signal<'a> = Box<dyn Fn(RcCell<Client>, &[u8]) -> Result<()> + 'a>;
pub type Method<'a> = Box<dyn Fn(RcCell<Client>, &[u8]) -> Result<Vec<u8>> + 'a>;
pub type Signal<'a> = Box<dyn Fn(Rc<Client>, &[u8]) -> Result<()> + 'a>;
pub type Method<'a> = Box<dyn Fn(Rc<Client>, &[u8]) -> Result<Vec<u8>> + 'a>;
pub struct Node<'a> {
client: WeakCell<Client<'a>>,
client: Weak<Client<'a>>,
path: String,
trailing_slash_pos: usize,
local_signals: HashMap<String, Signal<'a>>,
@@ -19,7 +19,7 @@ pub struct Node<'a> {
}
impl<'a> Node<'a> {
pub fn get_client(&self) -> Option<RcCell<Client<'a>>> {
pub fn get_client(&self) -> Option<Rc<Client<'a>>> {
self.client.clone().upgrade()
}
pub fn get_name(&self) -> &str {
@@ -29,18 +29,13 @@ impl<'a> Node<'a> {
self.path.as_str()
}
pub fn create(
client: WeakCell<Client<'a>>,
parent: &str,
name: &str,
destroyable: bool,
) -> Self {
pub fn create(client: Weak<Client<'a>>, parent: &str, name: &str, destroyable: bool) -> Self {
let mut path = parent.to_string();
path.push('/');
path.push_str(name);
Node {
client,
path: path,
path,
trailing_slash_pos: parent.len(),
local_signals: HashMap::new(),
local_methods: HashMap::new(),
@@ -55,7 +50,7 @@ impl<'a> Node<'a> {
pub fn send_local_signal(
&self,
calling_client: RcCell<Client>,
calling_client: Rc<Client>,
method: &str,
data: &[u8],
) -> Result<()> {
@@ -67,7 +62,7 @@ impl<'a> Node<'a> {
}
pub fn execute_local_method(
&self,
calling_client: RcCell<Client>,
calling_client: Rc<Client>,
method: &str,
data: &[u8],
) -> Result<Vec<u8>> {
@@ -77,8 +72,7 @@ impl<'a> Node<'a> {
}
pub fn send_remote_signal(&self, method: &str, data: &[u8]) -> Result<()> {
self.get_client()
.ok_or(anyhow!("Node has no client, can't send remote signal!"))?
.borrow()
.ok_or_else(|| anyhow!("Node has no client, can't send remote signal!"))?
.get_messenger()
.send_remote_signal(self.path.as_str(), method, data)
.map_err(|_| anyhow!("Unable to write in messenger"))
@@ -90,8 +84,7 @@ impl<'a> Node<'a> {
callback: Box<dyn Fn(&[u8]) + 'a>,
) -> Result<()> {
self.get_client()
.ok_or(anyhow!("Node has no client, can't send remote signal!"))?
.borrow()
.ok_or_else(|| anyhow!("Node has no client, can't send remote signal!"))?
.get_messenger()
.execute_remote_method(self.path.as_str(), method, data, callback)
.map_err(|_| anyhow!("Unable to write in messenger"))