datex-core 0.0.13

The DATEX Core Rust implementation
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
use crate::{
    global::{
        operators::ModificationOperator,
        protocol_structures::injected_values::InjectedValueDeclaration,
    },
    instruction::type_instruction_codes::{
        TypeLocalOrShared, TypeMutabilityCode, TypeOwnershipCode,
    },
    prelude::*,
    shared_values::{
        PointerAddress, ReferenceMutability, RemotePointerAddress,
        SelfOwnedPointerAddress, SharedContainerMutability,
    },
    types::{
        type_definition::callable::CallableKind,
        type_definition_with_metadata::TypeMetadata,
    },
    values::core_values::{decimal::Decimal, integer::Integer},
};
use alloc::string::FromUtf8Error;
use binrw::{
    BinRead, BinResult, BinWrite, Endian,
    io::{Read, Seek, Write},
    meta::{EndianKind, ReadEndian},
};
use core::{fmt::Display, ops::Deref};
use itertools::Itertools;
use modular_bitfield::{bitfield, prelude::B4};

#[cfg(feature = "disassembler")]
mod disassembler_instruction_data;
use crate::{
    libs::core::{
        core_lib_id::CoreLibIdIndex,
        type_id::{CoreLibBaseTypeId, CoreLibTypeId, CoreLibVariantTypeId},
    },
    values::core_values::integer::typed_integer::IntegerTypeVariant,
};
#[cfg(feature = "disassembler")]
pub use disassembler_instruction_data::*;

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Int8Data(pub i8);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Int16Data(pub i16);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Int32Data(pub i32);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Int64Data(pub i64);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Int128Data(pub i128);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UInt8Data(pub u8);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UInt16Data(pub u16);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UInt32Data(pub u32);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UInt64Data(pub u64);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UInt128Data(pub u128);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Float32Data(pub f32);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Float64Data(pub f64);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct FloatAsInt16Data(pub i16);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct FloatAsInt32Data(pub i32);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct DecimalData(pub Decimal);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct IntegerData(pub Integer);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct InstantData(pub i128);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ShortTextDataRaw {
    pub length: u8,
    #[br(count = length)]
    pub text: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ShortTextData(pub String);
impl ShortTextData {
    pub fn new(text: impl Into<String>) -> Self {
        ShortTextData(text.into())
    }
}
impl Deref for ShortTextData {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl From<&ShortTextData> for ShortTextDataRaw {
    fn from(value: &ShortTextData) -> Self {
        let bytes = value.0.as_bytes();

        Self {
            length: bytes.len() as u8,
            text: bytes.to_vec(),
        }
    }
}

impl TryFrom<ShortTextDataRaw> for ShortTextData {
    type Error = FromUtf8Error;
    fn try_from(raw: ShortTextDataRaw) -> Result<Self, Self::Error> {
        let string = String::from_utf8(raw.text)?;
        Ok(ShortTextData(string))
    }
}

impl BinWrite for ShortTextData {
    type Args<'a> = ();

    fn write_options<W: Write + Seek>(
        &self,
        writer: &mut W,
        endian: Endian,
        _: Self::Args<'_>,
    ) -> BinResult<()> {
        let raw = ShortTextDataRaw::from(self);
        raw.write_options(writer, endian, ())
    }
}

impl BinRead for ShortTextData {
    type Args<'a> = ();

    fn read_options<R: Read + Seek>(
        reader: &mut R,
        endian: Endian,
        _: Self::Args<'_>,
    ) -> BinResult<Self> {
        let raw = ShortTextDataRaw::read_options(reader, endian, ())?;
        raw.try_into().map_err(|_| binrw::Error::AssertFail {
            pos: reader.stream_position().unwrap_or(0),
            message: "Invalid UTF-8 string".to_string(),
        })
    }
}

impl ReadEndian for ShortTextData {
    const ENDIAN: EndianKind = EndianKind::Endian(Endian::Little);
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct CallableSignatureData {
    pub name: ShortTextData, // empty string if anonymous
    pub kind: CallableKind,
    pub parameter_count: u8,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub requires_async: bool,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub has_rest_parameter: bool,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub has_return_type: bool,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub has_yeet_type: bool,
    #[br(count = parameter_count)]
    pub parameter_names: Vec<ShortTextData>,
    #[br(if(has_rest_parameter))]
    pub rest_parameter_name: Option<ShortTextData>,
}

impl Display for CallableSignatureData {
    fn fmt(
        &self,
        formatter: &mut core::fmt::Formatter,
    ) -> Result<(), core::fmt::Error> {
        write!(formatter, "[")?;
        write!(formatter, "kind: {}, ", self.kind)?;
        write!(formatter, "requires_async: {}, ", self.requires_async)?;
        write!(
            formatter,
            "parameters: [{}], ",
            self.parameter_names.iter().map(|n| &n.0).join(", ")
        )?;
        if let Some(rest) = &self.rest_parameter_name {
            write!(formatter, ", rest_parameter: {}, ", rest.0)?;
        }
        write!(formatter, "has_return_type: {}, ", self.has_return_type)?;
        write!(formatter, "has_yeet_type: {}", self.has_yeet_type)?;
        write!(formatter, "]")?;
        Ok(())
    }
}

impl CallableSignatureData {
    /// Returns the total number of types in the signature, including parameters, rest parameter, return type, and yeet type.
    pub fn total_type_count(&self) -> u32 {
        let mut count = self.parameter_count as u32;
        if self.has_rest_parameter {
            count += 1;
        }
        if self.has_return_type {
            count += 1;
        }
        if self.has_yeet_type {
            count += 1;
        }
        count
    }
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct CallableDeclarationData {
    pub signature: CallableSignatureData,
    pub body: InstructionBlockData,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct EntityTypeDefinitionData {
    pub name: ShortTextData,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ClassifiedValueData {
    // tag
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub has_tag: bool,
    #[br(if(has_tag))]
    pub(crate) tag: Option<ShortTextData>,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub(crate) tag_value_is_empty: bool,

    // entity
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub(crate) is_entity: bool,

    // impls
    pub impl_count: u32,
    #[br(count = impl_count)]
    pub(crate) impls: Vec<PointerAddress>,
}

impl ClassifiedValueData {
    pub fn new_tagged(tag: String, tag_value_is_empty: bool) -> Self {
        Self {
            has_tag: true,
            tag: Some(ShortTextData(tag)),
            tag_value_is_empty,
            is_entity: false,
            impl_count: 0,
            impls: Vec::new(),
        }
    }

    pub fn new_entity() -> Self {
        Self {
            has_tag: false,
            tag: None,
            tag_value_is_empty: false,
            is_entity: true,
            impl_count: 0,
            impls: Vec::new(),
        }
    }
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct CallableData {
    pub signature: CallableSignatureData,
    pub body: CallableDataBody,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct CallableDataBody {
    pub injected_value_count: u32,
    pub length: u32, // if length is 0, the body has a native implementation
    #[br(count = length)]
    pub body: Vec<u8>,
}

impl Display for CallableDataBody {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "[length: {}, injected_value_count: {}]",
            self.length, self.injected_value_count,
        )
    }
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct TextDataRaw {
    pub length: u32,
    #[br(count = length)]
    pub text: Vec<u8>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct TextData(pub String);

impl From<String> for TextData {
    fn from(value: String) -> Self {
        TextData(value)
    }
}
impl From<&str> for TextData {
    fn from(value: &str) -> Self {
        TextData(value.to_string())
    }
}

impl From<&TextData> for TextDataRaw {
    fn from(value: &TextData) -> Self {
        let bytes = value.0.as_bytes();

        Self {
            length: bytes.len() as u32,
            text: bytes.to_vec(),
        }
    }
}

impl TryFrom<TextDataRaw> for TextData {
    type Error = FromUtf8Error;
    fn try_from(raw: TextDataRaw) -> Result<Self, Self::Error> {
        let string = String::from_utf8(raw.text)?;
        Ok(TextData(string))
    }
}

impl BinWrite for TextData {
    type Args<'a> = ();

    fn write_options<W: Write + Seek>(
        &self,
        writer: &mut W,
        endian: Endian,
        _: Self::Args<'_>,
    ) -> BinResult<()> {
        let raw = TextDataRaw::from(self);
        raw.write_options(writer, endian, ())
    }
}

impl BinRead for TextData {
    type Args<'a> = ();

    fn read_options<R: Read + Seek>(
        reader: &mut R,
        endian: Endian,
        _: Self::Args<'_>,
    ) -> BinResult<Self> {
        let raw = TextDataRaw::read_options(reader, endian, ())?;
        raw.try_into().map_err(|_| binrw::Error::AssertFail {
            pos: reader.stream_position().unwrap_or(0),
            message: "Invalid UTF-8 string".to_string(),
        })
    }
}

impl ReadEndian for TextData {
    const ENDIAN: EndianKind = EndianKind::Endian(Endian::Little);
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ShortListData {
    pub element_count: u8,
}

/// Returns the size in bytes of a single element of the given core lib type id.
/// This is used for compact lists and other data structures that store elements of a single core lib type.
/// If the core lib type id does not have a known fixed size, this function will panic.
pub fn element_size(core_lib_type_id: CoreLibIdIndex) -> u32 {
    match CoreLibTypeId::try_from(core_lib_type_id) {
        Ok(id) => match id {
            CoreLibTypeId::Base(base_id) => match base_id {
                CoreLibBaseTypeId::Null => 0,
                CoreLibBaseTypeId::Boolean => 1,
                _ => unimplemented!(
                    "Core lib type does not support element size: {}",
                    core_lib_type_id
                ),
            },
            CoreLibTypeId::Variant(variant_id) => match variant_id {
                CoreLibVariantTypeId::Integer(integer_variant) => {
                    match integer_variant {
                        IntegerTypeVariant::U8 => 1,
                        IntegerTypeVariant::U16 => 2,
                        IntegerTypeVariant::U32 => 4,
                        IntegerTypeVariant::U64 => 8,
                        IntegerTypeVariant::U128 => 16,
                        IntegerTypeVariant::I8 => 1,
                        IntegerTypeVariant::I16 => 2,
                        IntegerTypeVariant::I32 => 4,
                        IntegerTypeVariant::I64 => 8,
                        IntegerTypeVariant::I128 => 16,
                        _ => unimplemented!(
                            "Core lib type does not support element size: {}",
                            core_lib_type_id
                        ),
                    }
                }
                _ => unimplemented!(
                    "Core lib type does not support element size: {}",
                    core_lib_type_id
                ),
            },
        },
        Err(_) => unimplemented!(
            "Core lib type does not support element size: {}",
            core_lib_type_id
        ),
    }
}

pub fn calculate_list_size(
    core_lib_type_id: CoreLibIdIndex,
    element_count: u32,
) -> u32 {
    let element_size = element_size(core_lib_type_id);
    element_size * element_count
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct CompactListData {
    pub element_count: u32,
    pub core_lib_type: CoreLibIdIndex,
    #[br(count = calculate_list_size(core_lib_type, element_count))]
    pub elements: Vec<u8>,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct StatementsData {
    pub statements_count: u32,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub terminated: bool,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UnboundedStatementsData {
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub terminated: bool,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ShortStatementsData {
    pub statements_count: u8,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub terminated: bool,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ListData {
    pub element_count: u32,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ShortMapData {
    pub element_count: u8,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub allow_only_text_keys: bool,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct MapData {
    pub element_count: u32,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub allow_only_text_keys: bool,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UnionData {
    pub element_count: u32,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct InstructionCloseAndStore {
    pub instruction: Int8Data,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct GetOrCreateRemoteRefData {
    pub address: RemotePointerAddress,
    pub create_block_size: u64,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct MoveWithValue {
    pub mutability: SharedContainerMutability,
    pub previous_address: SelfOwnedPointerAddress,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct SharedRef {
    pub address: PointerAddress,
    pub ref_mutability: ReferenceMutability,
    pub container_mutability: SharedContainerMutability,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub is_debug: bool,
    // TODO: hash
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct SharedRefWithValue {
    pub address: SelfOwnedPointerAddress, // address of the caller
    pub ref_mutability: ReferenceMutability,
    pub container_mutability: SharedContainerMutability,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub is_debug: bool,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ModifySharedContainerValue {
    pub operator: ModificationOperator,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct InstructionBlockData {
    pub length: u32,
    pub injected_value_count: u32,
    #[br(count = injected_value_count)]
    pub injected_values: Vec<InjectedValueDeclaration>,
    #[br(count = length)]
    pub body: Vec<u8>,
}

impl Display for InstructionBlockData {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "[length: {}, injected_value_count: {}, injected_values: [{}]]",
            self.length,
            self.injected_value_count,
            self.injected_values
                .iter()
                .map(|v| format!("{}", v))
                .join(", "),
        )
    }
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct SpliceData {
    pub start_index: u32,
    pub delete_count: u32,
    pub insert_count: u32,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct JumpData {
    pub offset: i32,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct JumpWithValueData {
    pub offset: i32,
    pub value: i32, // For now it will be just "i32", to test loops and maybe some easy inline functions, but later will be changed to universal value
                    // and maybe changed to something like "Vec<Value>", so we can send more then one Value at time
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ApplyData {
    pub arg_count: u8,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct CallMethodData {
    pub method_name: ShortTextData,
    pub arg_count: u8,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ImplMarkersData {
    pub impl_count: u8,
    #[br(count = impl_count)]
    pub impls: Vec<PointerAddress>,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct TaggedTypeData {
    pub(crate) tag: ShortTextData,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub(crate) has_type: bool,
}
impl TaggedTypeData {
    pub fn new(tag: String, has_type: bool) -> Self {
        Self {
            tag: ShortTextData(tag),
            has_type,
        }
    }
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct IntersectionData {
    pub(crate) element_count: u32,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ListSliceCollectionData {
    pub(crate) element_count: u32,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct TypeReferenceData {
    pub address: PointerAddress,
}

#[bitfield]
#[derive(BinWrite, BinRead, Clone, Copy, Debug, PartialEq)]
#[bw(map = |&x| Self::into_bytes(x))]
#[br(map = Self::from_bytes)]
#[brw(little)]
pub struct TypeMetadataBin {
    pub ownership: TypeOwnershipCode,
    pub mutability: TypeMutabilityCode,
    pub type_local_or_shared: TypeLocalOrShared,
    #[skip]
    _unused: B4,
}

impl From<&TypeMetadataBin> for TypeMetadata {
    fn from(value: &TypeMetadataBin) -> Self {
        match value.type_local_or_shared() {
            TypeLocalOrShared::Local => TypeMetadata::Local {
                mutability: (&value.mutability()).into(),
                ownership: (&value.ownership()).into(),
            },
            TypeLocalOrShared::Shared => TypeMetadata::Shared {
                mutability: (&value.mutability()).into(),
                ownership: (&value.ownership()).into(),
            },
        }
    }
}

impl From<&TypeMetadata> for TypeMetadataBin {
    fn from(value: &TypeMetadata) -> Self {
        match value {
            TypeMetadata::Local {
                mutability,
                ownership: reference_mutability,
            } => Self::new()
                .with_type_local_or_shared(TypeLocalOrShared::Local)
                .with_mutability(mutability.into())
                .with_ownership(reference_mutability.into()),
            TypeMetadata::Shared {
                mutability,
                ownership,
            } => Self::new()
                .with_type_local_or_shared(TypeLocalOrShared::Shared)
                .with_mutability(mutability.into())
                .with_ownership(ownership.into()),
        }
    }
}