From 4de024a6423782885c1c3bc6c3a9b790f32d799e Mon Sep 17 00:00:00 2001 From: Gareth Johnson Date: Fri, 23 Feb 2024 11:03:59 +0000 Subject: [PATCH] Update dis_macro and add ref dis injectiond --- .../encoding/decode_ref_dis_factory.rs | 65 +++++++++++++++++++ src/haystack/encoding/json/decode.rs | 41 +++++++++--- src/haystack/encoding/mod.rs | 2 + src/haystack/val/dict.rs | 6 +- src/haystack/val/dis_macro.rs | 13 ++-- 5 files changed, 111 insertions(+), 16 deletions(-) create mode 100644 src/haystack/encoding/decode_ref_dis_factory.rs diff --git a/src/haystack/encoding/decode_ref_dis_factory.rs b/src/haystack/encoding/decode_ref_dis_factory.rs new file mode 100644 index 0000000..a15c835 --- /dev/null +++ b/src/haystack/encoding/decode_ref_dis_factory.rs @@ -0,0 +1,65 @@ +// Copyright (C) 2020 - 2024, J2 Innovations + +use std::borrow::Cow; +use std::sync::RwLock; + +/// Enables display values to be injected into decoded Ref objects. +/// +/// This is used to handle the case whereby pre-calculated display +/// names for Refs need to be utilized when encoding/decoding haystack data. +/// +/// Please note, the return type is a `Cow`. At some point we'll make `Ref` a little +/// more flexible regarding how it holds its display data and hence its usage. +type RefDisFactoryFunc<'a> = Box) -> Option> + Send + Sync>; + +/// Holds the Ref factory function used for creating Refs. +static REF_DIS_FACTORY_FUNC: RwLock> = RwLock::new(None); + +/// Get a ref's display name value from any registered factory. +pub fn get_ref_dis_from_factory<'a>(val: &str, dis: Option<&'a str>) -> Option> { + if let Some(func) = REF_DIS_FACTORY_FUNC.read().unwrap().as_ref() { + func(val, dis) + } else { + dis.map(Cow::Borrowed) + } +} + +/// Set the factory function for getting ref display name values. +pub fn set_ref_dis_factory(factory_fn: Option>) { + *REF_DIS_FACTORY_FUNC.write().unwrap() = factory_fn; +} + +#[cfg(test)] +mod test { + use std::{borrow::Cow, sync::Mutex}; + + use super::{get_ref_dis_from_factory, set_ref_dis_factory}; + + // Use a mutex to prevent unit tests from interfering with each other. One of the tests + // sets some global data so they can overlap. + static MUTEX: Mutex<()> = Mutex::new(()); + + #[test] + fn make_ref_returns_ref() { + let _ = MUTEX.lock(); + + let dis = get_ref_dis_from_factory("a", Some("c")); + + assert_eq!(dis, Some(Cow::Borrowed("c"))); + } + + #[test] + fn make_ref_from_factory_returns_ref() { + let _ = MUTEX.lock(); + + let factory_fn = Box::new(|_: &str, _: Option<&str>| Some(Cow::Owned(String::from("c")))); + + set_ref_dis_factory(Some(factory_fn)); + + let dis = get_ref_dis_from_factory("a", Some("b")); + + assert_eq!(dis, Some(Cow::Borrowed("c"))); + + set_ref_dis_factory(None); + } +} diff --git a/src/haystack/encoding/json/decode.rs b/src/haystack/encoding/json/decode.rs index 7f789e2..0bbdb20 100644 --- a/src/haystack/encoding/json/decode.rs +++ b/src/haystack/encoding/json/decode.rs @@ -3,6 +3,7 @@ //! //! Implement Hayson decoding //! +use crate::encoding::decode_ref_dis_factory::get_ref_dis_from_factory; use crate::haystack::val::{ Column, Coord, Date, DateTime, Dict, Grid, HaystackDict, List, Marker, Na, Number, Ref, Remove, Str, Symbol, Time, Uri, Value as HVal, XStr, @@ -103,7 +104,19 @@ impl<'de> Deserialize<'de> for Ref { fn deserialize>(deserializer: D) -> Result { let val = deserializer.deserialize_any(HValVisitor)?; match val { - HVal::Ref(val) => Ok(val), + HVal::Ref(val) => { + let dis = get_ref_dis_from_factory(val.value.as_str(), val.dis.as_deref()) + .map(|v| v.to_string()); + + Ok(if dis == val.dis { + val + } else { + Ref { + value: val.value, + dis, + } + }) + } _ => Err(D::Error::custom("Invalid Hayson Ref")), } } @@ -377,16 +390,26 @@ fn parse_number(dict: &Dict) -> Result { fn parse_ref(dict: &Dict) -> Result { match dict.get_str("val") { Some(val) => match dict.get_str("dis") { - Some(dis) => Ok(Ref { - value: val.value.clone(), - dis: Some(dis.value.clone()), + Some(dis) => { + let dis = get_ref_dis_from_factory(val.value.as_str(), Some(dis.as_str())) + .map(|val| val.to_string()); + + Ok(Ref { + value: val.value.clone(), + dis, + } + .into()) } - .into()), - None => Ok(Ref { - value: val.value.clone(), - dis: None, + None => { + let dis = + get_ref_dis_from_factory(val.value.as_str(), None).map(|val| val.to_string()); + + Ok(Ref { + value: val.value.clone(), + dis, + } + .into()) } - .into()), }, None => Err(JsonErr::custom("Missing or invalid 'val'")), } diff --git a/src/haystack/encoding/mod.rs b/src/haystack/encoding/mod.rs index eeb7bac..6a32bb0 100644 --- a/src/haystack/encoding/mod.rs +++ b/src/haystack/encoding/mod.rs @@ -7,3 +7,5 @@ pub mod json; #[cfg(feature = "zinc")] pub mod zinc; + +pub mod decode_ref_dis_factory; diff --git a/src/haystack/val/dict.rs b/src/haystack/val/dict.rs index e27e729..9ebd99b 100644 --- a/src/haystack/val/dict.rs +++ b/src/haystack/val/dict.rs @@ -386,7 +386,11 @@ where if let Some(val) = dict.get("disMacro") { return if let Value::Str(val) = val { - dis_macro(&val.value, |val| dict.get(val), get_localized) + dis_macro( + &val.value, + |val| dict.get(val).map(Cow::Borrowed), + get_localized, + ) } else { decode_str_from_value(val) }; diff --git a/src/haystack/val/dis_macro.rs b/src/haystack/val/dis_macro.rs index 6e3ed07..32ce63a 100644 --- a/src/haystack/val/dis_macro.rs +++ b/src/haystack/val/dis_macro.rs @@ -9,7 +9,7 @@ use regex::{Captures, Regex, Replacer}; /// values in a display macro string. struct DisReplacer<'a, 'b, GetValueFunc, GetLocalizedFunc> where - GetValueFunc: Fn(&str) -> Option<&'a Value>, + GetValueFunc: Fn(&str) -> Option>, GetLocalizedFunc: Fn(&str) -> Option>, { get_value: &'b GetValueFunc, @@ -20,7 +20,7 @@ where impl<'a, 'b, GetValueFunc, GetLocalizedFunc> Replacer for DisReplacer<'a, 'b, GetValueFunc, GetLocalizedFunc> where - GetValueFunc: Fn(&str) -> Option<&'a Value>, + GetValueFunc: Fn(&str) -> Option>, GetLocalizedFunc: Fn(&str) -> Option>, { fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) { @@ -29,9 +29,9 @@ where // Replace $tag or ${tag} if let Some(cap_match) = caps.get(2).or_else(|| caps.get(4)) { if let Some(value) = (self.get_value)(cap_match.as_str()) { - if let Value::Ref(val) = value { + if let Value::Ref(val) = value.as_ref() { dst.push_str(val.dis.as_ref().unwrap_or(&val.value)); - } else if let Value::Str(val) = value { + } else if let Value::Str(val) = value.as_ref() { dst.push_str(&val.value); } else { dst.push_str(&value.to_string()); @@ -70,7 +70,7 @@ pub fn dis_macro<'a, GetValueFunc, GetLocalizedFunc>( get_localized: GetLocalizedFunc, ) -> Cow<'a, str> where - GetValueFunc: Fn(&str) -> Option<&'a Value>, + GetValueFunc: Fn(&str) -> Option>, GetLocalizedFunc: Fn(&str) -> Option>, { // Cache the regular expression in memory so it doesn't need to compile on each invocation. @@ -103,7 +103,7 @@ mod test { static DICT: OnceLock = OnceLock::new(); - fn dict_cb<'a>(name: &str) -> Option<&'a Value> { + fn dict_cb<'a>(name: &str) -> Option> { DICT.get_or_init(|| { dict![ "equipRef" => Value::make_ref("ref"), @@ -114,6 +114,7 @@ mod test { ] }) .get(name) + .map(|val| Cow::Borrowed(val)) } fn i18n_cb<'a>(name: &str) -> Option> {