Modelling a TLV (type length value) #290
-
Hi! I have a very general question. How would you model a TLV? I am using binrw quite a lot and I want to learn about The basic structure should be as follows: Particularly I want to model Here is a snippet for further illustration: #[binrw]
#[br(import(r#type: u8))]
enum Value {
#[br(assert(r#type == 1))]
Temperature(f32),
#[br(assert(r#type == 2))]
Opened(
#[br(map = |x: u8| x != 0)]
#[bw(map = |x: &bool| if *x { 1 } else { 0 })]
bool,
),
}
#[binrw]
struct TLV {
r#type: u8,
/// This value should be calculated by using the encoded size of `value`.
/// If `value` was a `Vec<u8>` I could use `calc` to write the correct size.
length: u16,
#[br(args(r#type))]
value: Value,
} When reading a Ah and btw how do you model the encoding of Thanks and greetings, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Use
The simplest way is to write a function that returns the expected size of a given type and e.g.
This depends on the file format you are writing. If it is a simple 0/1, Rust comes with |
Beta Was this translation helpful? Give feedback.
Use
pre_assert
, notassert
, for selecting an enum variant. For unknown types, specify a fallback variant as the last variant with nopre_assert
with#[br(count = length)] Vec<u8>
to collect data for an unknown type.The simplest way is to write a function that returns the expected size of a given type and e.g.
assert(length == TLV::size_of_type(r#type))
. This particular thing of determining struct size has been discussed in some other issues/discussions, so you may do a search around.