-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamic_struct_index_writer.rs
54 lines (48 loc) · 1.45 KB
/
dynamic_struct_index_writer.rs
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
use crate::{DynamicStructIndexType, Position, Write, Writer};
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DynamicStructIndexWriter {
U8(DynamicStructIndexWriterI<u8>),
U16(DynamicStructIndexWriterI<u16>),
}
impl Write for DynamicStructIndexWriter {
type Output = DynamicStructIndexWriter;
fn write(&self, writer: &mut Writer) -> Position<Self::Output> {
match self {
DynamicStructIndexWriter::U8(s) => writer.write(s).cast(),
DynamicStructIndexWriter::U16(s) => writer.write(s).cast(),
}
}
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DynamicStructIndexWriterI<I>(Vec<Option<I>>)
where
I: DynamicStructIndexType;
impl<I> DynamicStructIndexWriterI<I>
where
I: DynamicStructIndexType,
{
pub fn new(field_count: I) -> DynamicStructIndexWriterI<I> {
DynamicStructIndexWriterI(vec![None; field_count.to_usize().unwrap()])
}
pub fn set_field_offset(&mut self, field_id: I, offset: I) {
self.0.splice(
field_id.to_usize().unwrap()..field_id.to_usize().unwrap() + 1,
vec![Some(offset)],
);
}
}
impl<I> Write for DynamicStructIndexWriterI<I>
where
I: DynamicStructIndexType,
{
type Output = DynamicStructIndexWriterI<I>;
fn write(&self, writer: &mut Writer) -> Position<Self::Output> {
let position = writer.position();
let field_count = I::from_usize(self.0.len()).unwrap();
writer.write(&field_count);
for field_offset in self.0.iter() {
writer.write(&field_offset.unwrap_or_else(I::zero));
}
position
}
}