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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use crc_any::CRCu32;

use super::Segment;
use crate::bits::BitWriter;
use crate::result::CompilerResult;
use crate::version;

/// 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:12)
        buffer.append(now());
        // Versioning (major, minor, patch) (12:15)
        buffer.append(version::MAJOR);
        buffer.append(version::MINOR);
        buffer.append(version::PATCH);

        // NAborts (15:16)
        buffer.append(n_aborts);

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

        // Test-Body-Offset (76:80)
        buffer.append(test_body_offset);
        // Extra-Payload-Offset (80:84)
        buffer.append(extra_payload_offset);
        // Footer-Offset (84:88)
        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.
    /// Returns the crc hash of this TBF
    fn append_footer_to_buffer(&self, buffer: &mut BitWriter) -> u32 {
        let buffer_clone = buffer.clone();
        let test_bytes = buffer_clone.as_bytes();

        // Section Prefix
        buffer.append(0xF3u8);

        // Hash
        let mut crc32 = CRCu32::crc32q();
        crc32.digest(test_bytes);
        buffer.append(crc32.get_crc());
        // NL - Newline to assist editors
        buffer.append(b'\n');

        // Return the crc
        crc32.get_crc()
    }

    /// Appends the entire contents of this Test to a BitWriter
    pub fn append_to_buffer(&self, buffer: &mut BitWriter) -> u32 {
        // 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
        let crc_hash = self.append_footer_to_buffer(buffer);

        // Return the crc hash
        crc_hash
    }

    /// Format Test for TAF output
    pub fn disassemble(&self) -> CompilerResult<String> {
        let mut res = CompilerResult::new("Test disassembly");
        let mut lines = String::new();
        for (abort_idx, abort) in self.aborts.iter().enumerate() {
            if abort.not_empty() {
                check!(
                    res,
                    abort.append_assembly_to_string(&mut lines, abort_idx as u32 + 1)
                );
            }
        }
        check!(res, self.body.append_assembly_to_string(&mut lines));
        res.with_value(lines)
    }

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

    /// 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 name of the abort
    pub name: Option<String>,
    /// 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 {
            name: None,
            segments: Vec::new(),
        }
    }

    pub fn not_empty(&self) -> bool {
        !self.segments.is_empty()
    }

    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);
    }

    /// Format Abort contents for TAF output
    pub fn append_assembly_to_string(
        &self,
        lines: &mut String,
        abort_idx: u32,
    ) -> CompilerResult<()> {
        let mut res = CompilerResult::status_only("Abort disassembly");
        lines.push_str(format!("abort #{}:\n", abort_idx).as_str());
        for segment in &self.segments {
            check!(res, segment.append_assembly_to_string(lines));
        }
        res
    }

    /// 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(0xF1u8);
        // 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);
        }
    }

    /// Format TestBody for TAF output
    pub fn append_assembly_to_string(&self, lines: &mut String) -> CompilerResult<()> {
        let mut res = CompilerResult::status_only("Test body disassembly");
        lines.push_str("test:\n");

        for segment in &self.segments {
            check!(res, segment.append_assembly_to_string(lines));
        }
        res
    }

    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(ExtraPayload::len(), 24);
    }

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

fn now() -> u64 {
    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() as u64
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn crc_test() {
        let mut crc32 = CRCu32::crc32q();
        crc32.digest(b"123456789");
        assert_eq!("0x3010BF7F", crc32.to_string());

        let mut crc32 = CRCu32::crc32q();
        crc32.digest(b"987654321");
        assert_eq!("0x3172BE3A", crc32.to_string());

        let mut crc32 = CRCu32::crc32q();
        crc32.digest(b"Rockets are cool");
        assert_eq!("0xE98FB2A3", crc32.to_string());
    }

    #[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
        );
    }

    #[test]
    fn test_body_new_segments() {
        use crate::test_binary::instructions::{DeviceAddress, SensorAction, SensorInstr};

        let mut test_test_body = TestBody::new(); // 4 bytes long
        let mut test_segment = Segment::try_new(0).to_option().unwrap();
        let sensor_instruction = SensorInstr::try_new(
            SensorAction::is_now_in,
            1,
            DeviceAddress {
                value: 5,
                virtuality: 0,
            },
            0,
            0,
        )
        .to_option()
        .unwrap();

        test_segment.sensor_instructions.push(sensor_instruction);
        let seg_length = test_segment.len() as u32; // 13 bytes long
        test_test_body.segments.push(test_segment);

        // Verify that the length of a TestBody is equal to sum of segments
        let mut writer = BitWriter::new();
        test_test_body.append_to_buffer(&mut writer);
        assert_eq!((TestBody::HEADER_LEN + seg_length) * 8, writer.len() as u32);
    }
}