1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// ---------------- [ File: random-constructible-derive/src/clamp_code.rs ]
crate::ix!();
/// NEW HELPER FUNCTION
/// We generate a small piece of code to clamp `val` if the field is a known
/// numeric (primitive) type and we have `min` or `max` specified.
///
/// This returns a `TokenStream2` snippet you can inject directly after
/// computing `val`.
pub fn clamp_code(ty: &Type, maybe_min: Option<f64>, maybe_max: Option<f64>) -> TokenStream2 {
//trace!("clamp_code(...) invoked for type: {:?}", ty);
// If the type is not primitive, or there's no min/max, emit empty code
if !is_primitive_type(ty) || (maybe_min.is_none() && maybe_max.is_none()) {
return quote!{};
}
// If we do have min and/or max, we build the needed if-checks
let min_check = if let Some(minv) = maybe_min {
quote! {
if v < #minv as #ty {
v = #minv as #ty;
}
}
} else {
quote!{}
};
let max_check = if let Some(maxv) = maybe_max {
quote! {
if v > #maxv as #ty {
v = #maxv as #ty;
}
}
} else {
quote!{}
};
quote! {
{
#min_check
#max_check
}
}
}