macro_rules! define {
() => { ... };
($try_transform:ident) => { ... };
($try_transform:ident, $try_inverse:ident) => { ... };
($param_var:ident: $ParamType:ty) => { ... };
($param_var:ident: $ParamType:ty, $try_transform:ident) => { ... };
($param_var:ident: $ParamType:ty, $try_transform:ident, $try_inverse:ident) => { ... };
}Expand description
Define the boilerplate for the Lens.
This macro is the easiest way to setup your Lens file - provide this with a transform function and you should have a valid Lens.
This macro handles multiple patterns, each handled pattern will generate a different set of functions.
- next() and alloc() will always be defined.
- transform() will be defined if given a single transform function.
- transform() and inverse() will be defined if given the identities of two transform/inverse functions.
- set_param() will be defined if given the name of a variable to hold a param, and its type.
ยงExamples
The following example contains a complete Lens that transforms inputs by incrementing input.age by 1.
lens_sdk::define!(try_transform);
#[derive(Serialize, Deserialize)]
pub struct Value {
pub name: String,
pub age: i64,
}
fn try_transform(
iter: &mut dyn Iterator<Item = lens_sdk::Result<Option<Value>>>,
) -> Result<StreamOption<Value>, Box<dyn Error>> {
for item in iter {
let input = match item? {
Some(v) => v,
None => return Ok(StreamOption::None),
};
let result = Value {
name: input.name,
age: input.age + 1,
};
return Ok(StreamOption::Some(result))
}
Ok(StreamOption::EndOfStream)
}The next example contains a complete Lens that transforms, and inverses, the incrementing of input.age by the amount provided by the configured paramter.
lens_sdk::define!(PARAMETERS: Parameters, try_transform, try_inverse);
#[derive(Deserialize, Clone)]
pub struct Parameters {
pub magnitude: i64,
}
static PARAMETERS: RwLock<Option<Parameters>> = RwLock::new(None);
#[derive(Serialize, Deserialize)]
pub struct Value {
pub name: String,
pub age: i64,
}
fn try_transform(
iter: &mut dyn Iterator<Item = lens_sdk::Result<Option<Value>>>,
) -> Result<StreamOption<Value>, Box<dyn Error>> {
let params = PARAMETERS.read()?
.clone()
.ok_or(LensError::ParametersNotSetError)?;
for item in iter {
let input = match item? {
Some(v) => v,
None => return Ok(StreamOption::None),
};
let result = Value {
name: input.name,
age: input.age + params.magnitude,
};
return Ok(StreamOption::Some(result))
}
Ok(StreamOption::EndOfStream)
}
fn try_inverse(
iter: &mut dyn Iterator<Item = lens_sdk::Result<Option<Value>>>,
) -> Result<StreamOption<Value>, Box<dyn Error>> {
let params = PARAMETERS.read()?
.clone()
.ok_or(LensError::ParametersNotSetError)?;
for item in iter {
let input = match item? {
Some(v) => v,
None => return Ok(StreamOption::None),
};
let result = Value {
name: input.name,
age: input.age - params.magnitude,
};
return Ok(StreamOption::Some(result))
}
Ok(StreamOption::EndOfStream)
}