import type { HexString } from 'https://deno.land/x/polkadot@0.2.40/util/types.ts';import type { AnyString, AnyU8a, Inspect, IText, IU8a, Registry } from '../types/index.ts';
import { compactAddLength, compactFromU8aLim, compactToU8a, hexToU8a, isHex, isString, isU8a, stringToU8a, u8aToHex, u8aToString } from 'https://deno.land/x/polkadot@0.2.40/util/mod.ts';
import { Raw } from './Raw.ts';
const MAX_LENGTH = 128 * 1024;
function decodeText (value?: null | AnyString | AnyU8a | { toString: () => string }): [string, number] { if (isU8a(value)) { if (!value.length) { return ['', 0]; }
if (value instanceof Raw) { return [u8aToString(value), 0]; }
const [offset, length] = compactFromU8aLim(value); const total = offset + length;
if (length > MAX_LENGTH) { throw new Error(`Text: length ${length.toString()} exceeds ${MAX_LENGTH}`); } else if (total > value.length) { throw new Error(`Text: required length less than remainder, expected at least ${total}, found ${value.length}`); }
return [u8aToString(value.subarray(offset, total)), total]; } else if (isHex(value)) { return [u8aToString(hexToU8a(value)), 0]; }
return [value ? value.toString() : '', 0];}
export class Text extends String implements IText { readonly registry: Registry;
public createdAtHash?: IU8a; public initialU8aLength?: number; public isStorageFallback?: boolean;
#override: string | null = null;
constructor (registry: Registry, value?: null | AnyString | AnyU8a | { toString: () => string }) { const [str, decodedLength] = decodeText(value);
super(str);
this.registry = registry; this.initialU8aLength = decodedLength; }
public get encodedLength (): number { return this.toU8a().length; }
public get hash (): IU8a { return this.registry.hash(this.toU8a()); }
public get isEmpty (): boolean { return this.length === 0; }
public override get length (): number { return super.length; }
public eq (other?: unknown): boolean { return isString(other) ? this.toString() === other.toString() : false; }
public inspect (): Inspect { const value = stringToU8a(super.toString());
return { outer: value.length ? [compactToU8a(value.length), value] : [compactToU8a(value.length)] }; }
public setOverride (override: string): void { this.#override = override; }
public toHex (): HexString { return u8aToHex(this.toU8a(true)); }
public toHuman (): string { return this.toJSON(); }
public toJSON (): string { return this.toString(); }
public toPrimitive (): string { return this.toJSON(); }
public toRawType (): string { return 'Text'; }
public override toString (): string { return this.#override || super.toString(); }
public toU8a (isBare?: boolean): Uint8Array { const encoded = stringToU8a(super.toString());
return isBare ? encoded : compactAddLength(encoded); }}