binbuf/
dynamic.rs

1#![allow(type_alias_bounds)]
2
3pub use crate::{Entry, bytes_ptr as ptr};
4pub use ptr::Instance as Ptr;
5
6pub mod lens;
7
8pub type Buf<T: Instance, P> = T::Buf<P>;
9pub type BufConst<T: Instance> = T::Buf<ptr::Const>;
10pub type BufMut<T: Instance> = T::Buf<ptr::Mut>;
11
12pub fn buf_len<T: Instance>(buf: BufConst<T>) -> usize {
13    T::buf_len(buf)
14}
15
16pub unsafe fn ptr_len<T: Instance>(ptr: ptr::Const) -> usize {
17    T::buf_len(T::buf(ptr))
18}
19
20pub fn buf_swap<T: Instance>(a: BufMut<T>, b: BufMut<T>) {
21    T::buf_ptr(a).swap(T::buf_ptr(b))
22}
23
24pub fn buf_copy_to<T: Instance>(src: BufConst<T>, dst: BufMut<T>) -> usize {
25    unsafe {
26        let len = T::buf_len(src);
27        T::buf_ptr(src).range_at(0, len).copy_to(T::buf_ptr(dst).range_at(0, len));
28        len
29    }
30}
31
32pub fn buf_to_const<T: Instance, P: Ptr>(buf: Buf<T, P>) -> BufConst<T> {
33    unsafe { T::buf(T::buf_ptr(buf).to_const()) }
34}
35
36pub unsafe fn decode_ptr<T: Decode>(ptr: ptr::Const) -> (T, usize) {
37    T::decode(T::buf(ptr))
38}
39
40pub fn decode<T: Decode>(buf: BufConst<T>) -> (T, usize) {
41    T::decode(buf)
42}
43
44pub unsafe fn decode_slice<T: Decode>(slice: &[u8]) -> (T, usize) {
45    decode_ptr::<T>(ptr::Const::from_slice(slice))
46}
47
48pub unsafe fn encode_ptr<T: Instance>(ptr: ptr::Mut, value: &T) -> usize {
49    T::encode(value, T::buf(ptr))
50}
51
52pub trait Instance: Entry + Sized {
53    fn len(&self) -> usize;
54    fn buf_len(buf: BufConst<Self>) -> usize;
55    fn encode(&self, buf: BufMut<Self>) -> usize;
56}
57
58pub trait Decode: Instance {
59    fn decode(buf: BufConst<Self>) -> (Self, usize);
60}
61
62impl<T: crate::Fixed> Instance for T {
63    default fn len(&self) -> usize {
64        T::LEN
65    }
66    default fn buf_len(buf: BufConst<Self>) -> usize {
67        T::LEN
68    }
69    default fn encode(&self, buf: BufMut<Self>) -> usize {
70        <T as crate::Fixed>::encode(&self, unsafe { T::buf(T::buf_ptr(buf).range_at(0, T::LEN)) });
71        T::LEN
72    }
73}
74
75impl<T: crate::fixed::Decode> Decode for T {
76    default fn decode(buf: BufConst<Self>) -> (Self, usize) {
77        (<T as crate::fixed::Decode>::decode(buf), T::LEN)
78    }
79}
80
81// pub struct BufWithLen<T: Instance, P: Ptr>(T::Buf<P>, usize);
82
83pub trait Readable<T: Instance> {
84    fn len(&self) -> usize;
85    fn write_to(self, buf: BufMut<T>) -> usize;
86}
87
88impl<T: Instance> Readable<T> for &T {
89    fn len(&self) -> usize {
90        T::len(&self)
91    }
92
93    fn write_to(self, buf: BufMut<T>) -> usize {
94        self.encode(buf)
95    }
96}