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
use serde::{Deserialize, Serialize};

use crate::SizedField;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldWithMetadata<M, F> {
    pub metadata: M,
    pub field: F,
}

impl<M, F> SizedField for FieldWithMetadata<M, F>
where
    F: SizedField,
{
    type Value<'a> = F::Value<'a>;

    fn read<'a>(&self, bytes: &'a [u8]) -> anyhow::Result<Self::Value<'a>> {
        self.field.read(bytes)
    }

    fn write(&self, bytes: &mut [u8], value: Self::Value<'_>) -> anyhow::Result<()> {
        self.field.write(bytes, value)
    }

    fn last_bit_exclusive(&self) -> usize {
        self.field.last_bit_exclusive()
    }

    fn bit_len(&self) -> usize {
        self.field.bit_len()
    }
}

impl<M, F> SizedField for (M, F)
where
    F: SizedField,
{
    type Value<'a> = F::Value<'a>;

    fn read<'a>(&self, bytes: &'a [u8]) -> anyhow::Result<Self::Value<'a>> {
        self.1.read(bytes)
    }

    fn write(&self, bytes: &mut [u8], value: Self::Value<'_>) -> anyhow::Result<()> {
        self.1.write(bytes, value)
    }

    fn last_bit_exclusive(&self) -> usize {
        self.1.last_bit_exclusive()
    }

    fn bit_len(&self) -> usize {
        self.1.bit_len()
    }
}

impl<T, U, F> SizedField for (T, U, F)
where
    F: SizedField,
{
    type Value<'a> = F::Value<'a>;

    fn read<'a>(&self, bytes: &'a [u8]) -> anyhow::Result<Self::Value<'a>> {
        self.2.read(bytes)
    }

    fn write(&self, bytes: &mut [u8], value: Self::Value<'_>) -> anyhow::Result<()> {
        self.2.write(bytes, value)
    }

    fn last_bit_exclusive(&self) -> usize {
        self.2.last_bit_exclusive()
    }

    fn bit_len(&self) -> usize {
        self.2.bit_len()
    }
}