56 lines
1.4 KiB
TypeScript
56 lines
1.4 KiB
TypeScript
import type { EncoderState } from "./encoder";
|
|
import type { DecoderState } from "./decoder";
|
|
import type { Value } from "./values";
|
|
|
|
export type EmbeddedTypeEncode<T> = {
|
|
encode(s: EncoderState, v: T): void;
|
|
toValue(v: T): Value<GenericEmbedded>;
|
|
}
|
|
|
|
export type EmbeddedTypeDecode<T> = {
|
|
decode(s: DecoderState): T;
|
|
fromValue(v: Value<GenericEmbedded>): T;
|
|
}
|
|
|
|
export type EmbeddedType<T> = EmbeddedTypeEncode<T> & EmbeddedTypeDecode<T>;
|
|
|
|
export class Embedded<T> {
|
|
embeddedValue: T;
|
|
|
|
constructor(embeddedValue: T) {
|
|
this.embeddedValue = embeddedValue;
|
|
}
|
|
|
|
equals(other: any, is: (a: any, b: any) => boolean) {
|
|
return isEmbedded<T>(other) && is(this.embeddedValue, other.embeddedValue);
|
|
}
|
|
|
|
asPreservesText(): string {
|
|
return '#!' + (this.embeddedValue as any).asPreservesText();
|
|
}
|
|
}
|
|
|
|
export function embed<T>(embeddedValue: T): Embedded<T> {
|
|
return new Embedded(embeddedValue);
|
|
}
|
|
|
|
export function isEmbedded<T>(v: Value<T>): v is Embedded<T> {
|
|
return typeof v === 'object' && 'embeddedValue' in v;
|
|
}
|
|
|
|
export class GenericEmbedded {
|
|
generic: Value;
|
|
|
|
constructor(generic: Value) {
|
|
this.generic = generic;
|
|
}
|
|
|
|
equals(other: any, is: (a: any, b: any) => boolean) {
|
|
return typeof other === 'object' && 'generic' in other && is(this.generic, other.generic);
|
|
}
|
|
|
|
asPreservesText(): string {
|
|
return this.generic.asPreservesText();
|
|
}
|
|
}
|