preserves/implementations/javascript/packages/core/src/pointer.ts

56 lines
1.4 KiB
TypeScript
Raw Normal View History

import type { EncoderState } from "./encoder";
import type { DecoderState } from "./decoder";
2021-03-17 09:21:48 +00:00
import type { Value } from "./values";
export type PointerTypeEncode<T> = {
2021-04-24 19:59:52 +00:00
encode(s: EncoderState, v: T): void;
toValue(v: T): Value<GenericPointer>;
}
2021-04-24 19:59:52 +00:00
export type PointerTypeDecode<T> = {
decode(s: DecoderState): T;
fromValue(v: Value<GenericPointer>): T;
2021-04-24 19:59:52 +00:00
}
2021-03-17 09:21:48 +00:00
export type PointerType<T> = PointerTypeEncode<T> & PointerTypeDecode<T>;
2021-04-24 19:59:52 +00:00
export class Pointer<T> {
embeddedValue: T;
constructor(embeddedValue: T) {
this.embeddedValue = embeddedValue;
2021-03-17 09:21:48 +00:00
}
equals(other: any, is: (a: any, b: any) => boolean) {
2021-04-24 19:59:52 +00:00
return isPointer<T>(other) && is(this.embeddedValue, other.embeddedValue);
2021-03-17 09:21:48 +00:00
}
asPreservesText(): string {
2021-04-24 19:59:52 +00:00
return '#!' + (this.embeddedValue as any).asPreservesText();
2021-03-17 09:21:48 +00:00
}
}
2021-04-24 19:59:52 +00:00
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;
2021-03-17 09:21:48 +00:00
}
export class GenericPointer {
2021-04-24 19:59:52 +00:00
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();
}
2021-03-17 09:21:48 +00:00
}