Skip to content

Commit 9df3ef5

Browse files
committed
add JSONGetTextBuilder::allow_extra_texts to drop texts missing from the default key
1 parent 5343084 commit 9df3ef5

6 files changed

Lines changed: 59 additions & 14 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ assert_eq!("Hello, world!", get_text!(ctx, "hello").unwrap());
2323
assert_eq!("哈囉,世界!", get_text!(ctx, "zh_TW", "hello").unwrap());
2424
```
2525

26-
The argument before `;` is the **default key**. Every other key may only contain text names that also exist in the default key; this is checked when the context is built.
26+
The argument before `;` is the **default key**. Every other key may only contain text names that also exist in the default key; this is checked when the context is built. To drop such extra texts instead of failing, build with `JSONGetTextBuilder` and call `allow_extra_texts(true)`.
2727

2828
## Looking Up Texts
2929

‎src/common/json_get_text_builder.rs‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,31 @@ use crate::{JSONGetTextBuildError, JSONGetTextValue};
99
/// To build a JSONGetText instance, this struct can help you do that step by step.
1010
#[derive(Debug, Clone)]
1111
pub struct JSONGetTextBuilder<'a> {
12-
default_key: crate::Key,
13-
context: Context<'a>,
12+
default_key: crate::Key,
13+
context: Context<'a>,
14+
allow_extra_texts: bool,
1415
}
1516

1617
impl<'a> JSONGetTextBuilder<'a> {
1718
/// Create a new `JSONGetTextBuilder` instance. You need to decide your default key at this stage.
1819
#[inline]
1920
pub fn new<K: IntoKey>(default_key: K) -> JSONGetTextBuilder<'a> {
2021
JSONGetTextBuilder {
21-
default_key: default_key.into_key(), context: HashMap::new()
22+
default_key: default_key.into_key(),
23+
context: HashMap::new(),
24+
allow_extra_texts: false,
2225
}
2326
}
2427

28+
/// Set whether a non-default key may contain texts that the default key does not define.
29+
/// When enabled, such texts are dropped while building instead of causing a `TextInKeyNotInDefaultKey` error.
30+
#[inline]
31+
pub fn allow_extra_texts(&mut self, allow: bool) -> &mut Self {
32+
self.allow_extra_texts = allow;
33+
34+
self
35+
}
36+
2537
/// Add a JSON string to the context for a specific key. The JSON string must represent a map object (key-value).
2638
pub fn add_json<K: IntoKey, J: AsRef<str> + ?Sized>(
2739
&mut self,
@@ -145,7 +157,11 @@ impl<'a> JSONGetTextBuilder<'a> {
145157

146158
/// Build a `JSONGetText` instance.
147159
pub fn build(self) -> Result<JSONGetText<'a>, JSONGetTextBuildError> {
148-
JSONGetText::from_context_with_default_key(self.default_key, self.context)
160+
JSONGetText::from_context_with_default_key(
161+
self.default_key,
162+
self.context,
163+
self.allow_extra_texts,
164+
)
149165
}
150166
}
151167

‎src/common/json_gettext.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,9 @@ impl<'a> JSONGetText<'a> {
2424
pub(crate) fn from_context_with_default_key(
2525
default_key: crate::Key,
2626
context: Context<'a>,
27+
allow_extra_texts: bool,
2728
) -> Result<JSONGetText<'a>, JSONGetTextBuildError> {
28-
let context = text_lookup::finalize_context(&default_key, context)?;
29+
let context = text_lookup::finalize_context(&default_key, context, allow_extra_texts)?;
2930

3031
Ok(JSONGetText {
3132
default_key,

‎src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ assert_eq!("Hello, world!", get_text!(ctx, "hello").unwrap());
2121
assert_eq!("哈囉,世界!", get_text!(ctx, "zh_TW", "hello").unwrap());
2222
```
2323
24-
The argument before `;` is the **default key**. Every other key may only contain text names that also exist in the default key; this is checked when the context is built.
24+
The argument before `;` is the **default key**. Every other key may only contain text names that also exist in the default key; this is checked when the context is built. To drop such extra texts instead of failing, build with [`JSONGetTextBuilder`] and call `allow_extra_texts(true)`.
2525
2626
## Looking Up Texts
2727

‎src/text_lookup.rs‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@ type TextMap<'a> = HashMap<String, JSONGetTextValue<'a>>;
1010

1111
/// Validate that every non-default key only contains texts that also exist in the default key.
1212
/// Each key keeps only its own texts; missing texts are resolved at lookup time by falling back to the default key.
13+
/// When `allow_extra_texts` is `true`, texts that the default key does not define are dropped instead of causing an error.
1314
pub(crate) fn finalize_context<'a>(
1415
default_key: &Key,
1516
mut context: Context<'a>,
17+
allow_extra_texts: bool,
1618
) -> Result<Context<'a>, JSONGetTextBuildError> {
1719
// Recover the owned key from the map so it can be re-inserted without cloning.
1820
let (default_key, default_map) = match context.remove_entry(default_key) {
@@ -22,13 +24,17 @@ pub(crate) fn finalize_context<'a>(
2224

2325
let mut inner_context = HashMap::with_capacity(context.len() + 1);
2426

25-
for (key, map) in context {
26-
for map_key in map.keys() {
27-
if !default_map.contains_key(map_key) {
28-
return Err(JSONGetTextBuildError::TextInKeyNotInDefaultKey {
29-
key,
30-
text: map_key.clone(),
31-
});
27+
for (key, mut map) in context {
28+
if allow_extra_texts {
29+
map.retain(|text, _| default_map.contains_key(text));
30+
} else {
31+
for map_key in map.keys() {
32+
if !default_map.contains_key(map_key) {
33+
return Err(JSONGetTextBuildError::TextInKeyNotInDefaultKey {
34+
key,
35+
text: map_key.clone(),
36+
});
37+
}
3238
}
3339
}
3440

‎tests/allow_extra_texts.rs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#![cfg(not(feature = "langid"))]
2+
3+
use json_gettext::JSONGetText;
4+
5+
#[test]
6+
fn allow_extra_texts_drops_unknown() {
7+
let mut builder = JSONGetText::build("en_US");
8+
9+
builder.allow_extra_texts(true);
10+
builder.add_json_owned("en_US", r#"{"hello": "Hello, world!"}"#).unwrap();
11+
builder.add_json_owned("zh_TW", r#"{"hello": "哈囉,世界!", "extra": "額外"}"#).unwrap();
12+
13+
let ctx = builder.build().unwrap();
14+
15+
assert_eq!("哈囉,世界!", ctx.get_text_with_key("zh_TW", "hello").unwrap());
16+
17+
// The text `extra` is not in the default key, so it was dropped while building.
18+
let map = ctx.get("zh_TW");
19+
20+
assert!(map.get("hello").is_some());
21+
assert!(map.get("extra").is_none());
22+
}

0 commit comments

Comments
 (0)