From 7b8f091ab3937c4828be403605e6d4c7af9c888d Mon Sep 17 00:00:00 2001 From: Quaternions Date: Fri, 4 Oct 2024 21:08:28 -0700 Subject: [PATCH] deduplicate more find code --- src/runner/instance.rs | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/src/runner/instance.rs b/src/runner/instance.rs index e52caf2..a850ac1 100644 --- a/src/runner/instance.rs +++ b/src/runner/instance.rs @@ -29,6 +29,13 @@ fn get_full_name(dom:&rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance)->S full_name } +pub fn find_first_child<'a>(dom:&'a rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance,name:&str)->Option<&'a rbx_dom_weak::Instance>{ + instance.children().iter().filter_map(|&r|dom.get_by_ref(r)).find(|inst|inst.name==name) +} +pub fn find_first_descendant<'a>(dom:&'a rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance,name:&str)->Option<&'a rbx_dom_weak::Instance>{ + dom.descendants_of(instance.referent()).find(|&inst|inst.name==name) +} + pub fn find_first_child_of_class<'a>(dom:&'a rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance,class:&str)->Option<&'a rbx_dom_weak::Instance>{ instance.children().iter().filter_map(|&r|dom.get_by_ref(r)).find(|inst|inst.class==class) } @@ -171,10 +178,8 @@ impl Instance{ let instance=this.get(dom)?; Ok( match search_descendants.unwrap_or(false){ - true=>dom.descendants_of(this.referent()).find(|inst|inst.name==name_str), - false=>instance.children().iter().filter_map(|&r| - dom.get_by_ref(r) - ).find(|inst|inst.name==name_str), + true=>find_first_descendant(dom,instance,name_str), + false=>find_first_child(dom,instance,name_str), } .map(|instance| Instance::new(instance.referent()) @@ -192,7 +197,9 @@ impl Instance{ true=>find_first_descendant_of_class(dom,this.get(dom)?,class_str), false=>find_first_child_of_class(dom,this.get(dom)?,class_str), } - .map(|inst|(Instance::new(inst.referent()))) + .map(|instance| + Instance::new(instance.referent()) + ) ) }) }); @@ -232,13 +239,9 @@ impl Instance{ } //find a child with a matching name Ok( - instance.children() - .iter() - .find(|&&r| - dom.get_by_ref(r) - .is_some_and(|instance|instance.name==index_str) - ) - .map(|&referent|Instance::new(referent)).into_lua(lua) + find_first_child(dom,instance,index_str) + .map(|instance|Instance::new(instance.referent())) + .into_lua(lua) ) }) }); @@ -320,15 +323,11 @@ impl DataModel{ dom(lua,|dom|{ match service.as_str(){ "Lighting"=>{ - let referent=dom.root() - .children() - .iter() - .find(|&&c| - dom.get_by_ref(c).is_some_and(|c|c.class=="Lighting") - ).map(|r|*r) - .unwrap_or_else(|| - dom.insert(dom.root_ref(),InstanceBuilder::new("Lighting")) - ); + let referent=find_first_child_of_class(dom,dom.root(),"Lighting") + .map(|instance|instance.referent()) + .unwrap_or_else(|| + dom.insert(dom.root_ref(),InstanceBuilder::new("Lighting")) + ); Lighting::new(referent).into_lua(lua) }, other=>Err::(mlua::Error::runtime(format!("Service '{other}' not supported"))),