tinyosc/
message.rs

1// Copyright (c) 2015 William Light <wrl@illest.net>
2// 
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9// 
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12// 
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21use std::io::Write;
22use std::io;
23
24use Argument;
25
26pub struct Message<'a> {
27    pub path: &'a str,
28    pub arguments: Vec<Argument<'a>>
29}
30
31impl<'a> Message<'a> {
32    pub fn deserialize(buf: &'a [u8]) -> Result<Message<'a>, ()> {
33        let mut msg = Message {
34            path: "",
35            arguments: vec![]
36        };
37
38        let mut slice = buf;
39
40        match Argument::deserialize('s', &mut slice) {
41            Ok(Argument::s(st)) => msg.path = st,
42            _ => return Err(())
43        }
44
45        let typetags = match Argument::deserialize('s', &mut slice) {
46            Ok(Argument::s(st)) => st,
47            _ => return Err(())
48        };
49
50        if typetags.as_bytes()[0] != (',' as u8) {
51            return Err(())
52        }
53
54        for typetag in typetags[1 ..].chars() {
55            let arg = Argument::deserialize(typetag, &mut slice);
56
57            match arg {
58                Ok(arg) => msg.arguments.push(arg),
59                Err(_) => return Err(())
60            }
61        }
62
63        Ok(msg)
64    }
65
66    pub fn serialize_into(&self, into: &mut Write) -> io::Result<()> {
67        try!(Argument::s(self.path).serialize(into));
68
69        let mut typetags = String::from(",");
70
71        for arg in &self.arguments {
72            typetags.push(arg.typetag());
73        }
74
75        try!(Argument::s(&*typetags).serialize(into));
76
77        for arg in &self.arguments {
78            try!(arg.serialize(into));
79        }
80
81        Ok(())
82    }
83
84    pub fn serialize(&self) -> io::Result<Vec<u8>> {
85        let mut ret: Vec<u8> = vec![];
86        try!(self.serialize_into(&mut ret));
87        Ok(ret)
88    }
89}