rust-stdf 1.1.0

A library for parsing Standard Test Data Format (STDF) files of version V4 and V4-2007.
Documentation
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use crate::stdf_codec::*;
use crate::stdf_error::{StdfError, StdfErrorKind};
use rust_stdf_derive::{stdf_match_expr, stdf_records};
use smart_default::SmartDefault;

mod type_0_file_info;
mod type_10_test_synopsis;
mod type_15_test_info;
mod type_180_reserved;
mod type_1_lot_info;
mod type_20_generic_data;
mod type_2_wafer_info;
mod type_50_program_segment;
mod type_5_part_info;

pub use type_0_file_info::*;
pub use type_10_test_synopsis::*;
pub use type_15_test_info::*;
pub use type_180_reserved::*;
pub use type_1_lot_info::*;
pub use type_20_generic_data::*;
pub use type_2_wafer_info::*;
pub use type_50_program_segment::*;
pub use type_5_part_info::*;

#[derive(SmartDefault, Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecordHeader {
    pub len: u16,
    pub typ: u8,
    pub sub: u8,
}

// Record Types

/// This module contains constants
/// for STDF Record type check and
/// some help functions
///
/// ```
/// use rust_stdf::{StdfRecord, stdf_record_type::*};
///
/// // use constant for record initializing
/// let mut rec = StdfRecord::new(REC_MIR);
///
/// // for type check
/// let t = REC_MIR | REC_MRR | REC_PTR;
/// let is_t = rec.is_type(t);      // true
/// ```
pub mod stdf_record_type {
    use crate::stdf_error::{StdfError, StdfErrorKind};
    use rust_stdf_derive::{stdf_match_expr, stdf_records};

    // Generates the `REC_*` record-type code constants.
    stdf_records!(rec_codes);

    /// This function gets record (typ, sub)
    /// from record type constant.
    ///
    /// ```
    /// use rust_stdf::stdf_record_type::*;
    ///
    /// let ptr_typ_sub = get_typ_sub_from_code(REC_PTR).unwrap();
    /// assert_eq!((15, 10), ptr_typ_sub);
    /// ```
    #[inline(always)]
    pub fn get_typ_sub_from_code(code: u64) -> Result<(u8, u8), StdfError> {
        stdf_match_expr!(typ_sub_from_code)
    }

    /// This function gets record type constant
    /// from record (typ, sub).
    ///
    /// ```
    /// use rust_stdf::stdf_record_type::*;
    ///
    /// let type_code = get_code_from_typ_sub(15, 10);
    /// assert_eq!(REC_PTR, type_code);
    /// ```
    #[inline(always)]
    pub fn get_code_from_typ_sub(typ: u8, sub: u8) -> u64 {
        stdf_match_expr!(code_from_typ_sub)
    }

    /// This function gets record name string
    /// from record type constant.
    ///
    /// ```
    /// use rust_stdf::stdf_record_type::*;
    ///
    /// let rec_name = get_rec_name_from_code(REC_PTR);
    /// assert_eq!("PTR", rec_name);
    /// ```
    #[inline(always)]
    pub fn get_rec_name_from_code(rec_type: u64) -> &'static str {
        stdf_match_expr!(name_from_code)
    }

    /// This function gets the record type constant
    /// from record name string.
    ///
    /// ```
    /// use rust_stdf::stdf_record_type::*;
    ///
    /// let type_code = get_code_from_rec_name("PTR");
    /// assert_eq!(REC_PTR, type_code);
    /// ```
    ///
    #[inline(always)]
    pub fn get_code_from_rec_name(rec_name: &str) -> u64 {
        stdf_match_expr!(code_from_name)
    }
}

// Generates the `StdfRecord` and `StdfRecordView` enums.
stdf_records!(rec_enums);

/// Element yielded by [`RawDataIter`](crate::stdf_file::RawDataIter). It owns unprocessed STDF record data,
/// and can be converted to [`StdfRecord`], or borrowed as [`StdfRecordView`].
///
/// ```
/// use rust_stdf::{RawDataElement, ByteOrder, StdfRecord, RecordHeader, stdf_record_type::REC_FAR};
///
/// let rde = RawDataElement {
///     offset: 0,
///     header: RecordHeader {typ: 0, sub: 10, len: 2},
///     raw_data: vec![0u8; 0],
///     byte_order: ByteOrder::LittleEndian
/// };
/// let rec: StdfRecord = (&rde).into();    // not consume
/// let rec: StdfRecord = rde.into();       // consume
/// println!("{:?}", rec);
/// assert!(rec.is_type(REC_FAR));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawDataElement {
    /// file offset of `raw_data` in file,
    /// after header.len and before raw_data
    ///
    /// |-typ-|-sub-|--len--⬇️--raw..data--|
    ///
    /// note that the offset is relative to the
    /// file position that runs `get_rawdata_iter`,
    ///
    /// it can be treated as file position **only if**
    /// the iteration starts from beginning of the file.
    pub offset: u64,

    /// used for identifying StdfRecord types
    pub header: RecordHeader,

    /// field data of current STDF Record
    pub raw_data: Vec<u8>,
    pub byte_order: ByteOrder,
}

/// Element yielded by [`RawDataViewIter`](crate::stdf_file::RawDataViewIter). Unlike [`RawDataElement`],
/// it borrows the unprocessed record bytes from the iterator's reused buffer, so it's only valid
/// until the next call to [`RawDataViewIter::next`](crate::stdf_file::RawDataViewIter::next).
///
/// In return, it offers better performance and lower heap footprints.
///
/// It can be converted to [`StdfRecord`], borrowed as [`StdfRecordView`], or copied into an owned
/// [`RawDataElement`] when it needs to outlive the current iteration scope.
///
/// ```
/// use rust_stdf::{RawDataElementView, ByteOrder, StdfRecord, RecordHeader, stdf_record_type::REC_FAR};
///
/// let raw = [0u8; 0];
/// let rdv = RawDataElementView {
///     offset: 0,
///     header: RecordHeader {typ: 0, sub: 10, len: 2},
///     raw_data: &raw,
///     byte_order: ByteOrder::LittleEndian
/// };
/// let rec: StdfRecord = (&rdv).into();
/// println!("{:?}", rec);
/// assert!(rec.is_type(REC_FAR));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RawDataElementView<'a> {
    /// file offset of `raw_data` in file,
    /// after header.len and before raw_data
    ///
    /// |-typ-|-sub-|--len--⬇️--raw..data--|
    ///
    /// note that the offset is relative to the
    /// file position that runs `get_rawdata_view_iter`,
    ///
    /// it can be treated as file position **only if**
    /// the iteration starts from beginning of the file.
    pub offset: u64,

    /// used for identifying StdfRecord types
    pub header: RecordHeader,

    /// field data of current STDF Record, borrowed from the iterator's reused buffer
    pub raw_data: &'a [u8],
    pub byte_order: ByteOrder,
}

// implementation

impl RecordHeader {
    #[inline(always)]
    pub fn new() -> Self {
        RecordHeader::default()
    }

    /// Construct a STDF record header from first 4 elements of given byte array,
    /// no error would occur even if the header is invalid.
    ///
    /// Unless the array size is less than 4, StdfError of
    /// `EOF` or `Unexpected EOF` will be returned
    #[inline(always)]
    pub fn read_from_bytes(
        mut self,
        raw_data: &[u8],
        order: &ByteOrder,
    ) -> Result<Self, StdfError> {
        match raw_data.len() {
            0 => Err(StdfError::new(
                StdfErrorKind::Eof,
                String::from("No bytes to read"),
            )),
            1..=3 => Err(StdfError::new(
                StdfErrorKind::UnexpectedEof,
                String::from("Not enough data to construct record header"),
            )),
            _ => {
                let len_bytes = [raw_data[0], raw_data[1]];
                self.len = match order {
                    ByteOrder::LittleEndian => u16::from_le_bytes(len_bytes),
                    ByteOrder::BigEndian => u16::from_be_bytes(len_bytes),
                };
                self.typ = raw_data[2];
                self.sub = raw_data[3];
                // return even if we have a invalid record type, let other code to handle it
                Ok(self)
            }
        }
    }

    /// return the type_code of current header
    pub fn get_type(&self) -> u64 {
        stdf_record_type::get_code_from_typ_sub(self.typ, self.sub)
    }
}

impl StdfRecord {
    /// Create a StdfRecord of a given type with default data
    ///
    /// ```
    /// use rust_stdf::{StdfRecord, stdf_record_type::REC_PMR};
    ///
    /// // create StdfRecord with a nested PMR
    /// let new_rec = StdfRecord::new(REC_PMR);
    ///
    /// if let StdfRecord::PMR(pmr_rec) = new_rec {
    ///     assert_eq!(pmr_rec.head_num, 1);
    ///     assert_eq!(pmr_rec.site_num, 1);
    /// } else {
    ///     // this case will not be hit
    /// }
    /// ```
    #[inline(always)]
    pub fn new(rec_type: u64) -> Self {
        stdf_match_expr!(record_new)
    }

    /// Create a `StdfRecord` from a `RecordHeader` with default data
    ///
    /// The difference between `new()` is that this method can save
    /// the info of an unknown/reserved record header, help the caller to
    /// debug
    ///
    /// ```
    /// use rust_stdf::{StdfRecord, RecordHeader, stdf_record_type::REC_PMR};
    ///
    /// // create a PMR StdfRecord from header
    /// // (1, 60)
    /// let pmr_header = RecordHeader {typ: 1, sub: 60, len: 0 };
    /// let new_rec = StdfRecord::new_from_header(&pmr_header);
    ///
    /// if let StdfRecord::PMR(pmr_rec) = new_rec {
    ///     assert_eq!(pmr_rec.head_num, 1);
    ///     assert_eq!(pmr_rec.site_num, 1);
    /// } else {
    ///     // this case will not be hit
    /// }
    /// ```
    #[inline(always)]
    pub fn new_from_header(header: &RecordHeader) -> Self {
        let code = stdf_record_type::get_code_from_typ_sub(header.typ, header.sub);
        match code {
            stdf_record_type::REC_RESERVE => {
                let mut rec = ReservedRec::new();
                rec.typ = header.typ;
                rec.sub = header.sub;
                StdfRecord::ReservedRec(rec)
            }
            stdf_record_type::REC_UNKNOWN => {
                let mut rec = ReservedRec::new();
                rec.typ = header.typ;
                rec.sub = header.sub;
                StdfRecord::UnknownRec(rec)
            }
            _ => StdfRecord::new(code),
        }
    }

    /// Returns the record type cdoe of the given StdfRecord,
    /// which is defined in `rust_stdf::stdf_record_type::*` module.
    ///
    /// ```
    /// use rust_stdf::{StdfRecord, stdf_record_type::*};
    ///
    /// // `REC_PTR` type code can be used for creating a new StdfRecord
    /// let new_rec = StdfRecord::new(REC_PTR);
    /// let returned_code = new_rec.get_type();
    ///
    /// assert_eq!(REC_PTR, returned_code);
    ///
    /// // type code can be used in variety of functions
    /// // get record (typ, sub)
    /// assert_eq!((15, 10), get_typ_sub_from_code(returned_code).unwrap());
    /// // get record name
    /// assert_eq!("PTR", get_rec_name_from_code(returned_code));
    /// ```
    #[inline(always)]
    pub fn get_type(&self) -> u64 {
        stdf_match_expr!(record_type)
    }

    /// Check the StdfRecord belongs the given type code(s),
    /// it is useful for filtering the records during the parsing iteration.
    /// ```
    /// use rust_stdf::{StdfRecord, stdf_record_type::*};
    ///
    /// let new_rec = StdfRecord::new(REC_PTR);
    ///
    /// assert!(new_rec.is_type(REC_PTR));
    /// assert!(new_rec.is_type(REC_PTR | REC_FTR | REC_MPR));
    /// assert!(!new_rec.is_type(REC_FTR | REC_MPR));
    /// ```
    #[inline(always)]
    pub fn is_type(&self, rec_type: u64) -> bool {
        (self.get_type() & rec_type) != 0
    }

    /// Parse StdfRecord from byte data which **DOES NOT**
    /// contain the record header (len, typ, sub),
    ///
    /// requires a mutable StdfRecord to store the parsed data
    ///
    /// ```
    /// use rust_stdf::{StdfRecord, ByteOrder, stdf_record_type::*};
    ///
    /// let raw_with_no_header: [u8; 2] = [1, 4];
    /// let mut new_rec = StdfRecord::new(REC_FAR);
    /// new_rec.read_from_bytes(&raw_with_no_header, &ByteOrder::LittleEndian);
    ///
    /// if let StdfRecord::FAR(ref far_rec) = new_rec {
    ///     assert_eq!(4, far_rec.stdf_ver);
    /// }
    /// ```
    #[inline(always)]
    pub fn read_from_bytes(&mut self, raw_data: &[u8], order: &ByteOrder) {
        stdf_match_expr!(record_read)
    }

    /// Parse StdfRecord from byte data which
    /// **contains** the record header (len, typ, sub).
    ///
    /// ## Error
    /// if the input data is not a valid (wrong typ, sub),
    /// incomplete data or incorrect byte order, [`StdfError`] will be
    /// returned instead.
    ///
    /// ```
    /// use rust_stdf::{StdfRecord, ByteOrder, stdf_record_type::*};
    ///
    /// let raw_with_header: [u8; 6] = [0, 2, 0, 10, 1, 4];
    /// let new_rec = StdfRecord::read_from_bytes_with_header(&raw_with_header, &ByteOrder::BigEndian).unwrap();
    ///
    /// if let StdfRecord::FAR(far_rec) = new_rec {
    ///     assert_eq!(4, far_rec.stdf_ver);
    /// }
    /// ```
    #[inline(always)]
    pub fn read_from_bytes_with_header(
        raw_data: &[u8],
        order: &ByteOrder,
    ) -> Result<StdfRecord, StdfError> {
        let header = RecordHeader::new().read_from_bytes(raw_data, order)?;

        let expected_end_pos = 4 + header.len as usize;
        if raw_data.len() < expected_end_pos {
            return Err(StdfError::new(
                StdfErrorKind::UnexpectedEof,
                format!(
                    "Length of stdf field data ({} - 4 = {}) is less than what header specified ({})",
                    raw_data.len(),
                    raw_data.len() - 4,
                    header.len
                ),
            ));
        }

        let data_slice = &raw_data[4..expected_end_pos];
        let mut rec = StdfRecord::new_from_header(&header);
        rec.read_from_bytes(data_slice, order);
        Ok(rec)
    }
}

impl<'a> StdfRecordView<'a> {
    /// Build a view from `RecordHeader`, raw field data and byte order.
    ///
    /// ```
    /// use rust_stdf::{StdfRecordView, ByteOrder, RecordHeader, stdf_record_type::REC_PTR};
    ///
    /// let header = RecordHeader { len: 0, typ: 15, sub: 10 }; // PTR
    /// let raw: [u8; 0] = []; // empty field data; getters fall back to defaults
    /// let view = StdfRecordView::read_from_bytes(header, &raw, &ByteOrder::LittleEndian);
    ///
    /// if let StdfRecordView::PTR(ptr_view) = view {
    ///     assert_eq!(0, ptr_view.test_num());
    /// }
    /// assert!(view.is_type(REC_PTR));
    /// ```
    #[inline]
    pub fn read_from_bytes(
        header: RecordHeader,
        raw_data: &'a [u8],
        byte_order: &ByteOrder,
    ) -> Self {
        stdf_match_expr!(view_read)
    }

    /// Parse a `StdfRecordView` from byte data that **contains** the record
    /// header (len, typ, sub).
    ///
    /// ## Error
    /// Returns [`StdfError`] when the input is not a valid header or is
    /// incomplete (the buffer is shorter than the header declares).
    ///
    /// ```
    /// use rust_stdf::{StdfRecordView, ByteOrder};
    ///
    /// let raw_with_header: [u8; 6] = [0, 2, 0, 10, 1, 4];
    /// let view = StdfRecordView::read_from_bytes_with_header(
    ///     &raw_with_header,
    ///     &ByteOrder::BigEndian,
    /// ).unwrap();
    ///
    /// if let StdfRecordView::FAR(far_view) = view {
    ///     assert_eq!(4, far_view.stdf_ver());
    /// }
    /// ```
    #[inline(always)]
    pub fn read_from_bytes_with_header(
        raw_data: &'a [u8],
        order: &ByteOrder,
    ) -> Result<Self, StdfError> {
        let header = RecordHeader::new().read_from_bytes(raw_data, order)?;

        let expected_end_pos = 4 + header.len as usize;
        if raw_data.len() < expected_end_pos {
            return Err(StdfError::new(
                StdfErrorKind::UnexpectedEof,
                format!(
                    "Length of stdf field data ({} - 4 = {}) is less than what header specified ({})",
                    raw_data.len(),
                    raw_data.len() - 4,
                    header.len
                ),
            ));
        }

        let data_slice = &raw_data[4..expected_end_pos];
        Ok(Self::read_from_bytes(header, data_slice, order))
    }

    /// Return the record type code (see `stdf_record_type::*`).
    #[inline(always)]
    pub fn get_type(&self) -> u64 {
        stdf_match_expr!(view_type)
    }

    /// Check whether this view belongs to the given record type(s).
    #[inline(always)]
    pub fn is_type(&self, rec_type: u64) -> bool {
        (self.get_type() & rec_type) != 0
    }

    /// Parse this borrowed view into an owned [`StdfRecord`], escaping the
    /// borrow of the underlying buffer.
    #[inline]
    pub fn to_owned(&self) -> StdfRecord {
        stdf_match_expr!(view_to_owned)
    }
}

impl RawDataElement {
    #[inline(always)]
    pub fn is_type(&self, rec_type: u64) -> bool {
        (self.header.get_type() & rec_type) != 0
    }
}

impl From<&RawDataElement> for StdfRecord {
    /// It will NOT consume the input RawDataElement
    #[inline(always)]
    fn from(raw_element: &RawDataElement) -> Self {
        let mut rec = StdfRecord::new_from_header(&raw_element.header);
        rec.read_from_bytes(&raw_element.raw_data, &raw_element.byte_order);
        rec
    }
}

impl<'a> From<&'a RawDataElement> for StdfRecordView<'a> {
    /// Build a zero-copy view; does not consume the input.
    #[inline]
    fn from(raw_element: &'a RawDataElement) -> Self {
        Self::read_from_bytes(
            raw_element.header,
            &raw_element.raw_data,
            &raw_element.byte_order,
        )
    }
}

impl From<RawDataElement> for StdfRecord {
    /// It will consume the input RawDataElement
    #[inline(always)]
    fn from(raw_element: RawDataElement) -> Self {
        let mut rec = StdfRecord::new_from_header(&raw_element.header);
        rec.read_from_bytes(&raw_element.raw_data, &raw_element.byte_order);
        rec
    }
}

impl RawDataElementView<'_> {
    #[inline(always)]
    pub fn is_type(&self, rec_type: u64) -> bool {
        (self.header.get_type() & rec_type) != 0
    }
}

impl From<&RawDataElementView<'_>> for StdfRecord {
    /// Parse the borrowed bytes into an owned record; does not consume the input.
    #[inline(always)]
    fn from(raw_view: &RawDataElementView<'_>) -> Self {
        let mut rec = StdfRecord::new_from_header(&raw_view.header);
        rec.read_from_bytes(raw_view.raw_data, &raw_view.byte_order);
        rec
    }
}

impl<'a> From<&RawDataElementView<'a>> for StdfRecordView<'a> {
    /// Build a zero-copy view; does not consume the input.
    #[inline]
    fn from(raw_view: &RawDataElementView<'a>) -> Self {
        Self::read_from_bytes(raw_view.header, raw_view.raw_data, &raw_view.byte_order)
    }
}

impl From<&RawDataElementView<'_>> for RawDataElement {
    /// Copy the borrowed bytes into an owned [`RawDataElement`]; does not consume the input.
    #[inline(always)]
    fn from(raw_view: &RawDataElementView<'_>) -> Self {
        RawDataElement {
            offset: raw_view.offset,
            header: raw_view.header,
            raw_data: raw_view.raw_data.to_vec(),
            byte_order: raw_view.byte_order,
        }
    }
}

impl<'a> From<&StdfRecordView<'a>> for StdfRecord {
    /// Parse the borrowed view into an owned record; does not consume the view.
    #[inline(always)]
    fn from(view: &StdfRecordView<'a>) -> Self {
        view.to_owned()
    }
}