dbn 0.74.0

Library for working with Databento Binary Encoding (DBN)
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
use crate::{
    layout::{
        FieldDef, LabelDef, RecordLayout, RecordLayoutDesc, StreamLayout, StructLayout,
        StructLayoutDesc,
    },
    v4::{
        fields::{self, Field, FieldType, FixedWidth},
        types::{CStr, Decimal},
        RecordHeader,
    },
    RType,
};

use super::validate::validate;

/// Assembles a [`FieldDef`] through named setters so its many same-width fields
/// can't be transposed. The [`FieldDef`] struct literal lives only in
/// [`build`](FieldDefBuilder::build).
pub(crate) struct FieldDefBuilder {
    field_id: u16,
    type_id: u8,
    offset: u16,
    size: u16,
    flags: u8,
    def_index: u16,
    scale: i8,
}

impl FieldDefBuilder {
    pub(super) const fn new(field_id: u16, type_id: u8) -> Self {
        Self {
            field_id,
            type_id,
            offset: 0,
            size: 0,
            flags: 0,
            def_index: 0,
            scale: 0,
        }
    }

    pub(super) const fn offset(mut self, offset: u16) -> Self {
        self.offset = offset;
        self
    }

    pub(super) const fn size(mut self, size: u16) -> Self {
        self.size = size;
        self
    }

    pub(super) const fn flags(mut self, flags: u8) -> Self {
        self.flags = flags;
        self
    }

    pub(super) const fn def_index(mut self, def_index: u16) -> Self {
        self.def_index = def_index;
        self
    }

    pub(super) const fn scale(mut self, scale: i8) -> Self {
        self.scale = scale;
        self
    }

    /// The only place the [`FieldDef`] struct literal appears.
    pub(super) const fn build(self) -> FieldDef {
        FieldDef {
            field_id: self.field_id,
            offset: self.offset,
            size: self.size,
            type_id: self.type_id,
            flags: self.flags,
            def_index: self.def_index,
            scale: self.scale,
            _reserved: [0; 5],
        }
    }

    /// A padding field of `size` bytes at `offset`. Explicit so the field table covers
    /// the record with no gaps.
    const fn padding(offset: u16, size: u16) -> FieldDef {
        Self::new(fields::PADDING, fields::PADDING_ID)
            .offset(offset)
            .size(size)
            .build()
    }
}

/// Assembles a [`StreamLayout`] computing offsets and padding.
pub struct StreamLayoutBuilder {
    version: u16,
    symbol_cstr_len: u16,
    struct_layouts: Vec<StructLayout>,
    label_defs: Vec<LabelDef>,
    records: Vec<RecordLayout>,
}

/// Places the fields of one [`RecordLayout`] after its header. Created by
/// [`StreamLayoutBuilder::record`] or [`StreamLayoutBuilder::layout_of`].
#[must_use = "call `finish` to add the record to the stream"]
pub struct RecordLayoutBuilder<'a> {
    parent: &'a mut StreamLayoutBuilder,
    rtype: u16,
    schema: u16,
    name: String,
    seq: FieldCursor,
}

/// Places the fields of one [`StructLayout`]. Created by
/// [`StreamLayoutBuilder::struct_layout`].
#[must_use = "call `finish` to add the struct to the stream"]
pub struct StructLayoutBuilder<'a> {
    parent: &'a mut StreamLayoutBuilder,
    name: String,
    seq: FieldCursor,
}

impl StreamLayoutBuilder {
    /// Creates a builder for a stream with layout revision `version` whose symbol fields
    /// are `symbol_cstr_len` bytes wide.
    pub fn new(version: u16, symbol_cstr_len: u16) -> Self {
        Self {
            version,
            symbol_cstr_len,
            struct_layouts: vec![HeaderFields {
                length: fields::LENGTH,
                rtype: fields::RTYPE,
                instrument_id: fields::INSTRUMENT_ID,
            }
            .struct_layout::<RecordHeader>()],
            label_defs: vec![],
            records: vec![],
        }
    }

    pub(crate) fn pre_v4(symbol_cstr_len: u16) -> Self {
        Self {
            struct_layouts: vec![HeaderFields {
                length: fields::LENGTH_V1,
                rtype: fields::RTYPE_V1,
                instrument_id: fields::INSTRUMENT_ID_V1,
            }
            .struct_layout::<crate::RecordHeader>()],
            ..Self::new(1, symbol_cstr_len)
        }
    }

    /// Appends a [`LabelDef`] and returns its `label_defs` index.
    pub fn label(&mut self, def: LabelDef) -> u16 {
        self.label_defs.push(def);
        u16::try_from(self.label_defs.len() - 1).expect("exceeded maximum number of label defs")
    }

    /// Opens a record layout for `rtype`, starting with the header.
    pub fn record(&mut self, rtype: u16, schema: u16, name: &str) -> RecordLayoutBuilder<'_> {
        RecordLayoutBuilder::new(self, rtype, schema, name)
    }

    /// Opens a record layout for `rtype` holding the fields of the compiled record
    /// struct `R`.
    pub fn layout_of<R: RecordLayoutDesc>(&mut self, rtype: u16) -> RecordLayoutBuilder<'_> {
        let schema = RType::try_into_schema(rtype).map_or(crate::NULL_SCHEMA, |s| s as u16);
        let mut rec = self.record(rtype, schema, R::NAME);
        R::add_fields(&mut rec);
        for &(f, name) in R::REQUIRED_FIELDS {
            rec.symbol_field(f, name);
        }
        rec
    }

    /// Opens a struct layout for a struct nested in records.
    pub fn struct_layout(&mut self, name: &str) -> StructLayoutBuilder<'_> {
        StructLayoutBuilder::new(self, name)
    }

    fn label_index<'l>(
        &mut self,
        name: &str,
        values: impl IntoIterator<Item = (u16, &'l str)>,
    ) -> u16 {
        if let Some(idx) = self.label_defs.iter().position(|ld| ld.name == name) {
            return u16::try_from(idx).expect("exceeded maximum number of label defs");
        }
        self.label(LabelDef {
            name: name.to_owned(),
            labels: values
                .into_iter()
                .map(|(code, label)| (code, label.to_owned()))
                .collect(),
        })
    }

    fn def_index<T: FieldType>(&mut self) -> u16 {
        match T::LABELS {
            Some(labels) => self.label_index(labels.name, labels.values.iter().copied()),
            None if fields::uses_label_def(T::TYPE_ID) => FieldDef::UNDEF_LABEL_DEF,
            None => 0,
        }
    }

    /// The `struct_layouts` index of `S`, describing it on first use.
    fn struct_index_of<S: StructLayoutDesc>(&mut self) -> u16 {
        if let Some(idx) = self.struct_layouts.iter().position(|s| s.name == S::NAME) {
            return u16::try_from(idx).expect("exceeded maximum number of struct layouts");
        }
        let mut s = self.struct_layout(S::NAME);
        S::add_fields(&mut s);
        s.finish()
    }

    /// Validates the assembled layout and stamps each record's `layout_hash`.
    ///
    /// # Errors
    /// Returns an error if the layout violates any of the stream layout invariants.
    pub fn build(self) -> crate::Result<StreamLayout> {
        let mut layout = StreamLayout {
            stream_layout_version: self.version,
            record_layouts: self.records,
            struct_layouts: self.struct_layouts,
            label_defs: self.label_defs,
        };
        validate(&layout, self.symbol_cstr_len)?;
        for rec in &mut layout.record_layouts {
            rec.layout_hash = rec.layout_hash(&layout.struct_layouts);
        }
        Ok(layout)
    }

    pub(crate) fn into_unvalidated(self) -> StreamLayout {
        StreamLayout {
            stream_layout_version: self.version,
            record_layouts: self.records,
            struct_layouts: self.struct_layouts,
            label_defs: self.label_defs,
        }
    }
}

impl<'a> RecordLayoutBuilder<'a> {
    fn new(parent: &'a mut StreamLayoutBuilder, rtype: u16, schema: u16, name: &str) -> Self {
        let mut rec = Self {
            parent,
            rtype,
            schema,
            name: name.to_owned(),
            seq: FieldCursor::empty(),
        };
        // The header is one `STRUCT_ID` field referencing the shared
        // `RecordHeader` layout at `struct_layouts[0]`
        rec.struct_field(fields::HD.id(), "hd", HEADER_STRUCT_IDX);
        rec
    }

    /// Moves the cursor to `offset`, filling any gap with padding.
    ///
    /// # Panics
    /// Panics if `offset` is behind the cursor, i.e. it overlaps a placed field.
    pub fn at(&mut self, offset: usize) -> &mut Self {
        self.seq.at(offset);
        self
    }

    /// Places a fixed-width field at the cursor, after any alignment padding.
    pub fn field<T: FixedWidth>(&mut self, f: Field<T>, name: &str) -> &mut Self {
        let def_index = self.parent.def_index::<T>();
        self.seq.scalar(f, name, def_index);
        self
    }

    /// Places a C string field `width` bytes wide at the cursor.
    pub fn str_field(&mut self, f: Field<CStr>, name: &str, width: u16) -> &mut Self {
        self.seq.string(f, name, width);
        self
    }

    /// Places a symbol field of the stream's symbol width at the cursor.
    pub fn symbol_field(&mut self, f: Field<CStr>, name: &str) -> &mut Self {
        self.seq.string(f, name, self.parent.symbol_cstr_len);
        self
    }

    /// Places a nested struct field referencing `struct_layouts[struct_idx]`.
    pub fn struct_field(&mut self, field_id: u16, name: &str, struct_idx: u16) -> &mut Self {
        let sd = &self.parent.struct_layouts[struct_idx as usize];
        let nested = Nested {
            struct_idx,
            size: sd.size,
            align: sd.align(),
            flags: 0,
        };
        self.seq.nested(field_id, name, nested);
        self
    }

    /// A fixed-count array of the struct `S`, e.g. `Mbp10Msg`'s `[BidAskPair; 10]` book
    /// levels, adding `S`'s layout to the stream if absent. `size` spans all `N`
    /// elements; the array flag lets a reader recover the count as `size / struct.size`.
    pub fn struct_array_of<S: StructLayoutDesc, const N: usize>(
        &mut self,
        f: Field<[S; N]>,
        name: &str,
    ) -> &mut Self
    where
        [S; N]: FieldType,
    {
        let struct_idx = self.parent.struct_index_of::<S>();
        let count = u16::try_from(N).expect("struct array count exceeds u16");
        let sd = &self.parent.struct_layouts[struct_idx as usize];
        let nested = Nested {
            struct_idx,
            size: sd
                .size
                .checked_mul(count)
                .expect("struct array size exceeds u16"),
            align: sd.align(),
            flags: fields::FLAG_IS_ARRAY,
        };
        self.seq.nested(f.id(), name, nested);
        self
    }

    /// Sets the order CSV and JSON present fields in. `finish` sorts the fields by
    /// `ids` and puts unlisted fields and padding after them in declaration order.
    pub fn order(&mut self, ids: &[u16]) -> &mut Self {
        self.seq.order(ids);
        self
    }

    /// Ends the base fields and returns `base_record_size`, padded to an 8-byte
    /// boundary. Fields placed afterwards are extensions, so declare all base fields
    /// before.
    pub fn finish_base(&mut self) -> u16 {
        self.seq.finish_base()
    }

    /// Places a field with the type, size, and scale of `def` from another layout, for
    /// fields only known at runtime. The offset comes from the cursor, and a label def
    /// is copied from the source layout's `label_defs`.
    pub(crate) fn copy_field(
        &mut self,
        def: &FieldDef,
        name: &str,
        label_defs: &[LabelDef],
    ) -> &mut Self {
        let def_index = if fields::uses_label_def(def.type_id) && def.has_label_def() {
            let ld = &label_defs[usize::from(def.def_index)];
            self.parent.label_index(
                &ld.name,
                ld.labels
                    .iter()
                    .map(|(&code, label)| (code, label.as_str())),
            )
        } else {
            def.def_index
        };
        self.seq.like(def, name, def_index);
        self
    }

    /// Pads the base and any extensions to 8-byte boundaries and appends the record
    /// to the stream.
    pub fn finish(self) {
        let mut seq = self.seq;
        let base = seq.finish_record();
        self.parent.records.push(RecordLayout {
            rtype: self.rtype,
            schema: self.schema,
            base_record_size: base,
            // filled by StreamLayoutBuilder::build()
            layout_hash: 0,
            name: self.name,
            field_defs: seq.field_defs,
            field_names: seq.field_names,
        });
    }
}

impl<'a> StructLayoutBuilder<'a> {
    fn new(parent: &'a mut StreamLayoutBuilder, name: &str) -> Self {
        Self {
            parent,
            name: name.to_owned(),
            seq: FieldCursor::empty(),
        }
    }

    /// Moves the cursor to `offset`, filling any gap with padding.
    ///
    /// # Panics
    /// Panics if `offset` is behind the cursor, i.e. it overlaps a placed field.
    pub fn at(&mut self, offset: usize) -> &mut Self {
        self.seq.at(offset);
        self
    }

    /// Places a fixed-width field at the cursor, after any alignment padding.
    pub fn field<T: FixedWidth>(&mut self, f: Field<T>, name: &str) -> &mut Self {
        let def_index = self.parent.def_index::<T>();
        self.seq.scalar(f, name, def_index);
        self
    }

    /// Sets the order CSV and JSON present fields in. `finish` sorts the fields by `ids`
    /// and puts unlisted fields and padding after them in declaration order.
    pub fn order(&mut self, ids: &[u16]) -> &mut Self {
        self.seq.order(ids);
        self
    }

    /// Appends the struct to the stream and returns its `struct_layouts` index.
    pub fn finish(self) -> u16 {
        let mut seq = self.seq;
        let struct_size = seq.finish();
        self.parent.struct_layouts.push(StructLayout {
            size: struct_size,
            name: self.name,
            field_defs: seq.field_defs,
            field_names: seq.field_names,
        });
        u16::try_from(self.parent.struct_layouts.len() - 1)
            .expect("exceeded maximum number of struct layouts")
    }
}

/// The shared `RecordHeader` layout is always first.
const HEADER_STRUCT_IDX: u16 = 0;

/// The record header fields whose widths differ between DBN versions 1-3 and 4.
struct HeaderFields<L: FixedWidth, R: FixedWidth, I: FixedWidth> {
    length: Field<L>,
    rtype: Field<R>,
    instrument_id: Field<I>,
}

impl<L: FixedWidth, R: FixedWidth, I: FixedWidth> HeaderFields<L, R, I> {
    fn struct_layout<H>(self) -> StructLayout {
        let mut seq = FieldCursor::empty();
        // Length is hidden from CSV and JSON: no encoded name
        seq.scalar(self.length, "", 0);
        seq.scalar(self.rtype, "rtype", 0);
        seq.scalar(fields::PUBLISHER_ID, "publisher_id", 0);
        seq.scalar(self.instrument_id, "instrument_id", 0);
        seq.scalar(fields::TS_EVENT, "ts_event", 0);
        // Matches the column order of the v1-3 headers
        seq.order(&[fields::TS_EVENT.id()]);
        let struct_size = seq.finish();
        debug_assert_eq!(struct_size as usize, std::mem::size_of::<H>());
        StructLayout {
            size: struct_size,
            name: "RecordHeader".to_owned(),
            field_defs: seq.field_defs,
            field_names: seq.field_names,
        }
    }
}

/// The geometry of a nested-struct field, resolved from the referenced
/// [`StructLayout`] before placement.
struct Nested {
    struct_idx: u16,
    /// Spans every element when `flags` marks an array.
    size: u16,
    align: u16,
    flags: u8,
}

/// A field-placement cursor that computes offsets and padding.
#[derive(Default)]
struct FieldCursor {
    field_defs: Vec<FieldDef>,
    field_names: Vec<String>,
    cursor: u16,
    base: Option<u16>,
    /// Display order field IDs
    order: Vec<u16>,
}

impl FieldCursor {
    /// A cursor for a nested struct body, starting at offset 0.
    fn empty() -> Self {
        Self::default()
    }

    fn scalar<T: FixedWidth>(&mut self, f: Field<T>, name: &str, def_index: u16) {
        // The wire width, not `align_of::<T>()`
        self.align_to(
            fields::scalar_size(T::TYPE_ID).expect("a scalar field has a scalar type_id"),
        );
        let def = FieldDefBuilder::new(f.id(), T::TYPE_ID)
            .offset(self.cursor)
            .size(f.size())
            .flags(f.flags())
            .def_index(def_index)
            .scale(if T::TYPE_ID == Decimal::TYPE_ID {
                -9
            } else {
                0
            })
            .build();
        self.push(def, name);
    }

    fn string<T: FieldType>(&mut self, f: Field<T>, name: &str, width: u16) {
        // strings are 1-byte aligned, so no padding
        let def = FieldDefBuilder::new(f.id(), T::TYPE_ID)
            .offset(self.cursor)
            .size(width)
            .flags(f.flags())
            .build();
        self.push(def, name);
    }

    fn like(&mut self, def: &FieldDef, name: &str, def_index: u16) {
        assert_ne!(
            def.type_id,
            fields::STRUCT_ID,
            "can't copy nested field {name}"
        );
        self.align_to(fields::scalar_size(def.type_id).unwrap_or(1));
        let def = FieldDefBuilder::new(def.field_id, def.type_id)
            .offset(self.cursor)
            .size(def.size)
            .flags(def.flags)
            .def_index(def_index)
            .scale(def.scale)
            .build();
        self.push(def, name);
    }

    fn nested(&mut self, field_id: u16, name: &str, nested: Nested) {
        self.align_to(nested.align);
        let def = FieldDefBuilder::new(field_id, fields::STRUCT_ID)
            .offset(self.cursor)
            .size(nested.size)
            .flags(nested.flags)
            .def_index(nested.struct_idx)
            .build();
        self.push(def, name);
    }

    fn order(&mut self, ids: &[u16]) {
        self.order = ids.to_vec();
    }

    fn sort_by_order(&mut self) {
        let ids = std::mem::take(&mut self.order);
        let rank = |def: &FieldDef| {
            ids.iter()
                .position(|&id| id == def.field_id && !def.is_padding())
                .unwrap_or(ids.len())
        };
        let mut placed: Vec<_> = self
            .field_defs
            .drain(..)
            .zip(self.field_names.drain(..))
            .collect();
        placed.sort_by_key(|(def, _)| rank(def));
        (self.field_defs, self.field_names) = placed.into_iter().unzip();
    }

    fn at(&mut self, offset: usize) {
        let offset = u16::try_from(offset).expect("record layout exceeds u16 bytes");
        assert!(
            offset >= self.cursor,
            "offset {offset} overlaps the field ending at {}",
            self.cursor
        );
        self.pad_to(offset);
    }

    fn align_to(&mut self, align: u16) {
        self.pad_to(align_up(self.cursor, align));
    }

    fn pad_to(&mut self, offset: u16) {
        if offset > self.cursor {
            self.push(
                FieldDefBuilder::padding(self.cursor, offset - self.cursor),
                "",
            );
        }
    }

    fn finish_base(&mut self) -> u16 {
        if let Some(base) = self.base {
            return base;
        }
        self.align_to(8);
        self.base = Some(self.cursor);
        self.cursor
    }

    fn finish_record(&mut self) -> u16 {
        let base = self.finish_base();
        self.finish();
        base
    }

    fn push(&mut self, mut def: FieldDef, name: &str) {
        if self.base.is_some() && !def.is_padding() {
            def.flags |= fields::FLAG_IS_EXTENSION;
        }
        self.cursor = self
            .cursor
            .checked_add(def.size)
            .expect("record layout exceeds u16 bytes");
        self.field_defs.push(def);
        self.field_names.push(name.to_owned());
    }

    /// Round the record or struct up to an 8-byte boundary, apply the display order, and
    /// return its size.
    fn finish(&mut self) -> u16 {
        self.align_to(8);
        self.sort_by_order();
        self.cursor
    }
}

const fn align_up(v: u16, align: u16) -> u16 {
    (v + align - 1) & !(align - 1)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::v4::{
        rtype,
        types::{CStr, Char},
    };

    fn bid_ask(sb: &mut StreamLayoutBuilder) -> u16 {
        let mut s = sb.struct_layout("BidAskPair");
        s.field(Field::<i64>::new(20), "bid_px")
            .field(Field::<i64>::new(21), "ask_px")
            .field(Field::<u32>::new(22), "bid_sz")
            .field(Field::<u32>::new(23), "ask_sz");
        s.finish()
    }

    /// A one-record stream.
    fn sample(fixed_price: bool, sym_name: &str) -> StreamLayout {
        let mut sb = StreamLayoutBuilder::new(1, 8);
        let ba = bid_ask(&mut sb);
        {
            let mut r = sb.record(rtype::MBP_1, 0, "Sample");
            r.field(fields::ORDER_ID, "order_id");
            if fixed_price {
                r.field(fields::PRICE, "price");
            } else {
                r.field(Field::<i64>::new(fields::PRICE.id()), "price");
            }
            r.field(fields::SIZE, "size");
            r.field(fields::FLAGS, "flags");
            r.str_field(Field::<CStr>::new(30), sym_name, 8);
            r.struct_field(40, "levels", ba);
            r.finish();
        }
        sb.build().unwrap()
    }

    #[test]
    fn fixed_price_carries_scale_and_wire_size() {
        let rec = &sample(true, "symbol").record_layouts[0];
        let price = rec
            .field_defs
            .iter()
            .find(|f| f.field_id == fields::PRICE.id())
            .unwrap();
        assert_eq!(price.scale, -9);
        // Fixed is 8 wire bytes, not size_of::<Decimal>()
        assert_eq!(price.size, 8);
    }

    #[test]
    fn padding_and_length_are_unnamed() {
        let layout = sample(true, "symbol");
        let rec = &layout.record_layouts[0];
        for (f, name) in rec.field_defs.iter().zip(&rec.field_names) {
            if f.is_padding() {
                assert!(name.is_empty(), "padding should be unnamed");
            }
        }
        let header = &layout.struct_layouts[0];
        assert_eq!(header.name, "RecordHeader");
        assert_eq!(header.size as usize, std::mem::size_of::<RecordHeader>());
        let name_of = |id: u16| {
            let i = header
                .field_defs
                .iter()
                .position(|f| f.field_id == id)
                .unwrap();
            header.field_names[i].as_str()
        };
        assert_eq!(name_of(fields::LENGTH.id()), ""); // hidden
        assert_eq!(name_of(fields::RTYPE.id()), "rtype");
    }

    #[test]
    fn layout_hash_covers_structure_not_display() {
        let h = |l: &StreamLayout| l.record_layouts[0].layout_hash;
        let base = sample(true, "symbol");
        // Identical builds hash identically
        assert_eq!(h(&base), h(&sample(true, "symbol")));
        // A display-only change (the field name) doesn't change the hash
        assert_eq!(h(&base), h(&sample(true, "other_symbol")));
        // A structural change (price type/scale) does
        assert_ne!(h(&base), h(&sample(false, "symbol")));
        // Neither does reordering the record's or a struct's fields
        let mut reordered = base.clone();
        reordered.record_layouts[0].field_defs.reverse();
        for sd in &mut reordered.struct_layouts {
            sd.field_defs.reverse();
        }
        assert_eq!(
            h(&base),
            reordered.record_layouts[0].layout_hash(&reordered.struct_layouts)
        );
    }

    #[test]
    fn scalar_array_field_carries_size_and_array_flag() {
        let mut sb = StreamLayoutBuilder::new(1, 8);
        {
            let mut r = sb.record(rtype::MBP_0, 0, "TradeMsg");
            r.field(
                Field::<[Char; 4]>::new(fields::SALE_CONDITION.id()),
                "sale_condition",
            );
            r.finish();
        }
        let layout = sb.build().unwrap();
        let cond = layout.record_layouts[0]
            .field_defs
            .iter()
            .find(|f| f.field_id == fields::SALE_CONDITION.id())
            .unwrap();
        assert!(cond.is_array());
        assert_eq!(cond.type_id, Char::TYPE_ID);
        assert_eq!(cond.size, 4); // 4 elements x 1 byte
    }

    #[test]
    fn at_pads_a_gap() {
        let mut sb = StreamLayoutBuilder::new(1, 8);
        {
            let mut r = sb.record(rtype::MBP_0, 0, "Gapped");
            r.at(28).field(fields::SIZE, "size");
            r.finish();
        }
        let rec = &sb.build().unwrap().record_layouts[0];
        let gap = rec.field_defs[1];
        assert!(gap.is_padding());
        assert_eq!((gap.offset, gap.size), (24, 4));
        assert_eq!(rec.field_defs[2].offset, 28);
    }

    #[test]
    #[should_panic(expected = "overlaps")]
    fn at_rejects_an_overlap() {
        let mut sb = StreamLayoutBuilder::new(1, 8);
        let mut r = sb.record(rtype::MBP_0, 0, "Overlapping");
        r.field(fields::ORDER_ID, "order_id").at(28);
    }

    #[test]
    fn struct_array_of_spans_all_elements() {
        let mut sb = StreamLayoutBuilder::new(1, 8);
        {
            let mut r = sb.record(rtype::MBP_10, 0, "Mbp10");
            r.field(fields::ORDER_ID, "order_id");
            r.struct_array_of(fields::LEVELS_10, "levels");
            r.finish();
        }
        let layout = sb.build().unwrap();
        let levels = layout.record_layouts[0]
            .field_defs
            .iter()
            .find(|f| f.field_id == fields::LEVELS_10.id())
            .unwrap();
        let ba = &layout.struct_layouts[levels.def_index as usize];
        assert_eq!(ba.name, "BidAskPair");
        assert!(levels.is_array());
        assert_eq!(levels.type_id, fields::STRUCT_ID);
        assert_eq!(levels.size, ba.size * 10);
        let align = ba.align();
        assert_eq!(levels.offset % align, 0);
    }

    #[test]
    fn finish_base_starts_string_extensions() {
        let mut sb = StreamLayoutBuilder::new(1, 22);
        {
            let mut r = sb.record(rtype::MBO, 0, "WithCurrency");
            r.field(fields::ORDER_ID, "order_id");
            r.symbol_field(fields::RAW_SYMBOL, "raw_symbol");
            assert_eq!(r.finish_base(), 56);
            r.str_field(fields::CURRENCY, "currency", 4);
            r.finish();
        }
        let rec = &sb.build().unwrap().record_layouts[0];
        let find = |id| rec.field_defs.iter().find(|f| f.field_id == id).unwrap();
        let currency = find(fields::CURRENCY.id());
        assert_eq!(currency.offset, 56);
        assert!(currency.is_extension());
        assert!(!find(fields::RAW_SYMBOL.id()).is_extension());
        assert_eq!(rec.base_record_size, 56);
        assert_eq!(rec.record_size(), 64);
    }
}