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

enhancement(remap): Add join function #6313

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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/remap-functions/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ default = [
"ip_to_ipv6",
"ipv6_to_ipv4",
"is_nullish",
"join",
"length",
"log",
"match",
Expand Down Expand Up @@ -128,6 +129,7 @@ ip_subnet = ["lazy_static", "regex"]
ip_to_ipv6 = []
ipv6_to_ipv4 = []
is_nullish = []
join = []
length = []
log = ["tracing"]
match = ["regex"]
Expand Down
156 changes: 156 additions & 0 deletions lib/remap-functions/src/join.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
use remap::prelude::*;
use std::borrow::Cow;

#[derive(Clone, Copy, Debug)]
pub struct Join;

impl Function for Join {
fn identifier(&self) -> &'static str {
"join"
}

fn parameters(&self) -> &'static [Parameter] {
&[
Parameter {
keyword: "value",
accepts: |v| matches!(v, Value::Array(_)),
required: true,
},
Parameter {
keyword: "separator",
accepts: |v| matches!(v, Value::Bytes(_)),
required: false,
},
]
}

fn compile(&self, mut arguments: ArgumentList) -> Result<Box<dyn Expression>> {
let value = arguments.required("value")?.boxed();
let separator = arguments.optional("separator").map(Expr::boxed);

Ok(Box::new(JoinFn { value, separator }))
}
}

#[derive(Clone, Debug)]
struct JoinFn {
value: Box<dyn Expression>,
separator: Option<Box<dyn Expression>>,
}

impl Expression for JoinFn {
fn execute(&self, state: &mut state::Program, object: &mut dyn Object) -> Result<Value> {
let array = self.value.execute(state, object)?.try_array()?;

let string_vec = array
.iter()
.map(|s| s.try_bytes_utf8_lossy().map_err(Into::into))
.collect::<Result<Vec<Cow<'_, str>>>>()
.map_err(|_| "all array items must be strings")?;

let separator: String = self
.separator
.as_ref()
.map(|s| {
s.execute(state, object)
.and_then(|v| Value::try_bytes(v).map_err(Into::into))
lucperkins marked this conversation as resolved.
Show resolved Hide resolved
})
.transpose()?
.map(|s| String::from_utf8_lossy(&s).to_string())
.unwrap_or_else(|| "".into());
lucperkins marked this conversation as resolved.
Show resolved Hide resolved

let joined = string_vec.join(&separator);

Ok(Value::from(joined))
}

fn type_def(&self, state: &state::Compiler) -> TypeDef {
use value::Kind;

self.value
.type_def(state)
// Always fallible because the `value` array could contain non-strings
.into_fallible(true)
lucperkins marked this conversation as resolved.
Show resolved Hide resolved
.with_constraint(Kind::Bytes)
}
}

#[cfg(test)]
mod test {
use super::*;
use value::Kind;

test_type_def![
value_string_array_fallible {
expr: |_| JoinFn {
value: array!["one", "two", "three"].boxed(),
separator: Some(lit!(", ").boxed()),
},
def: TypeDef {
fallible: true,
kind: Kind::Bytes,
..Default::default()
},
}

value_wrong_type_fallible {
expr: |_| JoinFn {
value: lit!(427).boxed(),
separator: None,
},
def: TypeDef {
fallible: true,
kind: Kind::Bytes,
..Default::default()
},
}

separator_wrong_type_fallible {
expr: |_| JoinFn {
value: array!["one", "two", "three"].boxed(),
separator: Some(lit!(427).boxed()),
},
def: TypeDef {
fallible: true,
kind: Kind::Bytes,
..Default::default()
},
}

both_types_wrong_fallible {
expr: |_| JoinFn {
value: lit!(true).boxed(),
separator: Some(lit!(427).boxed()),
},
def: TypeDef {
fallible: true,
kind: Kind::Bytes,
..Default::default()
},
}
];

test_function![
join => Join;

with_comma_separator {
args: func_args![value: array!["one", "two", "three"], separator: lit!(", ")],
want: Ok(value!("one, two, three")),
}

with_space_separator {
args: func_args![value: array!["one", "two", "three"], separator: lit!(" ")],
want: Ok(value!("one two three")),
}

without_separator {
args: func_args![value: array!["one", "two", "three"]],
want: Ok(value!("onetwothree")),
}

non_string_array_item_throws_error {
args: func_args![value: array!["one", "two", 3]],
want: Err("function call error: all array items must be strings"),
}
];
}
6 changes: 6 additions & 0 deletions lib/remap-functions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ mod ip_to_ipv6;
mod ipv6_to_ipv4;
#[cfg(feature = "is_nullish")]
mod is_nullish;
#[cfg(feature = "join")]
mod join;
#[cfg(feature = "length")]
mod length;
#[cfg(feature = "log")]
Expand Down Expand Up @@ -185,6 +187,8 @@ pub use ip_to_ipv6::IpToIpv6;
pub use ipv6_to_ipv4::Ipv6ToIpV4;
#[cfg(feature = "is_nullish")]
pub use is_nullish::IsNullish;
#[cfg(feature = "join")]
pub use join::Join;
#[cfg(feature = "length")]
pub use length::Length;
#[cfg(feature = "log")]
Expand Down Expand Up @@ -320,6 +324,8 @@ pub fn all() -> Vec<Box<dyn remap::Function>> {
Box::new(Ipv6ToIpV4),
#[cfg(feature = "is_nullish")]
Box::new(IsNullish),
#[cfg(feature = "join")]
Box::new(Join),
#[cfg(feature = "length")]
Box::new(Length),
#[cfg(feature = "log")]
Expand Down