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 PointerTypeEncode<T> = {
|
|
encode(s: EncoderState, v: T): void;
|
|
toValue(v: T): Value<GenericPointer>;
|
|
}
|
|
|
|
export type PointerTypeDecode<T> = {
|
|
decode(s: DecoderState): T;
|
|
fromValue(v: Value<GenericPointer>): T;
|
|
}
|
|
|
|
export type PointerType<T> = PointerTypeEncode<T> & PointerTypeDecode<T>;
|
|
|
|
export class Pointer<T> {
|
|
embeddedValue: T;
|
|
|
|
constructor(embeddedValue: T) {
|
|
this.embeddedValue = embeddedValue;
|
|
}
|
|
|
|
equals(other: any, is: (a: any, b: any) => boolean) {
|
|
return isPointer<T>(other) && is(this.embeddedValue, other.embeddedValue);
|
|
}
|
|
|
|
asPreservesText(): string {
|
|
return '#!' + (this.embeddedValue as any).asPreservesText();
|
|
}
|
|
}
|
|
|
|
export function embed<T>(embeddedValue: T): Pointer<T> {
|
|
return new Pointer(embeddedValue);
|
|
}
|
|
|
|
export function isPointer<T>(v: Value<T>): v is Pointer<T> {
|
|
return typeof v === 'object' && 'embeddedValue' in v;
|
|
}
|
|
|
|
export class GenericPointer {
|
|
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();
|
|
}
|
|
}
|