UNPKG

@ndn/packet

Version:

NDNts: Network Layer Packets

60 lines (59 loc) 2.34 kB
import { TT } from "../an_node.js"; import { Component } from "./component_node.js"; import { ImplicitDigest, ParamsDigest } from "./digest-comp_node.js"; import { Name } from "./name_node.js"; /** * Functions to print and parse names in alternate/pretty URI syntax. * * @remarks * This class is constructed with a sequence of `NamingConvention`s. Each component is matched * against these conventions in order, and the first matching convention can determine how to * print that component in an alternate URI syntax, if available. * * Other than pre-constructed `AltUri` instances exported by this and naming convention packages, * you may construct an instance with only the naming conventions you have adopted, so that a * component that happens to match a convention that your application did not adopt is not * mistakenly interpreted with that convention. */ export class AltUriConverter { conventions; constructor(conventions) { this.conventions = conventions; } /** Print component in alternate URI syntax */ ofComponent = (comp) => { for (const conv of this.conventions) { if (conv.match(comp)) { return conv.toAltUri(comp); } } return comp.toString(); }; /** Print name in alternate URI syntax. */ ofName = (name) => `/${name.comps.map((comp) => this.ofComponent(comp)).join("/")}`; /** Parse component from alternate URI syntax */ parseComponent = (input) => { for (const conv of this.conventions) { const comp = conv.fromAltUri(input); if (comp) { return comp; } } return Component.from(input); }; /** Parse name from alternate URI syntax. */ parseName = (input) => new Name(input, this.parseComponent); } class Generic { match({ type }) { return type === TT.GenericNameComponent; } create() { /* v8 ignore next */ throw new TypeError("not supported"); } parse() { /* v8 ignore next */ throw new TypeError("not supported"); } toAltUri(comp) { return comp.toString().slice(2); } fromAltUri() { return undefined; } } /** Print Generic, ImplicitDigest, ParamsDigest in alternate URI syntax. */ export const AltUri = new AltUriConverter([ new Generic(), ImplicitDigest, ParamsDigest, ]);