@ndn/tlv
Version:
NDNts: TLV
60 lines (59 loc) • 1.68 kB
JavaScript
export function makeField(tt, key, type, opts, evd) {
const fo = evd.applyDefaultsToRuleOptions(opts);
evd.add(tt, fo.repeat ?
(t, tlv) => t[key].push(type.decode(tlv)) :
(t, tlv) => t[key] = type.decode(tlv), fo);
const { asString: itemAsString = (value) => `${value}` } = type;
if (fo.repeat) {
return {
...fo,
tt,
key,
newValue: () => [],
*encode(vec) {
for (const item of vec) {
yield type.encode(item);
}
},
*asString(vec) {
if (vec.length === 0) {
return;
}
let delim = ` ${key}=[`;
for (const item of vec) {
yield `${delim}${itemAsString(item)}`;
delim = ", ";
}
yield "]";
},
};
}
return {
...fo,
tt,
key,
newValue: fo.required ? type.newValue : () => undefined,
*encode(v) {
if (v !== undefined) {
yield type.encode(v);
}
},
asString: function* (v) {
if (v !== undefined) {
yield ` ${key}=${itemAsString(v)}`;
}
},
};
}
export function sortFields(fields) {
fields.sort(({ order: a }, { order: b }) => a - b);
}
export function encodeFields(fields, obj) {
const elements = [];
for (const { tt, key, encode } of fields) {
for (const value of encode(obj[key])) {
elements.push([tt, value]);
}
}
return elements;
}