Mike Gerwitz

Activist for User Freedom

aboutsummaryrefslogtreecommitdiffstats
blob: 05d89f94060e56674c627effd3c5805567cdc096 (plain)
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// xmle object file writer
//
//  Copyright (C) 2014-2019 Ryan Specialty Group, LLC.
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

use crate::ir::asg::Object;
use crate::sym::Symbol;
use quick_xml::Error as XmlError;
use std::io::{Error as IoError, Write};
use std::result;
use std::str::Utf8Error;

type ObjectRef<'a, 'i> = &'a Object<'i>;
pub type Result<T = ()> = result::Result<T, WriterError>;
pub type ObjectVec<'a, 'i> = Vec<ObjectRef<'a, 'i>>;

/// A wrapper around a `Write` object
///
/// This is used to take the [`Sections`] and write out the xmle files.
pub trait Writer<W: Write> {
    fn write(
        &mut self,
        sections: &Sections,
        name: Symbol,
        relroot: &str,
    ) -> Result<()>
    where
        Self: Sized;
}

/// A Section that needs to be written to the buffer
///
/// Most sections will only need a `body`, but some innlude `head` and `tail`
///   information. Rather than dealing with those differently, each `Section`
///   will have a `head` and `tail` that are empty by default.
#[derive(Clone, Default)]
pub struct Section<'a, 'i> {
    head: ObjectVec<'a, 'i>,
    body: ObjectVec<'a, 'i>,
    tail: ObjectVec<'a, 'i>,
}

impl<'a, 'i> Section<'a, 'i> {
    /// Constructor for Sections
    ///
    /// ```
    /// use tamer::obj::xmle::writer::Section;
    ///
    /// let section = Section::new();
    /// ```
    pub fn new() -> Self {
        Self {
            head: Vec::new(),
            body: Vec::new(),
            tail: Vec::new(),
        }
    }

    /// The length of the `Section`
    pub fn len(&self) -> usize {
        self.head.len() + self.body.len() + self.tail.len()
    }

    /// Check if the `Section` is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Push an `Object` into a `Section`'s head
    pub fn push_head(&mut self, obj: ObjectRef<'a, 'i>) {
        self.head.push(&obj)
    }

    /// Push an `Object` into a `Section`'s body
    pub fn push_body(&mut self, obj: ObjectRef<'a, 'i>) {
        self.body.push(&obj)
    }

    /// Push an `Object` into a `Section`'s tail
    pub fn push_tail(&mut self, obj: ObjectRef<'a, 'i>) {
        self.tail.push(&obj)
    }

    /// Merge the parts of a `Section` into one [`SectionIterator`]
    ///
    /// The `Section` internals need to be iterated as a group so we needed to
    ///   create a custom iterator, [`SectionIterator`] to do this for us. This
    ///   method allows us to access the iterator.
    ///
    /// ```
    /// use tamer::obj::xmle::writer::Section;
    /// use tamer::ir::asg::Object;
    ///
    /// let mut section = Section::new();
    /// let obj = Object::Empty;
    /// let expect = vec![&obj, &obj, &obj];
    ///
    /// section.push_head(&obj);
    /// section.push_body(&obj);
    /// section.push_tail(&obj);
    /// let section_iter = section.iter();
    ///
    /// for object in section_iter {
    ///     assert_eq!(&obj, object);
    /// }
    /// ```
    pub fn iter(&self) -> SectionIterator {
        SectionIterator {
            inner: Box::new(
                self.head
                    .iter()
                    .chain(self.body.iter())
                    .chain(self.tail.iter())
                    .copied(),
            ),
        }
    }
}

/// Wrapper for an Iterator
///
/// This allows us to iterate over all parts of a [`Section`].
pub struct SectionIterator<'a, 'i> {
    inner: Box<dyn Iterator<Item = &'a Object<'i>> + 'a>,
}

impl<'a, 'i> Iterator for SectionIterator<'a, 'i> {
    type Item = &'a Object<'i>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

/// Sections that need to be written to a buffer
///
/// All the properties are public [`Section`] objects and will be accessed
///   directly by the [`Writer`].
#[derive(Default)]
pub struct Sections<'a, 'i> {
    pub map: Section<'a, 'i>,
    pub retmap: Section<'a, 'i>,
    pub meta: Section<'a, 'i>,
    pub worksheet: Section<'a, 'i>,
    pub params: Section<'a, 'i>,
    pub types: Section<'a, 'i>,
    pub funcs: Section<'a, 'i>,
    pub rater: Section<'a, 'i>,
}

impl<'a, 'i> Sections<'a, 'i> {
    /// Constructor for Sections
    ///
    /// ```
    /// use tamer::obj::xmle::writer::Sections;
    ///
    /// let sections = Sections::new();
    /// ```
    pub fn new() -> Self {
        Self {
            map: Section::new(),
            retmap: Section::new(),
            meta: Section::new(),
            worksheet: Section::new(),
            params: Section::new(),
            types: Section::new(),
            funcs: Section::new(),
            rater: Section::new(),
        }
    }
}

/// Error implementations for the writer
#[derive(Debug)]
pub enum WriterError {
    Io(IoError),
    Utf8(Utf8Error),
    XmlError(XmlError),
    ExpectedFragment(String),
}

impl From<IoError> for WriterError {
    fn from(err: IoError) -> Self {
        WriterError::Io(err)
    }
}

impl From<Utf8Error> for WriterError {
    fn from(err: Utf8Error) -> Self {
        WriterError::Utf8(err)
    }
}

impl From<XmlError> for WriterError {
    fn from(err: XmlError) -> Self {
        WriterError::XmlError(err)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn section_empty() {
        let section = Section::new();

        assert!(section.head.is_empty());
        assert!(section.body.is_empty());
        assert!(section.tail.is_empty());
    }

    #[test]
    fn section_head() {
        let mut section = Section::new();
        let obj = Object::Empty;

        assert!(section.head.is_empty());

        section.push_head(&obj);

        assert_eq!(Some(&&obj), section.head.get(0));
    }

    #[test]
    fn section_body() {
        let mut section = Section::new();
        let obj = Object::Empty;

        assert!(section.body.is_empty());

        section.push_body(&obj);

        let body = section.body;
        assert_eq!(Some(&&obj), body.get(0));
    }

    #[test]
    fn section_tail() {
        let mut section = Section::new();
        let obj = Object::Empty;

        assert!(section.tail.is_empty());

        section.push_tail(&obj);

        assert_eq!(Some(&&obj), section.tail.get(0));
    }

    #[test]
    fn section_len() {
        let mut section = Section::new();
        let obj = Object::Empty;

        assert_eq!(0, section.len());
        section.push_head(&obj);
        assert_eq!(1, section.len());
        section.push_body(&obj);
        assert_eq!(2, section.len());
        section.push_tail(&obj);
        assert_eq!(3, section.len());
    }

    #[test]
    fn section_is_empty_head() {
        let mut section = Section::new();
        let obj = Object::Empty;

        assert!(section.is_empty());
        section.push_head(&obj);
        assert!(!section.is_empty());
    }

    #[test]
    fn section_is_empty_body() {
        let mut section = Section::new();
        let obj = Object::Empty;

        assert!(section.is_empty());
        section.push_body(&obj);
        assert!(!section.is_empty());
    }

    #[test]
    fn section_is_empty_tail() {
        let mut section = Section::new();
        let obj = Object::Empty;

        assert!(section.is_empty());
        section.push_tail(&obj);
        assert!(!section.is_empty());
    }

    #[test]
    fn section_iterator() {
        let mut section = Section::new();
        let obj = Object::Empty;
        let expect = vec![&obj, &obj, &obj];

        section.push_head(&obj);
        section.push_body(&obj);
        section.push_tail(&obj);

        let collection: Vec<_> = section.iter().collect();

        assert_eq!(expect, collection);
    }
}