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
use twiml::*;
use xml::{
    writer::{EventWriter, XmlEvent}, EmitterConfig,
};

#[derive(Debug)]
pub struct Play<'a> {
    count: usize,
    body: &'a str,
}

impl<'a> Play<'a> {
    pub fn new(body: &'a str) -> Self {
        Play { body, count: 1 }
    }
    pub fn count(mut self, count: usize) -> Play<'a> {
        self.count = count;
        self
    }
}

impl<'a> Twiml for Play<'a> {
    fn write<W: Write>(&self, w: &mut EventWriter<W>) -> TwilioResult<()> {
        w.write(XmlEvent::start_element("Play").attr("loop", &self.count.to_string()))?;
        w.write(self.body)?;
        w.write(XmlEvent::end_element())?;
        Ok(())
    }
    fn build(&self) -> TwilioResult<String> {
        // Create a buffer and serialize our nodes into it
        let mut writer = Vec::with_capacity(30);
        {
            let mut w = EmitterConfig::new()
                .write_document_declaration(false)
                .create_writer(&mut writer);

            self.write(&mut w)?;
        }
        Ok(String::from_utf8(writer)?)
    }
}

impl<'a, T> From<T> for Play<'a>
where
    T: Into<&'a str>,
{
    fn from(s: T) -> Self {
        Play::new(s.into())
    }
}