| 694 | } |
| 695 | |
| 696 | protected internString(text: string): number | null { |
| 697 | const existing = this.stringIndexByValue.get(text); |
| 698 | if (existing !== undefined) return existing; |
| 699 | |
| 700 | if (!this.encoder) { |
| 701 | this.fail("ZRDL_INTERNAL", "drawText: TextEncoder is not available"); |
| 702 | return null; |
| 703 | } |
| 704 | |
| 705 | const nextIndex = this.stringSpanOffs.length; |
| 706 | if (nextIndex + 1 > this.maxStrings) { |
| 707 | this.fail( |
| 708 | "ZRDL_TOO_LARGE", |
| 709 | `drawText: maxStrings exceeded (count=${nextIndex + 1}, max=${this.maxStrings})`, |
| 710 | ); |
| 711 | return null; |
| 712 | } |
| 713 | |
| 714 | const cacheEligible = text.length <= ENCODED_STRING_CACHE_MAX_KEY_LENGTH; |
| 715 | const cache = cacheEligible ? this.encodedStringCache : null; |
| 716 | const cached = cache?.get(text); |
| 717 | const encoded = cached ?? this.encodeUtf8(text); |
| 718 | if (!cached && cache) { |
| 719 | if (cache.size >= this.encodedStringCacheCap) { |
| 720 | cache.clear(); |
| 721 | } |
| 722 | cache.set(text, encoded); |
| 723 | } |
| 724 | const byteLen = encoded.byteLength; |
| 725 | |
| 726 | const nextBytesLen = this.stringBytesLen + byteLen; |
| 727 | if (nextBytesLen > this.maxStringBytes) { |
| 728 | this.fail( |
| 729 | "ZRDL_TOO_LARGE", |
| 730 | `drawText: maxStringBytes exceeded (bytes=${nextBytesLen}, max=${this.maxStringBytes})`, |
| 731 | ); |
| 732 | return null; |
| 733 | } |
| 734 | |
| 735 | this.ensureStringBytesCapacity(nextBytesLen); |
| 736 | if (this.error) return null; |
| 737 | |
| 738 | const off = this.stringBytesLen; |
| 739 | this.stringBytesBuf.set(encoded, off); |
| 740 | this.stringBytesLen = nextBytesLen; |
| 741 | this.stringSpanOffs.push(off); |
| 742 | this.stringSpanLens.push(byteLen); |
| 743 | this.stringIndexByValue.set(text, nextIndex); |
| 744 | |
| 745 | this.maybeFailTooLargeAfterWrite(); |
| 746 | |
| 747 | return nextIndex; |
| 748 | } |
| 749 | |
| 750 | private encodeUtf8(text: string): Uint8Array { |
| 751 | let asciiOnly = true; |