summaryrefslogtreecommitdiffstats
path: root/src/stanza/mod.rs
blob: ad9e228adff99c2e844fb80653715a5bb7cdff7e (plain) (blame)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
// use quick_xml::events::BytesDecl;

pub mod bind;
pub mod iq;
pub mod sasl;
pub mod stream;

// const DECLARATION: BytesDecl<'_> = BytesDecl::new("1.0", None, None);
use async_recursion::async_recursion;
use quick_xml::events::Event;
use quick_xml::{Reader, Writer};
use tokio::io::{AsyncBufRead, AsyncWrite};

use crate::JabberError;

#[derive(Clone, Debug)]
pub struct Element<'e> {
    pub event: Event<'e>,
    pub children: Option<Vec<Element<'e>>>,
}

impl<'e: 'async_recursion, 'async_recursion> Element<'e> {
    pub fn write<'life0, W: AsyncWrite + Unpin + Send>(
        &'async_recursion self,
        writer: &'life0 mut Writer<W>,
    ) -> ::core::pin::Pin<
        Box<
            dyn ::core::future::Future<Output = Result<(), JabberError>>
                + 'async_recursion
                + ::core::marker::Send,
        >,
    >
    where
        W: 'async_recursion,
        'life0: 'async_recursion,
    {
        Box::pin(async move {
            match &self.event {
                Event::Start(e) => {
                    writer.write_event_async(Event::Start(e.clone())).await?;
                    if let Some(children) = &self.children {
                        for e in children {
                            e.write(writer).await?;
                        }
                    }
                    writer.write_event_async(Event::End(e.to_end())).await?;
                    return Ok(());
                }
                e => Ok(writer.write_event_async(e).await?),
            }
        })
    }
}

impl<'e> Element<'e> {
    pub async fn write_start<W: AsyncWrite + Unpin + Send>(
        &self,
        writer: &mut Writer<W>,
    ) -> Result<(), JabberError> {
        match self.event.as_ref() {
            Event::Start(e) => Ok(writer.write_event_async(Event::Start(e.clone())).await?),
            e => Err(ElementError::NotAStart(e.clone().into_owned()).into()),
        }
    }

    pub async fn write_end<W: AsyncWrite + Unpin + Send>(
        &self,
        writer: &mut Writer<W>,
    ) -> Result<(), JabberError> {
        match self.event.as_ref() {
            Event::Start(e) => Ok(writer
                .write_event_async(Event::End(e.clone().to_end()))
                .await?),
            e => Err(ElementError::NotAStart(e.clone().into_owned()).into()),
        }
    }

    #[async_recursion]
    pub async fn read<R: AsyncBufRead + Unpin + Send>(
        reader: &mut Reader<R>,
    ) -> Result<Self, JabberError> {
        let element = Self::read_recursive(reader)
            .await?
            .ok_or(JabberError::UnexpectedEnd);
        element
    }

    #[async_recursion]
    async fn read_recursive<R: AsyncBufRead + Unpin + Send>(
        reader: &mut Reader<R>,
    ) -> Result<Option<Self>, JabberError> {
        let mut buf = Vec::new();
        let event = reader.read_event_into_async(&mut buf).await?;
        match event {
            Event::Start(e) => {
                let mut children_vec = Vec::new();
                while let Some(sub_element) = Element::read_recursive(reader).await? {
                    children_vec.push(sub_element)
                }
                let mut children = None;
                if !children_vec.is_empty() {
                    children = Some(children_vec)
                }
                Ok(Some(Self {
                    event: Event::Start(e.into_owned()),
                    children,
                }))
            }
            Event::End(_) => Ok(None),
            e => Ok(Some(Self {
                event: e.into_owned(),
                children: None,
            })),
        }
    }

    #[async_recursion]
    pub async fn read_start<R: AsyncBufRead + Unpin + Send>(
        reader: &mut Reader<R>,
    ) -> Result<Self, JabberError> {
        let mut buf = Vec::new();
        let event = reader.read_event_into_async(&mut buf).await?;
        match event {
            Event::Start(e) => {
                return Ok(Self {
                    event: Event::Start(e.into_owned()),
                    children: None,
                })
            }
            e => Err(ElementError::NotAStart(e.into_owned()).into()),
        }
    }

    /// if there is only one child in the vec of children, will return that element
    pub fn child<'p>(&'p self) -> Result<&'p Element<'e>, ElementError<'static>> {
        if let Some(children) = &self.children {
            if children.len() == 1 {
                return Ok(&children[0]);
            } else {
                return Err(ElementError::MultipleChildren);
            }
        }
        Err(ElementError::NoChildren)
    }

    /// returns reference to children
    pub fn children<'p>(&'p self) -> Result<&'p Vec<Element<'e>>, ElementError<'e>> {
        if let Some(children) = &self.children {
            return Ok(children);
        }
        Err(ElementError::NoChildren)
    }
}

pub trait IntoElement<'e> {
    fn event(&self) -> Event<'e>;
    fn children(&self) -> Option<Vec<Element<'e>>>;
}

impl<'e, T: IntoElement<'e>> From<T> for Element<'e> {
    fn from(value: T) -> Self {
        Element {
            event: value.event(),
            children: value.children(),
        }
    }
}

#[derive(Debug)]
pub enum ElementError<'e> {
    NotAStart(Event<'e>),
    NoChildren,
    MultipleChildren,
}