Skip to content

Commit 9c75f38

Browse files
authored
Allow converting an EventValue into a plain String (#26)
fix #25
1 parent 480e23f commit 9c75f38

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

src/event.rs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,37 @@ impl TryFrom<serde_json::Value> for EventValue {
4949
}
5050

5151
impl EventValue {
52+
/// Returns the string representation of an EventValue
53+
pub fn value_to_string(&self) -> String {
54+
match self {
55+
Self::Value(v) => v.value_to_string(),
56+
Self::Sequence(v) => {
57+
let mut result = "[".to_string();
58+
result.push_str(
59+
v.iter()
60+
.map(|v| v.value_to_string())
61+
.collect::<Vec<String>>()
62+
.join(", ")
63+
.as_str(),
64+
);
65+
result.push(']');
66+
result
67+
}
68+
Self::Map(m) => {
69+
let mut result = "{".to_string();
70+
result.push_str(
71+
m.iter()
72+
.map(|(k, v)| format!("{}: {}", k, v.value_to_string()))
73+
.collect::<Vec<String>>()
74+
.join(", ")
75+
.as_str(),
76+
);
77+
result.push('}');
78+
result
79+
}
80+
}
81+
}
82+
5283
pub(crate) fn contains_keyword(&self, s: &str) -> bool {
5384
match self {
5485
Self::Value(v) => {
@@ -263,6 +294,34 @@ mod tests {
263294
use crate::wildcard::tokenize;
264295
use serde_json::json;
265296

297+
#[test]
298+
fn test_event_value_to_string() {
299+
let event_value = EventValue::Value(BaseValue::String("test".to_string()));
300+
assert_eq!(event_value.value_to_string(), "test");
301+
302+
let event_value = EventValue::Sequence(vec![
303+
EventValue::Value(BaseValue::String("test".to_string())),
304+
EventValue::Value(BaseValue::Int(42)),
305+
]);
306+
307+
assert_eq!(event_value.value_to_string(), "[test, 42]");
308+
309+
let event_value = EventValue::Map({
310+
let mut map = HashMap::new();
311+
map.insert(
312+
"key".to_string(),
313+
EventValue::Value(BaseValue::String("test".to_string())),
314+
);
315+
map.insert("number".to_string(), EventValue::Value(BaseValue::Int(42)));
316+
map
317+
});
318+
319+
assert!(
320+
event_value.value_to_string() == "{key: test, number: 42}"
321+
|| event_value.value_to_string() == "{number: 42, key: test}"
322+
);
323+
}
324+
266325
#[test]
267326
fn test_matches() {
268327
let mut modifier = Modifier::default();

0 commit comments

Comments
 (0)