-
Notifications
You must be signed in to change notification settings - Fork 8
/
metadata.ts
53 lines (45 loc) · 1.68 KB
/
metadata.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { Keyword } from "@ndn/naming-convention2";
import { type Component, Name, TT } from "@ndn/packet";
import { type Decodable, type Decoder, type EncodableObj, type Encoder, EvDecoder, Extensible } from "@ndn/tlv";
/** 32=metadata component. */
export const MetadataKeyword: Component = Keyword.create("metadata");
function makeEvd<M extends Metadata>(title: string) {
return new EvDecoder<M>(title)
.add(TT.Name, (t, { value }) => t.name = new Name(value), { required: true })
.setIsCritical(() => false);
}
const EVD = makeEvd<Metadata>("Metadata");
/** RDR metadata packet content. */
export class Metadata implements EncodableObj {
/**
* Constructor.
* @param name versioned name.
*/
constructor(public name = new Name()) {}
public static decodeFrom(decoder: Decoder): Metadata {
return EVD.decodeValue(new Metadata(), decoder);
}
public encodeTo(encoder: Encoder): void {
encoder.prependValue(this.name);
}
}
export namespace Metadata {
export interface Constructor<M extends Metadata = Metadata> extends Decodable<M> {
new(name?: Name): M;
}
/** Class decorator on an extensible Metadata subclass. */
export function extend<M extends Metadata & Extensible>(ctor: new() => M): void {
const registry = new ctor()[Extensible.TAG];
const evd = makeEvd<M>(ctor.name).setUnknown(registry.decodeUnknown);
Object.defineProperty(ctor, "decodeFrom", {
value(decoder: Decoder): M {
return evd.decodeValue(new ctor(), decoder);
},
});
Object.defineProperty(ctor.prototype, "encodeTo", {
value(this: M, encoder: Encoder): void {
encoder.prependValue(this.name, ...registry.encode(this));
},
});
}
}