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
use std::marker::PhantomData;
use crate::result::Result;
use crate::table_id::TableID;
pub trait Bufer<'buf> {
fn buf(&self) -> &'buf [u8];
}
pub const HEADER_SZ: usize = 3;
#[allow(dead_code)]
pub const HEADER_MAX_SECTION_LENGTH: usize = 0x3FD;
pub trait WithHeader<'buf>: Bufer<'buf> {
#[inline(always)]
fn b(&self) -> &'buf [u8] {
self.buf()
}
#[inline(always)]
fn table_id(&self) -> TableID {
TableID::from(self.b()[0])
}
#[inline(always)]
fn section_syntax_indicator(&self) -> bool {
(self.b()[1] & 0b1000_0000) != 0
}
#[inline(always)]
fn section_length(&self) -> u16 {
(u16::from(self.b()[1] & 0b0000_1111) << 8) | u16::from(self.b()[2])
}
#[inline(always)]
fn sz(&self) -> usize {
HEADER_SZ + usize::from(self.section_length())
}
}
pub trait WithTableIDExtension<'buf>: Bufer<'buf> {
#[inline(always)]
fn b(&self) -> &'buf [u8] {
self.buf()
}
#[inline(always)]
fn table_id_extension(&self) -> u16 {
(u16::from(self.b()[3]) << 8) | u16::from(self.b()[4])
}
}
pub const SYNTAX_SECTION_SZ: usize = 5;
pub trait WithSyntaxSection<'buf>: Bufer<'buf> {
#[inline(always)]
fn b(&self) -> &'buf [u8] {
&self.buf()[HEADER_SZ..]
}
#[inline(always)]
#[allow(dead_code)]
fn version_number(&self) -> u8 {
(self.b()[2] & 0b0011_1110) >> 1
}
#[inline(always)]
fn current_next_indicator(&self) -> bool {
(self.b()[2] & 0b0000_0001) != 0
}
#[inline(always)]
fn section_number(&self) -> u8 {
self.b()[3]
}
#[inline(always)]
fn last_section_number(&self) -> u8 {
self.b()[4]
}
}
pub trait Szer {
fn sz(&self) -> usize;
}
pub trait TryNewer<'buf> {
fn try_new(buf: &'buf [u8]) -> Result<Self>
where
Self: Sized;
}
pub struct Cursor<'buf, T> {
buf: &'buf [u8],
phantom: PhantomData<T>,
}
impl<'buf, T> Cursor<'buf, T> {
#[inline(always)]
pub fn new(buf: &'buf [u8]) -> Cursor<'buf, T> {
Cursor {
buf,
phantom: PhantomData,
}
}
#[inline(always)]
fn buf_drain(&mut self) {
self.buf = &self.buf[self.buf.len()..];
}
}
impl<'buf, T> Iterator for Cursor<'buf, T>
where
T: TryNewer<'buf> + Szer,
{
type Item = Result<T>;
fn next(&mut self) -> Option<Self::Item> {
if self.buf.is_empty() {
return None;
}
let row = match T::try_new(self.buf) {
Ok(row) => row,
Err(e) => {
self.buf_drain();
return Some(Err(e));
}
};
if self.buf.len() > row.sz() {
self.buf = &self.buf[row.sz()..];
} else {
self.buf_drain();
}
Some(Ok(row))
}
}
pub const CRC32_SZ: usize = 4;
pub(crate) trait WithCRC32<'buf>: Bufer<'buf> {}