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
use crate::bits::BitWriter;
use super::{ Segment };

/// Represents a Test and the logic required to create a Test Binary File from it.
pub struct Test {
    /// The Abort Sequences in the test.
    /// The index of an Abort in this Vec is one less than it's "abort_idx",
    /// because the hard abort has index 0, but is implicitly defined.
    pub aborts: [Abort; 15],
    /// The main body of the test that is executed when the test is run
    pub body: TestBody
}

impl Test {
    /// Creates a new empty test with no aborts, and no instructions
    pub fn new() -> Self {
        let aborts = [
            Abort::new(), Abort::new(), Abort::new(), Abort::new(),
            Abort::new(), Abort::new(), Abort::new(), Abort::new(),
            Abort::new(), Abort::new(), Abort::new(), Abort::new(),
            Abort::new(), Abort::new(), Abort::new()
        ];
        Test {
            aborts,
            body: TestBody::new()
        }
    }

    /// Appends the Test Header to a buffer
    fn append_header_to_buffer(&self, buffer: &mut BitWriter) {
        // Compute the offsets for all file sections
        let mut offset = Test::HEADER_LEN;
        let mut n_aborts: u8 = 0;

        let mut abort_offsets: [u32; 15] = [0u32; 15];

        for i in 0..15 {
            abort_offsets[i] = offset;
            offset += self.aborts[i].len();

            if self.aborts[i].not_empty() {
                n_aborts += 1;
            }
        }

        let test_body_offset = offset;
        offset += self.body.len();

        let extra_payload_offset = offset;
        offset += ExtraPayload::len();

        let footer_offset = offset;
        
        // Create the Header

        // Prefix (0:4)
        buffer.append(b'.');
        buffer.append(b'T');
        buffer.append(b'B');
        buffer.append(b'F');

        // Timestamp (4:20)
        buffer.append(now());

        // Versioning (major, minor, patch) (20:23)
        buffer.append(0u8);
        buffer.append(0u8);
        buffer.append(0u8);

        // NAborts (23:24)
        buffer.append(n_aborts);

        // Abort Offsets (24:84)
        for abort_offset in abort_offsets.iter() {
            buffer.append(*abort_offset);
        }

        // Test-Body-Offset (84:88)
        buffer.append(test_body_offset);
        // Extra-Payload-Offset (88:92)
        buffer.append(extra_payload_offset);
        // Footer-Offset (92:96)
        buffer.append(footer_offset);
    }

    /// Appends the Test Footer to the buffer.
    /// In the future this will involve computing the hash value of the test so far.
    fn append_footer_to_buffer(&self, buffer: &mut BitWriter) {
        // Section Prefix
        buffer.append(0xF3u8);
        // Hash - TODO
        buffer.append(0u128);
        // NL - Newline to assist editors
        buffer.append(b'\n')
    }

    /// Appends the entire contents of this Test to a BitWriter
    pub fn append_to_buffer(&self, buffer: &mut BitWriter) {
        // The Test Header
        self.append_header_to_buffer(buffer);

        // The Abort Sections from 1 to N
        for i in 0..15 {
            // Compute the abort index from the array index
            // 0 is the hard-abort, user-defined aborts start at 1
            let abort_idx: u8 = (i + 1) as u8;
            // Append the abort
            self.aborts[i].append_to_buffer(abort_idx, buffer); 
        }

        // The Test Body Section
        self.body.append_to_buffer(buffer);

        // The Extra Payload Section
        ExtraPayload::append_to_buffer(buffer);

        // The Footer Section
        self.append_footer_to_buffer(buffer);
    }

    /// The length of the Test Binary File Header.
    const HEADER_LEN: u32 = 96;
    /// The length of the Test Binary File Footer.
    const FOOTER_LEN: u32 = 18;

    /// Computes the number of bytes this Test will take up after serialization.
    pub fn len(&self) -> u32 {
        let aborts_len: u32 = self.aborts.iter().map(|a| a.len()).sum();

        Test::HEADER_LEN + aborts_len + self.body.len() + ExtraPayload::len() + Test::FOOTER_LEN
    }
}

/// An Abort Sequence.
pub struct Abort {
    /// The Instruction Segments that make up the abort.
    pub segments: Vec<Segment>
}

impl Abort {
    /// Creates a new empty abort, with no Instruction Segments
    pub fn new() -> Self {
        Abort {
            segments: Vec::new()
        }
    }

    pub fn not_empty(&self) -> bool {
        self.segments.len() > 0
    }

    fn append_header_to_buffer(&self, abort_idx: u8, buffer: &mut BitWriter) {
        // Header Prefix
        buffer.append(0xF0u8);
        // Abort Index
        buffer.append(abort_idx);
        // Section Length
        buffer.append(self.len() as u16);
    }

    /// Appends the entire contents of this Abort to a BitWriter
    pub fn append_to_buffer(&self, abort_idx: u8, buffer: &mut BitWriter) {
        self.append_header_to_buffer(abort_idx, buffer);

        for instruction_segment in self.segments.iter() {
            instruction_segment.append_to_buffer(buffer);
        }
    }

    const HEADER_LEN: u32 = 4;

    /// Computes the number of bytes that this abort will take up
    /// after serialization
    pub fn len(&self) -> u32 {
        let segment_lengths: u32 = self.segments.iter().map(|s| s.len()).sum();
        Abort::HEADER_LEN + segment_lengths
    }
}

/// The main body of the Test
pub struct TestBody {
    /// The Instruction Segments that make up the test body
    pub segments: Vec<Segment>
}

impl TestBody {
    /// Creates a new empty test body, with no Instruction Segments
    pub fn new() -> Self {
        TestBody {
            segments: Vec::new()
        }
    }

    fn append_header_to_buffer(&self, buffer: &mut BitWriter) {
        // Header Prefix
        buffer.append(0xF0u8);
        // Section Length
        buffer.append_tail(self.len(), 24);

    }

    /// Appends the entire contents of this TestBody to a BitWriter
    pub fn append_to_buffer(&self, buffer: &mut BitWriter) {
        self.append_header_to_buffer(buffer);

        for instruction_segment in self.segments.iter() {
            instruction_segment.append_to_buffer(buffer);
        }
    }

    const HEADER_LEN: u32 = 4;

    /// Computes the number of bytes that the test body will take up
    /// after serialization
    pub fn len(&self) -> u32 {
        let segment_lengths: u32 = self.segments.iter().map(|s| s.len()).sum();
        TestBody::HEADER_LEN + segment_lengths
    }
}

struct ExtraPayload;

impl ExtraPayload {
    /// Appends the entire extra payload to a BitWriter
    pub fn append_to_buffer(buffer: &mut BitWriter) {
        // Header Prefix
        buffer.append(0xF2u8);
        // Section Length
        buffer.append_tail(0u32, 24);
    }

    /// The number of bytes that the payload will take up
    /// after serialization
    pub fn len() -> u32 {
        4
    }
}

fn now() -> u128 {
    use std::time::{ SystemTime, UNIX_EPOCH };

    let start = SystemTime::now();
    let since_the_epoch = start.duration_since(UNIX_EPOCH)
        .expect("Time went backwards");

    since_the_epoch.as_millis()
}

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

    #[test]
    fn empty_test_len() {
        let empty_test = Test::new();

        let mut header_buffer = BitWriter::new();
        empty_test.append_header_to_buffer(&mut header_buffer);
        assert_eq!(Test::HEADER_LEN * 8, header_buffer.len() as u32);

        let mut footer_buffer = BitWriter::new();
        empty_test.append_footer_to_buffer(&mut footer_buffer);
        assert_eq!(Test::FOOTER_LEN * 8, footer_buffer.len() as u32);

        let test_len = Test::HEADER_LEN + (15 * Abort::HEADER_LEN) + TestBody::HEADER_LEN + ExtraPayload::len() + Test::FOOTER_LEN;
        
        let mut empty_test_buffer = BitWriter::new();
        empty_test.append_to_buffer(&mut empty_test_buffer);

        assert_eq!(test_len, empty_test.len());
        assert_eq!(test_len * 8, empty_test_buffer.len() as u32);
    }
    
    #[test]
    fn empty_test_body_len() {
        let empty_test_body = TestBody::new();

        // Verify that the header takes up the amount of buffer space it says it should
        let mut header_buffer = BitWriter::new();
        empty_test_body.append_header_to_buffer(&mut header_buffer);
        assert_eq!(TestBody::HEADER_LEN * 8, header_buffer.len() as u32);

        // Verify that the Test and the buffer report being the length of the header
        let mut empty_test_body_buffer = BitWriter::new();
        empty_test_body.append_to_buffer(&mut empty_test_body_buffer);
        assert_eq!(TestBody::HEADER_LEN, empty_test_body.len());
        assert_eq!(TestBody::HEADER_LEN * 8, empty_test_body_buffer.len() as u32);
    }
}