Browse Source

tlv: Add a typesafe serialization function for tlv namespaces

This is the counterpart to the typesafe deserialization function implemented
in an earlier commit.
travis-debug
Christian Decker 5 years ago
committed by Rusty Russell
parent
commit
e12b5c3824
  1. 22
      tools/gen/header_template
  2. 30
      tools/gen/impl_template

22
tools/gen/header_template

@ -66,7 +66,27 @@ struct ${tlv.struct_name()} {
% for tlv in tlvs.values():
struct ${tlv.struct_name()} *${tlv.struct_name()}_new(const tal_t *ctx);
bool fromwire_${tlv.name}(const u8 **cursor, size_t *max, struct ${tlv.struct_name()} *record);
/**
* Deserialize a TLV stream for the ${tlv.name} namespace.
*
* This function will parse any TLV stream, as long as the type, length and
* value fields are formatted correctly. Fields that are not known in the
* current namespace are stored in the `fields` member. Validity can be
* checked using ${tlv.name}_is_valid.
*/
bool fromwire_${tlv.name}(const u8 **cursor, size_t *max,
struct ${tlv.struct_name()} * record);
/**
* Serialize a TLV stream for the ${tlv.name} namespace.
*
* This function only considers known fields from the ${tlv.name} namespace,
* and will ignore any fields that may be stored in the `fields` member. This
* ensures that the resulting stream is valid according to
* `${tlv.name}_is_valid`.
*/
void towire_${tlv.name}(u8 **pptr, const void *record);
/**
* Check that the TLV stream is valid.

30
tools/gen/impl_template

@ -218,6 +218,36 @@ ${static}const struct tlv_record_type tlvs_${tlv.name}[] = {
% endfor
};
void towire_${tlv.name}(u8 **pptr,
const void *record)
{
size_t num_types = ${len(tlv.messages)};
const struct tlv_record_type *types = tlvs_${tlv.name};
if (!record)
return;
for (size_t i = 0; i < num_types; i++) {
u8 *val;
if (i != 0)
assert(types[i].type > types[i-1].type);
val = types[i].towire(NULL, record);
if (!val)
continue;
/* BOLT #1:
*
* The sending node:
...
* - MUST minimally encode `type` and `length`.
*/
towire_bigsize(pptr, types[i].type);
towire_bigsize(pptr, tal_bytelen(val));
towire(pptr, val, tal_bytelen(val));
tal_free(val);
}
}
bool fromwire_${tlv.name}(const u8 **cursor, size_t *max, struct ${tlv.struct_name()} *record)
{
size_t num_types = ${len(tlv.messages)};

Loading…
Cancel
Save