Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update dis_macro and add ref dis injection #19

Merged
merged 5 commits into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions src/haystack/encoding/decode_ref_dis_factory.rs
Original file line number Diff line number Diff line change
@@ -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 encoded/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<str>`. At some point we'll make `Ref` a little
/// more flexible regarding how it holds its display data.
type RefDisFactoryFunc<'a> = Box<dyn Fn(&str, Option<&str>) -> Option<Cow<'a, str>> + Send + Sync>;

/// Holds the Ref factory function used for creating Refs.
static REF_DIS_FACTORY_FUNC: RwLock<Option<RefDisFactoryFunc>> = 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<Cow<'a, str>> {
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<RefDisFactoryFunc<'static>>) {
*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);
}
}
36 changes: 22 additions & 14 deletions src/haystack/encoding/json/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -103,7 +104,18 @@ impl<'de> Deserialize<'de> for Ref {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Ref, D::Error> {
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());

Ok(if dis.as_deref() == val.dis.as_deref() {
val
} else {
Ref {
value: val.value,
dis: dis.map(|d| d.into_owned()),
}
})
}
_ => Err(D::Error::custom("Invalid Hayson Ref")),
}
}
Expand Down Expand Up @@ -375,21 +387,17 @@ fn parse_number(dict: &Dict) -> Result<HVal, JsonErr> {
}

fn parse_ref(dict: &Dict) -> Result<HVal, JsonErr> {
match dict.get_str("val") {
Some(val) => match dict.get_str("dis") {
Some(dis) => Ok(Ref {
dict.get_str("val")
.map(|val| {
let dis_str = dict.get_str("dis").map(|d| d.as_str());
let dis = get_ref_dis_from_factory(&val.value, dis_str).map(|val| val.into_owned());
Ref {
value: val.value.clone(),
dis: Some(dis.value.clone()),
dis,
}
.into()),
None => Ok(Ref {
value: val.value.clone(),
dis: None,
}
.into()),
},
None => Err(JsonErr::custom("Missing or invalid 'val'")),
}
.into()
})
.ok_or_else(|| JsonErr::custom("Missing or invalid 'val'"))
}

fn parse_symbol(dict: &Dict) -> Result<HVal, JsonErr> {
Expand Down
17 changes: 12 additions & 5 deletions src/haystack/encoding/json/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@

use chrono::SecondsFormat;

use crate::haystack::val::{
Column, Coord, Date, DateTime, Dict, Grid, Marker, Na, Number, Ref, Remove, Symbol, Time, Uri,
Value as HVal, XStr,
use crate::{
encoding::decode_ref_dis_factory::get_ref_dis_from_factory,
haystack::val::{
Column, Coord, Date, DateTime, Dict, Grid, Marker, Na, Number, Ref, Remove, Symbol, Time,
Uri, Value as HVal, XStr,
},
};

use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer};
Expand Down Expand Up @@ -54,8 +57,12 @@ impl Serialize for Ref {
let mut map = serializer.serialize_map(Some(if self.dis.is_none() { 2 } else { 3 }))?;
map.serialize_entry("_kind", "ref")?;
map.serialize_entry("val", &self.value)?;
if self.dis.is_some() {
let dis = self.dis.clone();

let dis = get_ref_dis_from_factory(self.value.as_str(), self.dis.as_deref())
.map(|v| v.into_owned())
.or_else(|| self.dis.clone());

if dis.is_some() {
map.serialize_entry("dis", &dis)?;
}
map.end()
Expand Down
2 changes: 2 additions & 0 deletions src/haystack/encoding/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@
pub mod json;
#[cfg(feature = "zinc")]
pub mod zinc;

pub mod decode_ref_dis_factory;
6 changes: 5 additions & 1 deletion src/haystack/val/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
};
Expand Down
13 changes: 7 additions & 6 deletions src/haystack/val/dis_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Cow<'a, Value>>,
GetLocalizedFunc: Fn(&str) -> Option<Cow<'a, str>>,
{
get_value: &'b GetValueFunc,
Expand All @@ -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<Cow<'a, Value>>,
GetLocalizedFunc: Fn(&str) -> Option<Cow<'a, str>>,
{
fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) {
Expand All @@ -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());
Expand Down Expand Up @@ -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<Cow<'a, Value>>,
GetLocalizedFunc: Fn(&str) -> Option<Cow<'a, str>>,
{
// Cache the regular expression in memory so it doesn't need to compile on each invocation.
Expand Down Expand Up @@ -103,7 +103,7 @@ mod test {

static DICT: OnceLock<Dict> = OnceLock::new();

fn dict_cb<'a>(name: &str) -> Option<&'a Value> {
fn dict_cb<'a>(name: &str) -> Option<Cow<'a, Value>> {
DICT.get_or_init(|| {
dict![
"equipRef" => Value::make_ref("ref"),
Expand All @@ -114,6 +114,7 @@ mod test {
]
})
.get(name)
.map(|val| Cow::Borrowed(val))
}

fn i18n_cb<'a>(name: &str) -> Option<Cow<'a, str>> {
Expand Down
Loading