cddl-codegen
cddl-codegen copied to clipboard
Add support for fixed values
Supposed the following CDDL
bootstrapEraDistr = 1
Expected code
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct BootstrapEraDistr {
}
#[wasm_bindgen]
impl BootstrapEraDistr {
pub fn new() -> Self {
Self {
}
}
}
impl Deserialize for BootstrapEraDistr {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
let mut read_len = CBORReadLen::new(len);
read_len.read_elems(1)?;
let ret = Self::deserialize_as_embedded_group(raw, len);
match len {
cbor_event::Len::Len(_) => (),
cbor_event::Len::Indefinite => match raw.special()? {
CBORSpecial::Break => (),
_ => return Err(DeserializeFailure::EndingBreakMissing.into()),
},
}
ret
})().map_err(|e| e.annotate("BootstrapEraDistr"))
}
}
impl DeserializeEmbeddedGroup for BootstrapEraDistr {
fn deserialize_as_embedded_group<R: BufRead + Seek>(raw: &mut Deserializer<R>, len: cbor_event::Len) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
let index_0_value = raw.unsigned_integer()?;
if index_0_value != 1 {
return Err(DeserializeFailure::FixedValueMismatch{ found: Key::Uint(index_0_value), expected: Key::Uint(1) }.into());
}
Ok(())
})().map_err(|e| e.annotate("index_0"))?;
Ok(BootstrapEraDistr {
})
}
}
Current behavior
should not expose Fixed type in member, only needed for serializaiton: Fixed(Uint(1))
Note: that error wasn't because you had bootstrapEraDistr = 1, it was because it was later used within a group choice as the only field, which is indeed a bug, but is a separate bug.
How do we know that the user will want to have an entire struct like that generated as well instead of just something like const BOOTSTRAP_ERA_DISTR: usize = 1?
Note: the current behavior generates a wasm-exposed function like pub fn bootstrap_era_distr() -> u32 { 1 } (wasm doesn't support exposing constants) but I seem to have forgotten to make a special case for it on the rust side but could super easily generate a constant like the above. There would be more work for other people referring to it in other structs I think though.