dysql_tpl/simple/
simple_section.rs

1use std::ops::Range;
2
3use crate::{traits::ContentSequence, Content, Next, simple::simple_block::SimpleTag, SimpleInnerError};
4
5use super::{simple_block::SimpleBlock, SimpleValue, SimpleError};
6
7/// SimpleSection 是用于参数值绑定的 section
8#[derive(Clone, Copy)]
9pub struct SimpleSection<'section, Contents> 
10where 
11    Contents: ContentSequence,
12{
13    blocks: &'section [SimpleBlock],
14    contents: Contents,
15}
16
17impl<'section> SimpleSection<'section, ()> 
18{
19    #[inline]
20    pub(crate) fn new(blocks: &'section [SimpleBlock]) -> Self
21    {
22
23        let rst = Self {
24            blocks,
25            contents: (),
26        };
27
28        rst
29    }
30}
31
32impl<'section, C> SimpleSection<'section, C> 
33where
34    C: ContentSequence,
35{
36    #[inline]
37    fn slice(self, range: Range<usize>) -> Self {
38        let rst = Self {
39            blocks: &self.blocks[range],
40            contents: self.contents,
41        };
42
43        rst
44    }
45
46    /// 传入实现 Content 的 dto
47    #[inline]
48    pub fn with<X>(self, content: &X) -> SimpleSection<'section, Next<'section, C, &X>>
49    where
50        X: Content + ?Sized,
51    {
52        let rst = SimpleSection {
53            blocks: self.blocks,
54            contents: self.contents.combine(content),
55        };
56
57        rst
58    }
59
60    pub fn apply(&self) -> Result<SimpleValue, SimpleError>
61    {
62        let mut index = 0;
63        let mut rst = Err(SimpleInnerError("apply dto error: not found target field".to_owned()).into());
64        while let Some(block) = self.blocks.get(index) { 
65            index += 1;
66
67            match block.tag {
68                SimpleTag::Unescaped => {
69                    rst = self.contents.apply_field_unescaped(block.hash, &block.name);
70                },
71                SimpleTag::Section => {
72                    rst = self.contents.apply_field_section(
73                        block.hash,
74                        &block.name,
75                        self.slice(index..index + block.children as usize), 
76                    );
77                    index += block.children as usize;
78                },
79            }
80        }
81
82        rst
83    }
84}