@slnknrr/str-im 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -1,75 +1,21 @@
1
- Slinkin Restricted License 1.0
2
- (A source-available license derived from the MIT License — no use in AI/ML, mandatory source attribution, email-based exceptions, Georgian governing law.)
3
-
4
- Copyright (c) 2026 Yury Slinkin <slnknrr.dev@gmail.com>
5
-
6
- NOTICE: THIS SOFTWARE IS SUBJECT TO A MODIFIED MIT LICENSE. IT STRICTLY PROHIBITS
7
- ANY USE IN MACHINE LEARNING, DATASETS, OR AUTOMATED CODE GENERATION. IT MANDATES
8
- PRESERVING MANDATORY SOURCE-LEVEL ATTRIBUTION COMMENTS IN ALL FILES. EXCEPTIONS
9
- CAN ONLY BE GRANTED VIA VERIFIED EMAIL PROTOCOL. THIS LICENSE IS GOVERNED BY THE
10
- LEGISLATION OF GEORGIA, GIVING ABSOLUTE PRIORITY TO TRUE AUTHORSHIP AND INALIENABLE
11
- MORAL RIGHTS OVER DIGITAL COMMUNICATIONS.
12
-
13
- Permission is hereby granted, free of charge, to any person obtaining a copy
14
- of this software and associated documentation files (the "Software"), to deal
15
- in the Software without restriction, including without limitation the rights
16
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
- copies of the Software, subject to the following conditions:
18
-
19
- The above copyright notice, this permission notice, the RESTRICTIONS,
20
- FILE ATTRIBUTION REQUIREMENTS, EXCEPTIONS VIA EMAIL, and GOVERNING LAW sections
21
- below shall be included in all copies or substantial portions of the Software.
22
-
23
- RESTRICTIONS:
24
- The Software, any derivative works, modifications, or products significantly
25
- influenced by or containing logic from the Software, shall not be used,
26
- directly or indirectly, in any of the following ways:
27
- 1. For the creation, training, testing, fine-tuning, or validation of machine
28
- learning (ML) models, artificial intelligence (AI) systems, or neural networks.
29
- 2. Inclusion, scraping, or ingestion into datasets intended for machine learning,
30
- data mining, or AI training.
31
- 3. Use by, integration into, or analysis by automated code generation systems,
32
- program synthesis tools, or AI coding assistants.
33
-
34
- FILE ATTRIBUTION REQUIREMENTS:
35
- All source code files derived from, copied from, or containing substantial portions
36
- of the Software must retain or include a top-level header comment block containing:
37
- 1. The original author's name and contact email (as specified in the Copyright notice).
38
- 2. The original copyright year or date range.
39
- 3. The origin link or source repository URL where the original code was obtained.
40
- 4. A clear indication that the file is governed by this Restricted MIT License.
41
- Stripping, removing, minifying out, or obscuring these header comments in source files
42
- or derivative works is strictly prohibited and constitutes a material breach of this License.
43
-
44
- EXCEPTIONS VIA EMAIL:
45
- The restrictions outlined above may be waived or modified only upon explicit
46
- written permission granted via email. To be considered authoritative, the
47
- permission process must meet the following criteria:
48
- 1. A formal request must be sent to the email address explicitly listed in
49
- the Copyright notice above.
50
- 2. The request must explicitly specify:
51
- - The exact names of the packages, projects, or licensed products.
52
- - The identity of the party (person or legal entity) requesting the rights.
53
- - The exact scope, purpose of use, and the duration (time limit) of the
54
- requested permission.
55
- 3. A clear, affirmative response must be issued from the Copyright holder's
56
- designated email address.
57
-
58
- GOVERNING LAW AND TRUE OWNERSHIP:
59
- Notwithstanding the email exception mechanism described above, this License and
60
- any granted permissions shall be governed by and construed in accordance with
61
- the legislation of Georgia.
62
- The inalienable moral rights of authorship and the absolute property rights
63
- over the Software take precedence over any digital communication. An email
64
- permission is deemed valid and legally binding only if it is issued by the true
65
- legal owner of the copyright. Unauthorized access to the designated email,
66
- account compromise, or impersonation shall render any granted permission
67
- null and void ab initio (from the beginning).
68
-
69
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
70
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
71
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
72
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
73
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
74
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
75
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yury Slinkin <slnknrr.dev@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  **A zero-allocation string engine. Numbers in the core, strings only at the boundary.**
4
4
 
5
+ > Strings giving you *str-ess*? Take [**str-ez**](https://www.npmjs.com/package/@slnknrr/str-ez). Want them to *str-eam*? Take [**str-im**](https://www.npmjs.com/package/@slnknrr/str-im). Same engine, two accents: `str-ez` says `startsWith` and returns `true`; `str-im` says `starts` and returns `-1` because it has more to tell you.
6
+
5
7
  `str-im` adds exactly the string operations JavaScript is missing — and nothing it already has. It never re-implements `for..of`, `indexOf`, or `slice`. It implements the things you keep hand-writing (with bugs): unique-character iterators, utf-8 buffer inspection **without decoding**, run detection, grapheme/width segmentation, mixed-script and homoglyph detection, bounded edit distance, single-pass multi-pattern search, lazy split, and entropy.
6
8
 
7
9
  The core runs on **code units and code points as numbers**. A `number` below 2³¹ is a V8 Smi — it lives inside the pointer, so it costs zero allocations. Strings are created in exactly one place: the public boundary, when you ask for characters back. If you only ask a *question* ("how many distinct?", "is it mixed-script?", "does it fit in 120 bytes?"), no string is ever built.
@@ -25,7 +27,8 @@ s.near('kitten', 'sitting', 2); // Infinity — "not within 2 edits", answered
25
27
  - **Lazy and bounded by default.** Iterators stop when you stop pulling. `max` lets you ask "is there more than *N*?" and leave. `near` answers "≤ *max* edits?" in `O(n·max)` time and `O(max)` space — never the full `O(n·m)`.
26
28
  - **Source-agnostic.** Every method works on a `string`, a utf-8 `Uint8Array`/`Buffer`, or an `Array<number>` of code points — through a one-line adapter you can extend to your own type.
27
29
  - **Regex-free classification.** Not one character class is tested with a regex (`/\p{L}/u.test(c)` forces a string allocation per character). Unicode properties are sorted `Int32Array` ranges, generated offline, queried by binary search, and materialized lazily on first use.
28
- - **Pure ESM, dependency-free, sync.** ~1900 lines, one file, immutable tables. Node ≥ 20.
30
+ - **Pure ESM, dependency-free, sync.** ~2300 lines, one file, immutable tables. Node ≥ 20.
31
+ - **One mutable string, one strategy.** `mut()` edits a string — or a utf-8 buffer, in the caller's own memory — in place, shrink-only, and materializes once. See [Mutable string](#14--mutable-string--mut).
29
32
 
30
33
  ## What it is NOT
31
34
 
@@ -45,7 +48,7 @@ npm install @slnknrr/str-im
45
48
 
46
49
  ```js
47
50
  import s from '@slnknrr/str-im'; // ready-to-use singleton — no `new`
48
- import { strim, _strim, NotFound, UNICODE } from '@slnknrr/str-im';
51
+ import { strim, _strim, Mut, NotFound, UNICODE } from '@slnknrr/str-im';
49
52
  ```
50
53
 
51
54
  Requirements: **Node ≥ 20**, ESM only (`"type": "module"` or `import`). Tables track **Unicode `UNICODE`** (currently 17.0).
@@ -88,6 +91,8 @@ Every reading method resolves an adapter **once** per call, then stays in a tigh
88
91
  | `Uint8Array` / `Buffer` | utf-8 bytes | `s.len(Buffer.from('café'))` |
89
92
  | `Array<number>` | ready code points | `s.len([99, 97, 102, 233])` |
90
93
 
94
+ Needles — the things `find`, `split`, `clear` and `omit` look for — are spelled in the **source's own units**: search a utf-8 buffer for `'é'` and it is matched as the bytes `C3 A9`; search an array of code points for `'😀'` and it is matched as `0x1F600`, not as a surrogate pair.
95
+
91
96
  Register your own once, process-wide, and the entire method family works with it:
92
97
 
93
98
  ```js
@@ -123,7 +128,7 @@ Why these win, structurally: the early-exit iterator **stops at 8** instead of s
123
128
 
124
129
  ## API
125
130
 
126
- 73 methods across 13 groups. `str` accepts any registered [source](#sources--adapters). A `target` is a `string` to locate or a `number` treated as a position. `max`/`n` default sensibly. Iterator methods return lazy `IterableIterator`s.
131
+ 75 methods across 14 groups. `str` accepts any registered [source](#sources--adapters). A `target` is a `string` to locate or a `number` treated as a position. `max`/`n` default sensibly. Iterator methods return lazy `IterableIterator`s.
127
132
 
128
133
  ### 1 · Slices relative to a target — `l` = last, `b` = back
129
134
  | Method | Returns |
@@ -213,7 +218,7 @@ All take `(str, max=∞)`.
213
218
  | `ind(str)` | `{ char, size, min, mixed }` indentation analysis |
214
219
  | `dedent(str)` | strip the common indent |
215
220
  | `esc(str, chars?, opts?)` / `unesc` | escape / unescape a character set |
216
- | `trim(str, chars?)` / `rtrim` | trim a custom set (default `\p{White_Space}`) |
221
+ | `trim(str, chars?)` / `ltrim` / `rtrim` | trim a custom set (default `\p{White_Space}`) — both edges / left / right |
217
222
 
218
223
  `opts`: `{ quote, quotes, esc, nest, limit, pairs }` — quote/escape-aware splitting and matching (CSV, shell).
219
224
 
@@ -239,6 +244,41 @@ All take `(str, max=∞)`.
239
244
  | `style(str)` | naming style: `camel`/`pascal`/`snake`/`screaming`/`kebab`/`dot`/`mixed`/… |
240
245
  | `wrap(str, width, opts?)` | width-aware line wrap (display columns, ANSI-safe) |
241
246
 
247
+ ### 14 · Mutable string — `mut`
248
+ | Method | Does |
249
+ |---|---|
250
+ | `mut(src)` | a `Mut` over a `string` (decoded once into a `Uint16Array`) or a utf-8 `Uint8Array` (edited **in place**, in the caller's memory) |
251
+
252
+ Everything above *reads*. A `Mut` is the one object that *writes*, under a single strategy: **one buffer, edits that only ever shrink it, one string at the end.** Every edit streams over the engine's index generators and compacts with `copyWithin` behind the read position — no intermediate string, no second buffer. An edit that would need the buffer to grow throws `RangeError` **before** the first write, so a `Mut` is never left half-edited. Every method returns `this`; `length` is in units (code units or bytes); the object is itself a [source](#sources--adapters), so `s.len(m)`, `s.blen(m)`, `s.find(m, …)` work on it as it is.
253
+
254
+ | `Mut` method | In-place twin of |
255
+ |---|---|
256
+ | `slice(start, end?)` | `str.slice` — keep `[start, end)` in units; out of range throws |
257
+ | `substr` / `lsubstr` / `substrb` / `lsubstrb` `(target, offset?)` | §1 — keep only that piece; `NotFound` as in the engine |
258
+ | `drop(needles)` | `clear` |
259
+ | `flat(chars?, keep?)` | `flat` |
260
+ | `unesc(opts?)` | `unesc` |
261
+ | `trim` / `ltrim` / `rtrim` `(chars?)` | §10 |
262
+ | `cut` / `bcut` / `wcut` `(max, ell?)` | §8 — an ellipsis must fit in the cut region |
263
+ | `dedent()` | `dedent` |
264
+ | `wrap(width)` | `wrap` — the space before a word that no longer fits becomes `
265
+ `; same length |
266
+ | `fold()` | simple case folding by table; in utf-8 a fold that widens (`Ⱥ` → `ⱥ`, 2 → 3 bytes) is refused up front |
267
+ | `toString()` / `value()` | one string; or the source's own type — for a buffer, a zero-copy `subarray` of the live prefix |
268
+
269
+ ```js
270
+ s.mut(' Héllo,, wörld!! ').trim().flat(',! ').drop('l').fold().toString(); // 'héo, wörd!'
271
+
272
+ const buf = Buffer.from(' héllo ');
273
+ const m = s.mut(buf).trim(); // edits buf itself
274
+ m.value(); // Uint8Array(6) — a view into buf, no copy
275
+ m.value().buffer === buf.buffer; // true
276
+
277
+ s.mut('世').bcut(2, 'ab'); // RangeError before any write: 'ab' does not fit in 1 unit
278
+ ```
279
+
280
+ What is deliberately **not** on a `Mut`: `esc`, `skel`, `deburr` and anything else that can grow. The strategy is the guarantee.
281
+
242
282
  ### Statics & factory
243
283
  | Symbol | Purpose |
244
284
  |---|---|
@@ -248,6 +288,7 @@ All take `(str, max=∞)`.
248
288
  | `_strim(overrides?)` | build a configured instance (see below) |
249
289
  | `UNICODE` | Unicode version of the tables |
250
290
  | `NotFound` | error class for absent targets |
291
+ | `Mut` | the mutable-string class, for `instanceof` — instances come from `mut()` |
251
292
 
252
293
  ---
253
294
 
@@ -294,6 +335,19 @@ Every internal call dispatches through `this`, so replacing one method replaces
294
335
 
295
336
  ---
296
337
 
338
+ ## Links
339
+
340
+ - Source: [https://codeberg.org/slnknrr/strim_lib.js-for-pm_npm/src/branch/main](https://codeberg.org/slnknrr/strim_lib.js-for-pm_npm/src/branch/main)
341
+ - npm: [https://www.npmjs.com/package/@slnknrr/str-im](https://www.npmjs.com/package/@slnknrr/str-im)
342
+ - Friendly wrapper — familiar names, booleans and arrays over the same engine: [@slnknrr/str-ez](https://www.npmjs.com/package/@slnknrr/str-ez)
343
+
344
+ ## Author
345
+
346
+ Yury Slinkin (Юрий Слинкин)
347
+
348
+ - Email: slnknrr.dev@gmail.com
349
+ - Codeberg: https://codeberg.org/slnknrr
350
+
297
351
  ## License
298
352
 
299
- **MIT + restrictions.** The MIT License, with added limits — chiefly no use in AI/ML training and mandatory source-attribution headers. Full terms: [Slinkin Restricted License 1.0](./LICENSE.md). © 2026 [Yury Slinkin](https://codeberg.org/slnknrr).
353
+ MIT. See [LICENSE.md](https://codeberg.org/slnknrr/strim_lib.js-for-pm_npm/src/branch/main/LICENSE.md).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slnknrr/str-im",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Zero-allocation string engine: unique-character iterators, UTF-8 buffer inspection without decoding, run detection, Unicode classification. Numbers in the core, strings only at the boundary.",
5
5
  "keywords": [
6
6
  "string",
@@ -19,7 +19,7 @@
19
19
  "entropy",
20
20
  "aho-corasick"
21
21
  ],
22
- "license": "SEE LICENSE IN LICENSE.md",
22
+ "license": "MIT",
23
23
  "author": "Yury Slinkin <slnknrr.dev@gmail.com>",
24
24
  "repository": {
25
25
  "type": "git",
package/src/str-im.js CHANGED
@@ -100,6 +100,17 @@
100
100
  // literally the same class, not two identical ones
101
101
  // - the default path pays nothing at all: the singleton is created once and is not subclassed
102
102
  // Dev-build diagnostic: a counter of created configurations, a warning after the 4th.
103
+ //
104
+ //13. MUTABLE STRING (Mut). Everything above READS. Mut is the one place that WRITES, and it
105
+ // does so under one strategy: a single buffer, edits that only ever SHRINK it, one string at
106
+ // the end. A string is decoded once into a Uint16Array; a utf-8 buffer is edited in the
107
+ // caller's own memory. Every edit streams over one of the engine's index generators and
108
+ // compacts with copyWithin BEHIND the read position — no intermediate string, no second
109
+ // buffer, no per-element allocation. An edit that would need the buffer to grow (an ellipsis
110
+ // that does not fit, a case fold that gets wider in utf-8) is a RangeError BEFORE the first
111
+ // write, so a Mut is never left half-edited. The object is a registered source (point 4),
112
+ // so every reading method works on it as it is. Growing operations (esc, skel, deburr) do
113
+ // not belong here, and that is a feature: the strategy is the guarantee.
103
114
 
104
115
  import * as T from './tables.js';
105
116
 
@@ -134,6 +145,8 @@ const ALPHA = new Map(); //Map<name, {v: Set<number>, c: Set<number>}>
134
145
  const TABS = Object.create(null); //cache of materialized Int32Array
135
146
  const ACS = new Map(); //cache of Aho-Corasick automata, see _ac
136
147
  const AC_MAX = 32;
148
+ const U8ENC = new TextEncoder(); //utf-8 needles (_needles) and the Mut boundary (point 13)
149
+ const U8DEC = new TextDecoder();
137
150
 
138
151
  //base64 -> 6-bit value (inverse of the alphabet from build-tables.js). Uint8Array(128),
139
152
  //indexed straight by charCodeAt: no Map, no branches in _decode. `d & 31` — the low
@@ -688,16 +701,24 @@ class strim {
688
701
  return true; //GB999
689
702
  }
690
703
 
691
- //normalize a needle set to an array of Int32Array code units + a cache key.
692
- //Accepts a string, a number (code point), or an iterable of those.
693
- _needles(target, fold) {
704
+ //normalize a needle set to an array of Int32Array units. Accepts a string, a number
705
+ //(code point), or an iterable of those. dec — the SOURCE's decoding (point 4): the
706
+ //automaton runs over raw source units, so a needle must be spelled in the same units —
707
+ //utf-16 code units for a string, utf-8 bytes for a buffer, code points for an array.
708
+ //Folding is a code-unit / code-point transform and has no meaning on bytes (see _gfind).
709
+ _needles(target, fold, dec = 0) {
694
710
  const list = [];
695
711
  const one = (t) => {
696
712
  if (typeof t === 'number') t = String.fromCodePoint(t);
697
713
  if (typeof t !== 'string') throw new TypeError('str-im: a needle must be a string or a code point');
698
714
  if (t.length === 0) return; //an empty needle would match everywhere and hang the automaton
699
- const a = new Int32Array(t.length);
700
- for (let i = 0; i < t.length; i++) a[i] = fold ? this._fold(t.charCodeAt(i)) : t.charCodeAt(i);
715
+ let a;
716
+ if (dec === 1) a = Int32Array.from(U8ENC.encode(t));
717
+ else if (dec === 2) a = Int32Array.from(t, (c) => fold ? this._fold(c.codePointAt(0)) : c.codePointAt(0));
718
+ else {
719
+ a = new Int32Array(t.length);
720
+ for (let i = 0; i < t.length; i++) a[i] = fold ? this._fold(t.charCodeAt(i)) : t.charCodeAt(i);
721
+ }
701
722
  list.push(a);
702
723
  };
703
724
  if (typeof target === 'string' || typeof target === 'number') one(target);
@@ -716,9 +737,12 @@ class strim {
716
737
  //The core for find, lfind, ifind, omit, omitn, clear, split, splitn.
717
738
  //For a single needle the automaton degenerates into KMP, no separate code needed.
718
739
  _ac(needles) {
719
- //cache key — the needles themselves. as a separator is safe: empty needles are dropped
740
+ //cache key — the needles themselves, as decimal units with ',' inside a needle and ';'
741
+ //after it. Both separators are outside the digit alphabet, so the key is injective:
742
+ //['a', 'b'] and ['a b'] MUST NOT share an automaton (a raw-character key with a space
743
+ //separator once let them, and the second call silently got the first one's matches).
720
744
  let key = '';
721
- for (const n of needles) { key += ' '; for (let i = 0; i < n.length; i++) key += String.fromCharCode(n[i]); }
745
+ for (const n of needles) key += n.join(',') + ';';
722
746
  const hit = ACS.get(key);
723
747
  if (hit) { ACS.delete(key); ACS.set(key, hit); return hit; } //LRU: refresh
724
748
  //--- build the trie on temporary Maps (build stage only) ---
@@ -1027,7 +1051,7 @@ class strim {
1027
1051
  omit(str, omits) { return this._prime(this._gomit(str, omits)); }
1028
1052
  *_gomit(str, omits) {
1029
1053
  const adp = this._adapter(str);
1030
- const ac = this._ac(this._needles(omits, false));
1054
+ const ac = this._ac(this._needles(omits, false, adp.dec));
1031
1055
  yield; //barrier (point 6): validation of the source and needles has already happened
1032
1056
  const seg = this._seg(str, adp, ac);
1033
1057
  for (let s = seg.next(); !s.done; s = seg.next()) {
@@ -1045,7 +1069,7 @@ class strim {
1045
1069
  omitn(str, omits) { return this._prime(this._gomitn(str, omits)); }
1046
1070
  *_gomitn(str, omits) {
1047
1071
  const adp = this._adapter(str);
1048
- const ac = this._ac(this._needles(omits, false));
1072
+ const ac = this._ac(this._needles(omits, false, adp.dec));
1049
1073
  yield;
1050
1074
  const seg = this._seg(str, adp, ac);
1051
1075
  let prevEnd = -1;
@@ -1064,7 +1088,7 @@ class strim {
1064
1088
  clear(str, omits) {
1065
1089
  if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
1066
1090
  const adp = this._adapter(str);
1067
- const ac = this._ac(this._needles(omits, false));
1091
+ const ac = this._ac(this._needles(omits, false, adp.dec));
1068
1092
  const seg = this._seg(str, adp, ac);
1069
1093
  const parts = [];
1070
1094
  let pairs = 0;
@@ -1306,17 +1330,17 @@ class strim {
1306
1330
  cut(src, max, ell) { return this._cut(src, max, ell, 0); }
1307
1331
  bcut(src, max, ell) { return this._cut(src, max, ell, 1); }
1308
1332
  wcut(src, max, ell) { return this._cut(src, max, ell, 2); }
1309
- _cut(src, max, ell, mode) {
1310
- max = this._max(max);
1311
- const adp = this._adapter(src);
1312
- const ellW = ell == null ? 0 : (mode === 0 ? this.len(ell) : mode === 1 ? this.blen(ell) : this.glen(ell));
1313
- const limit = max - ellW;
1314
- let wsum = 0, cutIdx = 0, fits = true;
1333
+ //where to cut: the unit index up to which the source stays within `limit` (max minus
1334
+ //the ellipsis weight), or -1 when the whole source fits in `max` and nothing is cut.
1335
+ //Shared by _cut and Mut._cut (point 13): the walk is the same, only what happens to
1336
+ //the head differs — a slice there, a length change in place here.
1337
+ _cutAt(src, adp, max, limit, mode) {
1338
+ let wsum = 0, cutIdx = 0;
1315
1339
  if (mode === 2) {
1316
1340
  let prev = -1;
1317
1341
  for (const b of this._graph(src, adp)) {
1318
1342
  if (prev >= 0) {
1319
- if (wsum + 1 > max) { fits = false; break; }
1343
+ if (wsum + 1 > max) return cutIdx;
1320
1344
  wsum += 1;
1321
1345
  if (wsum <= limit) cutIdx = b;
1322
1346
  }
@@ -1325,12 +1349,19 @@ class strim {
1325
1349
  } else {
1326
1350
  for (const [, end, cp] of this._cpwalk(src, adp)) {
1327
1351
  const w = mode === 1 ? this._cplen(cp) : 1;
1328
- if (wsum + w > max) { fits = false; break; }
1352
+ if (wsum + w > max) return cutIdx;
1329
1353
  wsum += w;
1330
1354
  if (wsum <= limit) cutIdx = end;
1331
1355
  }
1332
1356
  }
1333
- if (fits) return src;
1357
+ return -1;
1358
+ }
1359
+ _cut(src, max, ell, mode) {
1360
+ max = this._max(max);
1361
+ const adp = this._adapter(src);
1362
+ const ellW = ell == null ? 0 : (mode === 0 ? this.len(ell) : mode === 1 ? this.blen(ell) : this.glen(ell));
1363
+ const cutIdx = this._cutAt(src, adp, max, max - ellW, mode);
1364
+ if (cutIdx < 0) return src;
1334
1365
  if (typeof src === 'string') return src.slice(0, cutIdx) + (ell == null ? '' : String(ell));
1335
1366
  if (src instanceof Uint8Array) {
1336
1367
  const head = src.subarray(0, cutIdx);
@@ -1360,7 +1391,7 @@ class strim {
1360
1391
  ifind(str, target, opts) { return this._prime(this._gfind(str, target, false, true, opts?.all === true)); }
1361
1392
  *_gfind(str, target, rev, fold, all) {
1362
1393
  const adp = this._adapter(str);
1363
- let needles = this._needles(target, fold);
1394
+ let needles = this._needles(target, fold, adp.dec);
1364
1395
  if (rev) needles = needles.map((a) => Int32Array.from(a).reverse());
1365
1396
  const ac = this._ac(needles);
1366
1397
  yield; //barrier (point 6)
@@ -1469,7 +1500,7 @@ class strim {
1469
1500
  const quoteOn = this._quoteOn(opts);
1470
1501
  const limit = opts?.limit;
1471
1502
  if (limit != null && (!Number.isInteger(limit) || limit < 1)) throw new RangeError(`str-im: limit must be an integer >= 1, got ${limit}`);
1472
- const ac = sep == null ? null : this._ac(this._needles(sep, false));
1503
+ const ac = sep == null ? null : this._ac(this._needles(sep, false, adp.dec));
1473
1504
  yield; //barrier (point 6)
1474
1505
  const size = adp.size(str);
1475
1506
  const qit = quoteOn ? this._quote(this._units(str, adp), opts)[Symbol.iterator]() : null;
@@ -1638,8 +1669,9 @@ class strim {
1638
1669
  }
1639
1670
 
1640
1671
  //trim with a customizable set (\p{White_Space} by default). Works from the edges only,
1641
- //stopping at the first non-matching character. trim — both edges, rtrim — the right one.
1672
+ //stopping at the first non-matching character. trim — both edges, ltrim / rtrim — one.
1642
1673
  trim(str, chars) { return this._trim(str, chars, true, true); }
1674
+ ltrim(str, chars) { return this._trim(str, chars, true, false); }
1643
1675
  rtrim(str, chars) { return this._trim(str, chars, false, true); }
1644
1676
  _trimtest(chars) {
1645
1677
  if (chars == null) return (cp) => this._is('WS', cp);
@@ -1866,8 +1898,364 @@ class strim {
1866
1898
  }
1867
1899
  return w;
1868
1900
  }
1901
+
1902
+
1903
+ //=========================================================================
1904
+ //=== 14. MUTABLE STRING (point 13). The only method that hands out something writable.
1905
+ //=========================================================================
1906
+
1907
+ //a string is decoded ONCE into a Uint16Array of code units — the single allocation on the
1908
+ //way in; a utf-8 buffer is edited in place, the caller's bytes, no copy at all. Anything
1909
+ //else is a TypeError (point 6). The Mut remembers `this`, so a configured engine
1910
+ //(_strim) edits with its own overrides (point 11).
1911
+ mut(src) {
1912
+ if (typeof src === 'string') {
1913
+ const b = new Uint16Array(src.length);
1914
+ for (let i = 0; i < src.length; i++) b[i] = src.charCodeAt(i);
1915
+ return new MutU16(this, b, b.length);
1916
+ }
1917
+ if (src instanceof Uint8Array) return new MutU8(this, src, src.length);
1918
+ throw new TypeError(`str-im: mut(src) — a string or a utf-8 Uint8Array, got ${src === null ? 'null' : typeof src}`);
1919
+ }
1869
1920
  }
1870
1921
 
1922
+
1923
+ //=========================================================================
1924
+ //=== MUTABLE STRING (point 13). The engine READS; these WRITE, in place.
1925
+ //=========================================================================
1926
+
1927
+ //The shared part: everything that can be said in unit indices and the engine's index streams.
1928
+ //What differs between utf-16 and utf-8 — how many units a code point takes, how to write one,
1929
+ //where the previous one starts, how to materialize — lives in the two subclasses, and each is
1930
+ //registered as its own source: an adapter's dec is fixed per constructor (point 4).
1931
+ class Mut {
1932
+ constructor(engine, buf, n) {
1933
+ this.engine = engine; //the instance that made us: every call dispatches through it (point 11)
1934
+ this.buf = buf; //the one buffer; never reallocated
1935
+ this.n = n; //live length in units; only ever goes down
1936
+ }
1937
+ get length() { return this.n; }
1938
+ get [Symbol.toStringTag]() { return 'Mut'; }
1939
+ [Symbol.toPrimitive]() { return this.toString(); }
1940
+ toJSON() { return this.toString(); }
1941
+
1942
+ //--- 0. the compaction primitive ---
1943
+
1944
+ //copy [a, b) down to the write pointer w and return the new w. copyWithin is a memmove.
1945
+ //Every editing method streams over one of the engine's index generators and keeps the
1946
+ //ranges it wants. w <= a always holds because kept ranges arrive in ascending order, so a
1947
+ //write never lands at or beyond the generator's read position — the buffer being read IS
1948
+ //the buffer being written, and this ordering is exactly what makes that safe.
1949
+ _keep(w, a, b) {
1950
+ if (w !== a) this.buf.copyWithin(w, a, b);
1951
+ return w + (b - a);
1952
+ }
1953
+ //code points as [start, end) unit ranges without allocating a pair per element (point 8):
1954
+ //the engine yields starts, the end of one is the start of the next, the last ends at n.
1955
+ _walk(fn) {
1956
+ const e = this.engine, adp = e._adapter(this);
1957
+ let prev = -1;
1958
+ for (const i of e._pointn(this, adp)) {
1959
+ if (prev >= 0) fn(prev, i, e._at(this, adp, prev));
1960
+ prev = i;
1961
+ }
1962
+ if (prev >= 0) fn(prev, this.n, e._at(this, adp, prev));
1963
+ }
1964
+
1965
+ //--- 1. slices: keep a part ---
1966
+
1967
+ //keep [start, end) in units. Out of range is a RangeError, not a clamp (point 6).
1968
+ slice(start, end = this.n) {
1969
+ if (!Number.isInteger(start) || !Number.isInteger(end)) throw new TypeError(`str-im: slice(start, end) — integers required, got ${start}, ${end}`);
1970
+ if (start < 0 || end > this.n || start > end) throw new RangeError(`str-im: slice(${start}, ${end}) out of range 0..${this.n}`);
1971
+ if (start > 0) this.buf.copyWithin(0, start, end);
1972
+ this.n = end - start;
1973
+ return this;
1974
+ }
1975
+ //keep only the piece after / before the first / last `target` — the substr family, in place.
1976
+ //A string target is searched through the engine (find / lfind), so it works on utf-8 too;
1977
+ //a number is a position. Not found — NotFound, exactly as in the engine (point 6).
1978
+ substr(target, offset = Infinity) { return this._sub(target, offset, false, false); }
1979
+ lsubstr(target, offset = Infinity) { return this._sub(target, offset, true, false); }
1980
+ substrb(target, offset = Infinity) { return this._sub(target, offset, false, true); }
1981
+ lsubstrb(target, offset = Infinity) { return this._sub(target, offset, true, true); }
1982
+ _sub(target, offset, last, back) {
1983
+ const e = this.engine;
1984
+ offset = e._offset(offset);
1985
+ let i, tlen = 0;
1986
+ if (typeof target === 'number') {
1987
+ if (!Number.isInteger(target)) throw new TypeError(`str-im: a numeric target must be an integer, got ${target}`);
1988
+ if (target < 0 || target > this.n) throw new RangeError(`str-im: position ${target} out of range 0..${this.n}`);
1989
+ i = target;
1990
+ } else if (typeof target !== 'string') {
1991
+ throw new TypeError(`str-im: target must be a string or a position, got ${typeof target}`);
1992
+ } else if (target === '') {
1993
+ i = last ? this.n : 0; //indexOf('') is 0, lastIndexOf('') is the length
1994
+ } else {
1995
+ const r = (last ? e.lfind(this, target) : e.find(this, target)).next();
1996
+ if (r.done) throw new NotFound(JSON.stringify(target));
1997
+ i = r.value;
1998
+ tlen = e._needles(target, false, e._adapter(this).dec)[0].length;
1999
+ }
2000
+ if (back) return this.slice(offset === Infinity ? 0 : Math.max(0, i - offset), i);
2001
+ const start = i + tlen;
2002
+ return this.slice(start, offset === Infinity ? this.n : Math.min(this.n, start + offset));
2003
+ }
2004
+
2005
+ //--- 2. dropping ---
2006
+
2007
+ //remove every occurrence of the needles (leftmost-longest, non-overlapping) — clear, in place.
2008
+ //splitn yields exactly the pieces BETWEEN matches, validated at the call.
2009
+ drop(needles) {
2010
+ if (needles == null) throw new TypeError('str-im: drop(needles) — needles are required');
2011
+ const it = this.engine.splitn(this, needles);
2012
+ let w = 0;
2013
+ for (let a = it.next(); !a.done; a = it.next()) w = this._keep(w, a.value, it.next().value);
2014
+ this.n = w;
2015
+ return this;
2016
+ }
2017
+ //collapse runs to `keep` (default 1); chars — only these characters. flat, in place.
2018
+ flat(chars, keep = 1) {
2019
+ const e = this.engine;
2020
+ keep = e._max(keep);
2021
+ let set = null;
2022
+ if (chars != null) { set = new Set(); for (const ch of String(chars)) set.add(ch.codePointAt(0)); }
2023
+ let w = 0, prev = -1, run = 0;
2024
+ this._walk((a, b, cp) => {
2025
+ run = cp === prev ? run + 1 : 1;
2026
+ prev = cp;
2027
+ if (run <= (set === null || set.has(cp) ? keep : Infinity)) w = this._keep(w, a, b);
2028
+ });
2029
+ this.n = w;
2030
+ return this;
2031
+ }
2032
+ //drop the escape character and keep what follows it literally — unesc, in place.
2033
+ //A trailing lone escape stays, as in the engine.
2034
+ unesc(opts) {
2035
+ const ec = (opts?.esc ?? '\\').codePointAt(0);
2036
+ let w = 0, lit = false;
2037
+ this._walk((a, b, cp) => {
2038
+ if (lit) { lit = false; w = this._keep(w, a, b); }
2039
+ else if (cp === ec && b < this.n) lit = true;
2040
+ else w = this._keep(w, a, b);
2041
+ });
2042
+ this.n = w;
2043
+ return this;
2044
+ }
2045
+
2046
+ //--- 3. edges ---
2047
+
2048
+ //trim a set (\p{White_Space} by default) from the edges — trim / ltrim / rtrim, in place.
2049
+ //The left edge walks forward on the engine's index stream; the right edge walks back one
2050
+ //code point at a time (_back), and a stray unit that is not a whole character stops it.
2051
+ trim(chars) { return this._trim(chars, true, true); }
2052
+ ltrim(chars) { return this._trim(chars, true, false); }
2053
+ rtrim(chars) { return this._trim(chars, false, true); }
2054
+ _trim(chars, left, right) {
2055
+ const e = this.engine, adp = e._adapter(this), test = e._trimtest(chars);
2056
+ let a = 0, b = this.n;
2057
+ if (left) {
2058
+ a = b; //until a character says otherwise, everything is trimmable
2059
+ for (const i of e._pointn(this, adp)) if (!test(e._at(this, adp, i))) { a = i; break; }
2060
+ }
2061
+ if (right) while (b > a) {
2062
+ const s = this._back(b, a), cp = e._at(this, adp, s);
2063
+ if (s + this._units(cp) !== b || !test(cp)) break;
2064
+ b = s;
2065
+ }
2066
+ if (a === 0 && b === this.n) return this;
2067
+ if (a > 0) this.buf.copyWithin(0, a, b);
2068
+ this.n = b - a;
2069
+ return this;
2070
+ }
2071
+ //truncate to `max` code points / utf-8 bytes / grapheme clusters — cut / bcut / wcut, in
2072
+ //place. The walk is the engine's own (_cutAt). An ellipsis is written over the cut region
2073
+ //and must fit in it: the buffer never grows, and the check comes before the write.
2074
+ cut(max, ell) { return this._cut(max, ell, 0); }
2075
+ bcut(max, ell) { return this._cut(max, ell, 1); }
2076
+ wcut(max, ell) { return this._cut(max, ell, 2); }
2077
+ _cut(max, ell, mode) {
2078
+ const e = this.engine, adp = e._adapter(this);
2079
+ max = e._max(max);
2080
+ const ellW = ell == null ? 0 : (mode === 0 ? e.len(ell) : mode === 1 ? e.blen(ell) : e.glen(ell));
2081
+ const cutIdx = e._cutAt(this, adp, max, max - ellW, mode);
2082
+ if (cutIdx < 0) return this; //fits — untouched
2083
+ if (ell == null) { this.n = cutIdx; return this; }
2084
+ const tail = this._encode(ell);
2085
+ if (cutIdx + tail.length > this.n) throw new RangeError(`str-im: the ellipsis needs ${cutIdx + tail.length} units, the buffer holds ${this.n} — a Mut never grows`);
2086
+ this.buf.set(tail, cutIdx);
2087
+ this.n = cutIdx + tail.length;
2088
+ return this;
2089
+ }
2090
+ //strip the indent common to all non-empty lines — dedent, in place. Two passes: find the
2091
+ //prefix (spaces and tabs are single units in both encodings, so this is a plain unit scan),
2092
+ //then compact. The prefix lives in the first non-empty line, which compaction overwrites,
2093
+ //so it is copied out first — the one small allocation here besides an ellipsis.
2094
+ dedent() {
2095
+ const buf = this.buf, n = this.n;
2096
+ let pStart = -1, pLen = 0;
2097
+ for (let ls = 0; ls < n;) {
2098
+ let k = ls;
2099
+ while (k < n && (buf[k] === 32 || buf[k] === 9)) k++;
2100
+ let le = k;
2101
+ while (le < n && buf[le] !== 10) le++;
2102
+ if (k < le) { //a line with something after its indent constrains the prefix
2103
+ if (pStart < 0) { pStart = ls; pLen = k - ls; }
2104
+ else { let j = 0; while (j < pLen && ls + j < k && buf[pStart + j] === buf[ls + j]) j++; pLen = j; }
2105
+ if (pLen === 0) return this;
2106
+ }
2107
+ ls = le + 1;
2108
+ }
2109
+ if (pStart < 0) return this;
2110
+ const pre = buf.slice(pStart, pStart + pLen);
2111
+ let w = 0;
2112
+ for (let ls = 0; ls < n;) {
2113
+ let le = ls;
2114
+ while (le < n && buf[le] !== 10) le++;
2115
+ let j = 0;
2116
+ while (j < pLen && ls + j < le && buf[ls + j] === pre[j]) j++;
2117
+ w = this._keep(w, j === pLen ? ls + pLen : ls, le < n ? le + 1 : le);
2118
+ ls = le + 1;
2119
+ }
2120
+ this.n = w;
2121
+ return this;
2122
+ }
2123
+
2124
+ //--- 4. same-length rewrites ---
2125
+
2126
+ //wrap by display width, in place: the space before a word that no longer fits becomes a
2127
+ //newline. Same words, same length, same rule as the engine's wrap — the engine yields
2128
+ //lines, this rewrites separators. Paragraphs (\n) are kept; a long word overflows.
2129
+ //Space and newline are one unit in utf-16 and utf-8 alike, so the scan is on raw units.
2130
+ wrap(width) {
2131
+ if (!Number.isInteger(width) || width < 1) throw new RangeError(`str-im: width must be an integer >= 1, got ${width}`);
2132
+ const buf = this.buf, n = this.n;
2133
+ let lineW = 0, first = true;
2134
+ for (let ws = 0; ws <= n;) {
2135
+ let we = ws;
2136
+ while (we < n && buf[we] !== 32 && buf[we] !== 10) we++;
2137
+ const ww = this._vwidth(ws, we);
2138
+ if (first) { lineW = ww; first = false; }
2139
+ else if (lineW + 1 + ww <= width) lineW += 1 + ww;
2140
+ else { buf[ws - 1] = 10; lineW = ww; }
2141
+ if (we >= n) break;
2142
+ if (buf[we] === 10) first = true;
2143
+ ws = we + 1;
2144
+ }
2145
+ return this;
2146
+ }
2147
+ //display width of [a, b) — the engine's _vwidth over a range, ANSI-CSI excluded
2148
+ _vwidth(a, b) {
2149
+ const e = this.engine, adp = e._adapter(this);
2150
+ let w = 0;
2151
+ for (let i = a; i < b;) {
2152
+ const cp = e._at(this, adp, i);
2153
+ i = this._next(i);
2154
+ if (cp === 0x1b) {
2155
+ if (i < b) {
2156
+ const c1 = e._at(this, adp, i);
2157
+ i = this._next(i);
2158
+ if (c1 === 0x5b) while (i < b) { const c = e._at(this, adp, i); i = this._next(i); if (c >= 0x40 && c <= 0x7e) break; }
2159
+ }
2160
+ continue;
2161
+ }
2162
+ w += e._width(cp);
2163
+ }
2164
+ return w;
2165
+ }
2166
+ //simple case folding in place, by the engine's table. Pass one proves every folded code
2167
+ //point fits the slot of the original (utf-16 never changes width; in utf-8 a few do — Ⱥ
2168
+ //U+023A is 2 bytes, ⱥ U+2C65 is 3) — a RangeError before the first write, never a
2169
+ //half-folded buffer. Pass two writes, compacting where a fold got narrower.
2170
+ fold() {
2171
+ const e = this.engine, adp = e._adapter(this);
2172
+ for (let i = 0; i < this.n;) {
2173
+ const cp = e._at(this, adp, i), next = this._next(i), f = e._fold(cp);
2174
+ if (f !== cp && this._units(f) > next - i) throw new RangeError(`str-im: fold — U+${cp.toString(16).toUpperCase()} folds to U+${f.toString(16).toUpperCase()}, which is wider here; a Mut never grows`);
2175
+ i = next;
2176
+ }
2177
+ let w = 0;
2178
+ this._walk((a, b, cp) => {
2179
+ const f = e._fold(cp);
2180
+ w = f === cp ? this._keep(w, a, b) : w + this._put(w, f);
2181
+ });
2182
+ this.n = w;
2183
+ return this;
2184
+ }
2185
+ }
2186
+
2187
+ //utf-16 code units over a Uint16Array. Materialization is String.fromCharCode in chunks:
2188
+ //one call, one string for anything up to 8 K units; a TextDecoder would be as cheap but
2189
+ //replaces a lone surrogate with U+FFFD, and the user's data is not ours to repair.
2190
+ class MutU16 extends Mut {
2191
+ _units(cp) { return cp >= 0x10000 ? 2 : 1; }
2192
+ _put(i, cp) {
2193
+ if (cp < 0x10000) { this.buf[i] = cp; return 1; }
2194
+ cp -= 0x10000;
2195
+ this.buf[i] = 0xd800 + (cp >> 10);
2196
+ this.buf[i + 1] = 0xdc00 + (cp & 0x3ff);
2197
+ return 2;
2198
+ }
2199
+ //start of the code point that ends at b (b > a): one unit, or two for a surrogate pair
2200
+ _back(b, a) {
2201
+ const s = b - 1, u = this.buf[s];
2202
+ if (u >= 0xdc00 && u <= 0xdfff && s > a) { const h = this.buf[s - 1]; if (h >= 0xd800 && h <= 0xdbff) return s - 1; }
2203
+ return s;
2204
+ }
2205
+ //start of the code point after the one at i
2206
+ _next(i) {
2207
+ const u = this.buf[i];
2208
+ if (u >= 0xd800 && u <= 0xdbff && i + 1 < this.n) { const l = this.buf[i + 1]; if (l >= 0xdc00 && l <= 0xdfff) return i + 2; }
2209
+ return i + 1;
2210
+ }
2211
+ _encode(ell) {
2212
+ const s = ell instanceof Uint8Array ? U8DEC.decode(ell) : String(ell);
2213
+ const out = new Uint16Array(s.length);
2214
+ for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
2215
+ return out;
2216
+ }
2217
+ toString() {
2218
+ const b = this.buf, n = this.n;
2219
+ if (n <= 8192) return String.fromCharCode.apply(null, n === b.length ? b : b.subarray(0, n));
2220
+ const parts = [];
2221
+ for (let i = 0; i < n; i += 8192) parts.push(String.fromCharCode.apply(null, b.subarray(i, Math.min(n, i + 8192))));
2222
+ return parts.join('');
2223
+ }
2224
+ value() { return this.toString(); }
2225
+ }
2226
+
2227
+ //utf-8 bytes over the caller's own Uint8Array. value() is a view of the live prefix — no
2228
+ //copy; toString() decodes it once.
2229
+ class MutU8 extends Mut {
2230
+ _units(cp) { return this.engine._cplen(cp); }
2231
+ _put(i, cp) {
2232
+ const b = this.buf;
2233
+ if (cp < 0x80) { b[i] = cp; return 1; }
2234
+ if (cp < 0x800) { b[i] = 0xc0 | (cp >> 6); b[i + 1] = 0x80 | (cp & 0x3f); return 2; }
2235
+ if (cp < 0x10000) { b[i] = 0xe0 | (cp >> 12); b[i + 1] = 0x80 | ((cp >> 6) & 0x3f); b[i + 2] = 0x80 | (cp & 0x3f); return 3; }
2236
+ b[i] = 0xf0 | (cp >> 18); b[i + 1] = 0x80 | ((cp >> 12) & 0x3f); b[i + 2] = 0x80 | ((cp >> 6) & 0x3f); b[i + 3] = 0x80 | (cp & 0x3f);
2237
+ return 4;
2238
+ }
2239
+ //start of the character that ends at b: step back over continuation bytes to the lead
2240
+ _back(b, a) {
2241
+ let s = b - 1;
2242
+ while (s > a && (this.buf[s] & 0xc0) === 0x80) s--;
2243
+ return s;
2244
+ }
2245
+ _next(i) {
2246
+ i++;
2247
+ while (i < this.n && (this.buf[i] & 0xc0) === 0x80) i++;
2248
+ return i;
2249
+ }
2250
+ _encode(ell) { return ell instanceof Uint8Array ? ell : U8ENC.encode(String(ell)); }
2251
+ toString() { return U8DEC.decode(this.buf.subarray(0, this.n)); }
2252
+ value() { return this.buf.subarray(0, this.n); }
2253
+ }
2254
+
2255
+ //both are sources (point 4): size is the live length, units are the buffer's own
2256
+ strim.use(MutU16, { size: (m) => m.n, at: (m, i) => m.buf[i], dec: 0 });
2257
+ strim.use(MutU8, { size: (m) => m.n, at: (m, i) => m.buf[i], dec: 1 });
2258
+
1871
2259
  //a built-in set of cross-script homoglyphs for skel: Cyrillic and Greek characters that
1872
2260
  //look identical to Latin ones -> Latin. There is no full TR39 table in the package;
1873
2261
  //this is a practical minimum for catching fake domains/handles. Extended via confuse().
@@ -1917,4 +2305,4 @@ strim.alphabet('semivowel', 'yYйЙыЫ', '');
1917
2305
  //the default export is a ready instance, the class is available as a named export for str-ez.
1918
2306
  const SINGLETON = new strim();
1919
2307
  export default SINGLETON;
1920
- export { strim };
2308
+ export { strim, Mut };
package/types/str-im.d.ts CHANGED
@@ -12,8 +12,8 @@ export class NotFound extends Error {
12
12
  }
13
13
 
14
14
  /** A data source the engine can read. Out of the box: string (utf-16), Uint8Array
15
- * (utf-8), Array<number> (code points). Register more with {@link strim.use}. */
16
- export type Source = string | Uint8Array | readonly number[];
15
+ * (utf-8), Array<number> (code points), and a {@link Mut}. Register more with {@link strim.use}. */
16
+ export type Source = string | Uint8Array | readonly number[] | Mut;
17
17
 
18
18
  /** A search/slice target: a string to locate, or a number treated as a position. */
19
19
  export type Target = string | number;
@@ -179,6 +179,7 @@ export declare class strim {
179
179
  esc(str: string, chars?: string, opts?: EscOptions): string;
180
180
  unesc(str: string, opts?: EscOptions): string;
181
181
  trim(str: string, chars?: string): string;
182
+ ltrim(str: string, chars?: string): string;
182
183
  rtrim(str: string, chars?: string): string;
183
184
 
184
185
  // -- 11. unicode analysis --
@@ -199,6 +200,13 @@ export declare class strim {
199
200
  style(str: string): NamingStyle;
200
201
  wrap(str: string, width: number, opts?: WrapOptions): IterableIterator<string>;
201
202
 
203
+ // -- 14. mutable string --
204
+ /** A mutable view: a string is decoded once into a Uint16Array, a utf-8 buffer is edited
205
+ * in place. Edits only ever shrink it; see {@link Mut}. */
206
+ mut(src: string): Mut<string>;
207
+ mut(src: Uint8Array): Mut<Uint8Array>;
208
+ mut(src: string | Uint8Array): Mut;
209
+
202
210
  // -- process-wide registration --
203
211
  /** Register an adapter for a custom source constructor. Returns the constructor. */
204
212
  static use<C extends new (...args: any[]) => any>(ctor: C, adapter: Adapter<InstanceType<C>>): C;
@@ -210,6 +218,64 @@ export declare class strim {
210
218
  static confuse(map: Record<string, string> | Map<string, string>): typeof strim;
211
219
  }
212
220
 
221
+ /**
222
+ * A mutable string over one buffer: utf-16 code units for a string source, the caller's own
223
+ * bytes for a `Uint8Array` source. Every edit works in place and only ever shrinks the buffer;
224
+ * an edit that would need it to grow (an ellipsis that does not fit, a case fold that widens
225
+ * in utf-8) throws `RangeError` before the first write. Every method returns `this`. The
226
+ * object is a registered {@link Source}, so every reading method of the engine accepts it.
227
+ * Created by {@link strim.mut}; exported for `instanceof`.
228
+ */
229
+ export declare class Mut<T extends string | Uint8Array = string | Uint8Array> {
230
+ private constructor();
231
+ /** Live length in units: utf-16 code units or utf-8 bytes. */
232
+ readonly length: number;
233
+
234
+ // -- slices: keep a part --
235
+ /** Keep `[start, end)` in units. Out of range is a `RangeError`, not a clamp. */
236
+ slice(start: number, end?: number): this;
237
+ /** Keep the piece after the first `target`, at most `offset` units. Absent: `NotFound`. */
238
+ substr(target: Target, offset?: number): this;
239
+ lsubstr(target: Target, offset?: number): this;
240
+ substrb(target: Target, offset?: number): this;
241
+ lsubstrb(target: Target, offset?: number): this;
242
+
243
+ // -- dropping --
244
+ /** Remove every occurrence of the needles (the in-place `clear`). */
245
+ drop(needles: Target | Iterable<Target>): this;
246
+ /** Collapse runs to `keep` (default 1); `chars` restricts to a set (the in-place `flat`). */
247
+ flat(chars?: string | null, keep?: number): this;
248
+ /** Drop the escape character, keep what follows it (the in-place `unesc`). */
249
+ unesc(opts?: EscOptions): this;
250
+
251
+ // -- edges --
252
+ trim(chars?: string): this;
253
+ ltrim(chars?: string): this;
254
+ rtrim(chars?: string): this;
255
+ /** Truncate to `max` code points; an ellipsis must fit in the cut region. */
256
+ cut(max: number, ell?: string | Uint8Array): this;
257
+ /** Truncate to `max` utf-8 bytes. */
258
+ bcut(max: number, ell?: string | Uint8Array): this;
259
+ /** Truncate to `max` grapheme clusters. */
260
+ wcut(max: number, ell?: string | Uint8Array): this;
261
+ dedent(): this;
262
+
263
+ // -- same-length rewrites --
264
+ /** Wrap by display width: the space before a word that no longer fits becomes `
265
+ `. */
266
+ wrap(width: number): this;
267
+ /** Simple case folding by the engine's table. */
268
+ fold(): this;
269
+
270
+ // -- materialization --
271
+ /** The current text as a string (one allocation). */
272
+ toString(): string;
273
+ /** The current value in the source's own type: a string, or a zero-copy view of the buffer. */
274
+ value(): T;
275
+ toJSON(): string;
276
+ [Symbol.toPrimitive](): string;
277
+ }
278
+
213
279
  /**
214
280
  * Configuration factory. With no argument returns the base singleton (free). With an
215
281
  * `overrides` object it returns a cached instance whose listed methods are replaced;