pipebase/common/
field.rs

1/// Field visitor visits object's field
2pub struct FieldVisitor<F> {
3    value: Option<F>,
4}
5
6impl<F> FieldVisitor<F> {
7    pub fn new() -> Self {
8        FieldVisitor { value: None }
9    }
10
11    pub fn visit(&mut self, value: F) {
12        self.value = Some(value);
13    }
14
15    pub fn get_value(self) -> Option<F> {
16        self.value
17    }
18}
19
20impl<F> Default for FieldVisitor<F> {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26/// Accept field visitor
27pub trait FieldAccept<F> {
28    fn accept(self, visitor: &mut FieldVisitor<F>);
29}
30
31#[cfg(test)]
32mod tests {
33    use crate::prelude::*;
34
35    #[derive(FieldAccept)]
36    struct Records {
37        #[visit]
38        records: [i32; 3],
39    }
40
41    #[test]
42    fn test_field_visit() {
43        let record = [1, 2, 3];
44        let records = Records { records: record };
45        let mut visitor = FieldVisitor::<[i32; 3]>::new();
46        records.accept(&mut visitor);
47        let visitor_record = visitor.get_value().unwrap().to_owned();
48        assert_eq!(record, visitor_record)
49    }
50}