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
use crate::sans_io::WriterAction;
use crate::Error;
use std::io::Read;
use std::io::Write;

#[derive(Debug)]
enum State {
    FileHeader,
    FileData { size: usize },
    Flush,
}

/// The archive writer.
#[derive(Debug)]
pub struct Writer<W> {
    /// The inner writer.
    writer: W,

    /// The current state
    state: State,

    /// The state machine
    state_machine: crate::sans_io::Writer,
}

impl<W> Writer<W> {
    /// Create an archive writer around a writer.
    pub fn new(writer: W) -> Writer<W> {
        Writer {
            writer,
            state: State::FileHeader,
            state_machine: crate::sans_io::Writer::new(),
        }
    }

    /// Get the inner writer.
    pub fn into_inner(self) -> W {
        self.writer
    }

    /// Get a mutable ref to the inner writer.
    pub fn get_mut(&mut self) -> &mut W {
        &mut self.writer
    }
}

impl<W> Writer<W>
where
    W: Write,
{
    /// Write the archive header.
    ///
    /// If the header has already been written, this is a NOP.
    pub fn write_header(&mut self) -> Result<(), Error> {
        loop {
            let action = self.state_machine.step_write_header()?;
            match action {
                WriterAction::Write => {
                    let data = self.state_machine.data();
                    let size = self.writer.write(data)?;
                    self.state_machine.consume(size);
                }
                WriterAction::Done(()) => {
                    loop {
                        let data = self.state_machine.data();
                        if data.is_empty() {
                            break;
                        }

                        let n = self.writer.write(data)?;
                        self.state_machine.consume(n);
                    }

                    self.state = State::FileHeader;
                    return Ok(());
                }
            }
        }
    }

    /// Write a file.
    ///
    /// An file is composed of a name (path), size, and data.
    /// This function may be retried.
    /// To retry, call this function with the same arguments.
    /// Note that if anything other than an I/O error occurs, the written bytes are likely corrupted.
    pub fn write_file<R>(
        &mut self,
        file_name: &str,
        file_size: u32,
        mut file_data: R,
    ) -> Result<(), Error>
    where
        R: Read,
    {
        loop {
            match &mut self.state {
                State::FileHeader => {
                    let action = self
                        .state_machine
                        .step_write_file_header(file_name, file_size)?;

                    match action {
                        WriterAction::Write => {
                            let data = self.state_machine.data();
                            let size = self.writer.write(data)?;
                            self.state_machine.consume(size);
                        }
                        WriterAction::Done(()) => {
                            self.state = State::FileData { size: 0 };
                        }
                    }
                }
                State::FileData { size } => {
                    if *size == 0 {
                        let space = loop {
                            let space = self.state_machine.space();
                            if space.is_empty() {
                                let data = self.state_machine.data();
                                let n = self.writer.write(data)?;
                                self.state_machine.consume(n);
                            } else {
                                break space;
                            }
                        };
                        let n = file_data.read(space)?;
                        if n == 0 {
                            self.state = State::Flush;
                            continue;
                        }
                        *size = n;
                    } else {
                        let action = self.state_machine.step_write_file_data(*size)?;
                        match action {
                            WriterAction::Write => {
                                let data = self.state_machine.data();
                                let n = self.writer.write(data)?;
                                self.state_machine.consume(n);
                            }
                            WriterAction::Done(written) => {
                                *size -= written;
                            }
                        }
                    }
                }
                State::Flush => {
                    loop {
                        let data = self.state_machine.data();
                        if data.is_empty() {
                            break;
                        }

                        let n = self.writer.write(data)?;
                        self.state_machine.consume(n);
                    }

                    self.state = State::FileHeader;
                    return Ok(());
                }
            }
        }
    }

    /// Finish writing.
    ///
    /// This is only a convenience function to call the inner [`Write`] object's [`Write::flush`] method.
    pub fn finish(&mut self) -> Result<(), Error> {
        match &mut self.state {
            State::FileHeader => {}
            _ => {
                return Err(Error::InvalidState);
            }
        }

        self.writer.flush()?;
        Ok(())
    }
}