@slnknrr/str-im 1.0.0 → 1.2.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 +21 -75
- package/README.md +94 -7
- package/package.json +11 -8
- package/src/str-im.js +452 -38
- package/types/str-im.d.ts +68 -2
package/LICENSE.md
CHANGED
|
@@ -1,75 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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
|
@@ -1,7 +1,17 @@
|
|
|
1
|
-
# str-im
|
|
1
|
+
# @slnknrr/str-im
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@slnknrr/str-im)
|
|
4
|
+
[](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/actions/workflows/test.yml?query=branch%3Astr-im)
|
|
5
|
+
[](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/blob/str-im@1.2.0/LICENSE.md)
|
|
6
|
+
[](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/stargazers)
|
|
7
|
+
[](https://github.com/slnknrr-dev)
|
|
8
|
+
[](https://ko-fi.com/slnknrr)
|
|
9
|
+
[](https://paypal.me/slnknrrdev)
|
|
2
10
|
|
|
3
11
|
**A zero-allocation string engine. Numbers in the core, strings only at the boundary.**
|
|
4
12
|
|
|
13
|
+
> 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.
|
|
14
|
+
|
|
5
15
|
`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
16
|
|
|
7
17
|
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 +35,8 @@ s.near('kitten', 'sitting', 2); // Infinity — "not within 2 edits", answered
|
|
|
25
35
|
- **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
36
|
- **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
37
|
- **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.** ~
|
|
38
|
+
- **Pure ESM, dependency-free, sync.** ~2300 lines, one file, immutable tables. Node ≥ 20.
|
|
39
|
+
- **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
40
|
|
|
30
41
|
## What it is NOT
|
|
31
42
|
|
|
@@ -45,7 +56,7 @@ npm install @slnknrr/str-im
|
|
|
45
56
|
|
|
46
57
|
```js
|
|
47
58
|
import s from '@slnknrr/str-im'; // ready-to-use singleton — no `new`
|
|
48
|
-
import { strim, _strim, NotFound, UNICODE } from '@slnknrr/str-im';
|
|
59
|
+
import { strim, _strim, Mut, NotFound, UNICODE } from '@slnknrr/str-im';
|
|
49
60
|
```
|
|
50
61
|
|
|
51
62
|
Requirements: **Node ≥ 20**, ESM only (`"type": "module"` or `import`). Tables track **Unicode `UNICODE`** (currently 17.0).
|
|
@@ -88,6 +99,8 @@ Every reading method resolves an adapter **once** per call, then stays in a tigh
|
|
|
88
99
|
| `Uint8Array` / `Buffer` | utf-8 bytes | `s.len(Buffer.from('café'))` |
|
|
89
100
|
| `Array<number>` | ready code points | `s.len([99, 97, 102, 233])` |
|
|
90
101
|
|
|
102
|
+
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.
|
|
103
|
+
|
|
91
104
|
Register your own once, process-wide, and the entire method family works with it:
|
|
92
105
|
|
|
93
106
|
```js
|
|
@@ -123,7 +136,7 @@ Why these win, structurally: the early-exit iterator **stops at 8** instead of s
|
|
|
123
136
|
|
|
124
137
|
## API
|
|
125
138
|
|
|
126
|
-
|
|
139
|
+
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
140
|
|
|
128
141
|
### 1 · Slices relative to a target — `l` = last, `b` = back
|
|
129
142
|
| Method | Returns |
|
|
@@ -202,7 +215,7 @@ All take `(str, max=∞)`.
|
|
|
202
215
|
| `find(str, target, {all}?)` | lazy match indices; `target` = string or many (one Aho-Corasick pass) |
|
|
203
216
|
| `lfind` / `ifind` | right-to-left / case-insensitive |
|
|
204
217
|
| `near(a, b, max=∞, {damerau}?)` | edit distance, or `Infinity` if it exceeds `max` |
|
|
205
|
-
| `com(a, b)` / `comb(a, b)` | length of common prefix / suffix (`b` = one string or many) |
|
|
218
|
+
| `com(a, b)` / `comb(a, b)` | length of common prefix / suffix in code points (`b` = one string or many) |
|
|
206
219
|
|
|
207
220
|
### 10 · Segmentation & parsing
|
|
208
221
|
| Method | Returns |
|
|
@@ -213,7 +226,7 @@ All take `(str, max=∞)`.
|
|
|
213
226
|
| `ind(str)` | `{ char, size, min, mixed }` indentation analysis |
|
|
214
227
|
| `dedent(str)` | strip the common indent |
|
|
215
228
|
| `esc(str, chars?, opts?)` / `unesc` | escape / unescape a character set |
|
|
216
|
-
| `trim(str, chars?)` / `rtrim` | trim a custom set (default `\p{White_Space}`) |
|
|
229
|
+
| `trim(str, chars?)` / `ltrim` / `rtrim` | trim a custom set (default `\p{White_Space}`) — both edges / left / right |
|
|
217
230
|
|
|
218
231
|
`opts`: `{ quote, quotes, esc, nest, limit, pairs }` — quote/escape-aware splitting and matching (CSV, shell).
|
|
219
232
|
|
|
@@ -239,6 +252,41 @@ All take `(str, max=∞)`.
|
|
|
239
252
|
| `style(str)` | naming style: `camel`/`pascal`/`snake`/`screaming`/`kebab`/`dot`/`mixed`/… |
|
|
240
253
|
| `wrap(str, width, opts?)` | width-aware line wrap (display columns, ANSI-safe) |
|
|
241
254
|
|
|
255
|
+
### 14 · Mutable string — `mut`
|
|
256
|
+
| Method | Does |
|
|
257
|
+
|---|---|
|
|
258
|
+
| `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) |
|
|
259
|
+
|
|
260
|
+
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.
|
|
261
|
+
|
|
262
|
+
| `Mut` method | In-place twin of |
|
|
263
|
+
|---|---|
|
|
264
|
+
| `slice(start, end?)` | `str.slice` — keep `[start, end)` in units; out of range throws |
|
|
265
|
+
| `substr` / `lsubstr` / `substrb` / `lsubstrb` `(target, offset?)` | §1 — keep only that piece; `NotFound` as in the engine |
|
|
266
|
+
| `drop(needles)` | `clear` |
|
|
267
|
+
| `flat(chars?, keep?)` | `flat` |
|
|
268
|
+
| `unesc(opts?)` | `unesc` |
|
|
269
|
+
| `trim` / `ltrim` / `rtrim` `(chars?)` | §10 |
|
|
270
|
+
| `cut` / `bcut` / `wcut` `(max, ell?)` | §8 — an ellipsis must fit in the cut region |
|
|
271
|
+
| `dedent()` | `dedent` |
|
|
272
|
+
| `wrap(width)` | `wrap` — the space before a word that no longer fits becomes `
|
|
273
|
+
`; same length |
|
|
274
|
+
| `fold()` | simple case folding by table; in utf-8 a fold that widens (`Ⱥ` → `ⱥ`, 2 → 3 bytes) is refused up front |
|
|
275
|
+
| `toString()` / `value()` | one string; or the source's own type — for a buffer, a zero-copy `subarray` of the live prefix |
|
|
276
|
+
|
|
277
|
+
```js
|
|
278
|
+
s.mut(' Héllo,, wörld!! ').trim().flat(',! ').drop('l').fold().toString(); // 'héo, wörd!'
|
|
279
|
+
|
|
280
|
+
const buf = Buffer.from(' héllo ');
|
|
281
|
+
const m = s.mut(buf).trim(); // edits buf itself
|
|
282
|
+
m.value(); // Uint8Array(6) — a view into buf, no copy
|
|
283
|
+
m.value().buffer === buf.buffer; // true
|
|
284
|
+
|
|
285
|
+
s.mut('世').bcut(2, 'ab'); // RangeError before any write: 'ab' does not fit in 1 unit
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
What is deliberately **not** on a `Mut`: `esc`, `skel`, `deburr` and anything else that can grow. The strategy is the guarantee.
|
|
289
|
+
|
|
242
290
|
### Statics & factory
|
|
243
291
|
| Symbol | Purpose |
|
|
244
292
|
|---|---|
|
|
@@ -248,6 +296,7 @@ All take `(str, max=∞)`.
|
|
|
248
296
|
| `_strim(overrides?)` | build a configured instance (see below) |
|
|
249
297
|
| `UNICODE` | Unicode version of the tables |
|
|
250
298
|
| `NotFound` | error class for absent targets |
|
|
299
|
+
| `Mut` | the mutable-string class, for `instanceof` — instances come from `mut()` |
|
|
251
300
|
|
|
252
301
|
---
|
|
253
302
|
|
|
@@ -294,6 +343,44 @@ Every internal call dispatches through `this`, so replacing one method replaces
|
|
|
294
343
|
|
|
295
344
|
---
|
|
296
345
|
|
|
346
|
+
## Links
|
|
347
|
+
|
|
348
|
+
- Source: [github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/tree/str-im](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/tree/str-im)
|
|
349
|
+
- npm: [https://www.npmjs.com/package/@slnknrr/str-im](https://www.npmjs.com/package/@slnknrr/str-im)
|
|
350
|
+
- Friendly wrapper — familiar names, booleans and arrays over the same engine: [@slnknrr/str-ez](https://www.npmjs.com/package/@slnknrr/str-ez)
|
|
351
|
+
|
|
352
|
+
## Repository layout
|
|
353
|
+
|
|
354
|
+
Every `@slnknrr` library family lives in one GitHub repository, and **every npm package is a branch** of it — with its own README, tests and releases. A release is a version bump: when a push to the package's branch carries a `package.json` version that is not on npm yet, CI tests it, publishes it to npm and tags it `<package>@<version>` (`v<version>` on a `main` branch).
|
|
355
|
+
|
|
356
|
+
This package is the `str-im` branch of [`slnknrr-dev/str-lib-in-javascript-for-pm_npm`](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm); its releases are tagged `str-im@<version>`.
|
|
357
|
+
|
|
358
|
+
| Branch | npm package | Role |
|
|
359
|
+
|---|---|---|
|
|
360
|
+
| [`str-im`](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/tree/str-im) | [`@slnknrr/str-im`](https://www.npmjs.com/package/@slnknrr/str-im) | **this package** — the engine |
|
|
361
|
+
| [`str-ez`](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/tree/str-ez) | [`@slnknrr/str-ez`](https://www.npmjs.com/package/@slnknrr/str-ez) | the friendly wrapper over str-im |
|
|
362
|
+
|
|
363
|
+
All families:
|
|
364
|
+
|
|
365
|
+
| Family | Repository | Branches → packages |
|
|
366
|
+
|---|---|---|
|
|
367
|
+
| arrays | [`arr-lib-in-javascript-for-pm_npm`](https://github.com/slnknrr-dev/arr-lib-in-javascript-for-pm_npm) | [`arr-im`](https://github.com/slnknrr-dev/arr-lib-in-javascript-for-pm_npm/tree/arr-im) → [`@slnknrr/arr-im`](https://www.npmjs.com/package/@slnknrr/arr-im) |
|
|
368
|
+
| bytes | [`buf-lib-in-javascript-for-pm_npm`](https://github.com/slnknrr-dev/buf-lib-in-javascript-for-pm_npm) | [`buf-im`](https://github.com/slnknrr-dev/buf-lib-in-javascript-for-pm_npm/tree/buf-im) → [`@slnknrr/buf-im`](https://www.npmjs.com/package/@slnknrr/buf-im) |
|
|
369
|
+
| identifiers | [`id-lib-in-javascript-for-pm_npm`](https://github.com/slnknrr-dev/id-lib-in-javascript-for-pm_npm) | [`main`](https://github.com/slnknrr-dev/id-lib-in-javascript-for-pm_npm/tree/main) → [`@slnknrr/id`](https://www.npmjs.com/package/@slnknrr/id) |
|
|
370
|
+
| numbers as text | [`num-lib-in-javascript-for-pm_npm`](https://github.com/slnknrr-dev/num-lib-in-javascript-for-pm_npm) | [`num-im`](https://github.com/slnknrr-dev/num-lib-in-javascript-for-pm_npm/tree/num-im) → [`@slnknrr/num-im`](https://www.npmjs.com/package/@slnknrr/num-im) · [`num-ez`](https://github.com/slnknrr-dev/num-lib-in-javascript-for-pm_npm/tree/num-ez) → [`@slnknrr/num-ez`](https://www.npmjs.com/package/@slnknrr/num-ez) |
|
|
371
|
+
| random data | [`rnd-lib-in-javascript-for-pm_npm`](https://github.com/slnknrr-dev/rnd-lib-in-javascript-for-pm_npm) | [`rnd-im`](https://github.com/slnknrr-dev/rnd-lib-in-javascript-for-pm_npm/tree/rnd-im) → [`@slnknrr/rnd-im`](https://www.npmjs.com/package/@slnknrr/rnd-im) · [`rnd-ez`](https://github.com/slnknrr-dev/rnd-lib-in-javascript-for-pm_npm/tree/rnd-ez) → [`@slnknrr/rnd-ez`](https://www.npmjs.com/package/@slnknrr/rnd-ez) |
|
|
372
|
+
| strings | [`str-lib-in-javascript-for-pm_npm`](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm) | [`str-im`](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/tree/str-im) → [`@slnknrr/str-im`](https://www.npmjs.com/package/@slnknrr/str-im) · [`str-ez`](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/tree/str-ez) → [`@slnknrr/str-ez`](https://www.npmjs.com/package/@slnknrr/str-ez) |
|
|
373
|
+
| types | [`type-lib-in-javascript-for-pm_npm`](https://github.com/slnknrr-dev/type-lib-in-javascript-for-pm_npm) | [`type-im`](https://github.com/slnknrr-dev/type-lib-in-javascript-for-pm_npm/tree/type-im) → [`@slnknrr/type-im`](https://www.npmjs.com/package/@slnknrr/type-im) · [`type-ez`](https://github.com/slnknrr-dev/type-lib-in-javascript-for-pm_npm/tree/type-ez) → [`@slnknrr/type-ez`](https://www.npmjs.com/package/@slnknrr/type-ez) |
|
|
374
|
+
|
|
375
|
+
## Author
|
|
376
|
+
|
|
377
|
+
Yury Slinkin (Юрий Слинкин)
|
|
378
|
+
|
|
379
|
+
- Email: [slnknrr.dev@gmail.com](mailto:slnknrr.dev@gmail.com)
|
|
380
|
+
- GitHub: [github.com/slnknrr-dev](https://github.com/slnknrr-dev)
|
|
381
|
+
- Ko-fi: [ko-fi.com/slnknrr](https://ko-fi.com/slnknrr)
|
|
382
|
+
- PayPal: [paypal.me/slnknrrdev](https://paypal.me/slnknrrdev)
|
|
383
|
+
|
|
297
384
|
## License
|
|
298
385
|
|
|
299
|
-
|
|
386
|
+
MIT © 2026 Yury Slinkin <slnknrr.dev@gmail.com>. See [LICENSE.md](https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/blob/str-im@1.2.0/LICENSE.md).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@slnknrr/str-im",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.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,17 +19,20 @@
|
|
|
19
19
|
"entropy",
|
|
20
20
|
"aho-corasick"
|
|
21
21
|
],
|
|
22
|
-
"license": "
|
|
23
|
-
"author": "Yury Slinkin <slnknrr.dev@gmail.com>",
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"author": "Yury Slinkin <slnknrr.dev@gmail.com> (https://github.com/slnknrr-dev)",
|
|
24
24
|
"repository": {
|
|
25
25
|
"type": "git",
|
|
26
|
-
"url": "git+https://
|
|
26
|
+
"url": "git+https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm.git"
|
|
27
27
|
},
|
|
28
28
|
"bugs": {
|
|
29
|
-
"url": "https://
|
|
29
|
+
"url": "https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/issues"
|
|
30
|
+
},
|
|
31
|
+
"homepage": "https://github.com/slnknrr-dev/str-lib-in-javascript-for-pm_npm/tree/str-im#readme",
|
|
32
|
+
"funding": {
|
|
33
|
+
"type": "ko-fi",
|
|
34
|
+
"url": "https://ko-fi.com/slnknrr"
|
|
30
35
|
},
|
|
31
|
-
"homepage": "https://codeberg.org/slnknrr/strim_lib.js-for-pm_npm",
|
|
32
|
-
"funding": "https://slnknrr.codeberg.page/funding#?npmjs=@slnknrr/str-im",
|
|
33
36
|
"type": "module",
|
|
34
37
|
"exports": {
|
|
35
38
|
".": {
|
|
@@ -55,7 +58,7 @@
|
|
|
55
58
|
"bench": "node bench/index.js",
|
|
56
59
|
"types": "tsc -p tsconfig.json",
|
|
57
60
|
"tables": "node tools/build-tables.js",
|
|
58
|
-
"prepublishOnly": "npm run
|
|
61
|
+
"prepublishOnly": "npm run types && npm test"
|
|
59
62
|
},
|
|
60
63
|
"publishConfig": {
|
|
61
64
|
"access": "public"
|
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
|
|
@@ -564,6 +577,37 @@ class strim {
|
|
|
564
577
|
return this._find(this._class('WIDE'), cp, 2) >= 0 ? 2 : 1;
|
|
565
578
|
}
|
|
566
579
|
|
|
580
|
+
//width of one grapheme cluster from its first code point. Emoji presentation widens a
|
|
581
|
+
//narrow pictograph (☺ + VS16 U+FE0F → 2), and a regional-indicator pair is one flag (2).
|
|
582
|
+
_clusterw(base, cps) {
|
|
583
|
+
const w = this._width(base);
|
|
584
|
+
if (w !== 1) return w;
|
|
585
|
+
if (cps > 1 && (this._gcb(base) & 15) === GCB.RI) return 2;
|
|
586
|
+
return w;
|
|
587
|
+
}
|
|
588
|
+
//display width of a run of code points, cluster by cluster (UAX #29 boundaries, as _graph).
|
|
589
|
+
//One state machine for dlen and both wraps, so a ZWJ sequence is one glyph everywhere.
|
|
590
|
+
_cpsw(cps) {
|
|
591
|
+
let w = 0, prev = -1, ri = 0, pict = false, base = -1, n = 0, vs = false;
|
|
592
|
+
const flush = () => {
|
|
593
|
+
if (base < 0) return;
|
|
594
|
+
const cw = this._clusterw(base, n);
|
|
595
|
+
w += cw === 1 && vs && (this._gcb(base) & 16) ? 2 : cw;
|
|
596
|
+
};
|
|
597
|
+
for (const cp of cps) {
|
|
598
|
+
const raw = this._gcb(cp), cls = raw & 15;
|
|
599
|
+
if (prev < 0 || this._gbreak(prev, cls, ri, pict, (raw & 16) !== 0)) { flush(); base = cp; n = 0; vs = false; }
|
|
600
|
+
if (cp === 0xfe0f) vs = true;
|
|
601
|
+
n++;
|
|
602
|
+
ri = cls === GCB.RI ? ri + 1 : 0;
|
|
603
|
+
if (raw & 16) pict = true;
|
|
604
|
+
else if (cls !== GCB.EXTEND && cls !== GCB.ZWJ) pict = false;
|
|
605
|
+
prev = cls;
|
|
606
|
+
}
|
|
607
|
+
flush();
|
|
608
|
+
return w;
|
|
609
|
+
}
|
|
610
|
+
|
|
567
611
|
//case folding (simple case folding). By table, not via toLowerCase: the latter needs
|
|
568
612
|
//a string. Needed by ichar, ifind and skel.
|
|
569
613
|
_fold(cp) {
|
|
@@ -658,7 +702,7 @@ class strim {
|
|
|
658
702
|
if (first) {
|
|
659
703
|
yield 0;
|
|
660
704
|
first = false;
|
|
661
|
-
} else if (this._gbreak(prev, cls, ri, pict)) {
|
|
705
|
+
} else if (this._gbreak(prev, cls, ri, pict, (raw & 16) !== 0)) {
|
|
662
706
|
yield i;
|
|
663
707
|
}
|
|
664
708
|
//state for GB12/13: length of the current chain of regional indicators
|
|
@@ -673,7 +717,8 @@ class strim {
|
|
|
673
717
|
|
|
674
718
|
//whether to break between class a and class b. Extracted from _graph as a separate method
|
|
675
719
|
//so the rules can be overridden (point 11) — e.g. to glue emoji tags together.
|
|
676
|
-
|
|
720
|
+
//pict: the cluster so far is pictograph Extend* ZWJ; bpict: b is Extended_Pictographic.
|
|
721
|
+
_gbreak(a, b, ri, pict, bpict) {
|
|
677
722
|
if (a === GCB.CR && b === GCB.LF) return false; //GB3
|
|
678
723
|
if (a === GCB.CTRL || a === GCB.CR || a === GCB.LF) return true; //GB4
|
|
679
724
|
if (b === GCB.CTRL || b === GCB.CR || b === GCB.LF) return true; //GB5
|
|
@@ -683,21 +728,29 @@ class strim {
|
|
|
683
728
|
if (b === GCB.EXTEND || b === GCB.ZWJ) return false; //GB9
|
|
684
729
|
if (b === GCB.SPACING) return false; //GB9a
|
|
685
730
|
if (a === GCB.PREPEND) return false; //GB9b
|
|
686
|
-
if (a === GCB.ZWJ && pict) return false; //GB11 —
|
|
731
|
+
if (a === GCB.ZWJ && pict && bpict) return false; //GB11 — ExtPict Extend* ZWJ × ExtPict, nothing else
|
|
687
732
|
if (a === GCB.RI && b === GCB.RI && ri % 2 === 1) return false; //GB12/13
|
|
688
733
|
return true; //GB999
|
|
689
734
|
}
|
|
690
735
|
|
|
691
|
-
//normalize a needle set to an array of Int32Array
|
|
692
|
-
//
|
|
693
|
-
|
|
736
|
+
//normalize a needle set to an array of Int32Array units. Accepts a string, a number
|
|
737
|
+
//(code point), or an iterable of those. dec — the SOURCE's decoding (point 4): the
|
|
738
|
+
//automaton runs over raw source units, so a needle must be spelled in the same units —
|
|
739
|
+
//utf-16 code units for a string, utf-8 bytes for a buffer, code points for an array.
|
|
740
|
+
//Folding is a code-unit / code-point transform and has no meaning on bytes (see _gfind).
|
|
741
|
+
_needles(target, fold, dec = 0) {
|
|
694
742
|
const list = [];
|
|
695
743
|
const one = (t) => {
|
|
696
744
|
if (typeof t === 'number') t = String.fromCodePoint(t);
|
|
697
745
|
if (typeof t !== 'string') throw new TypeError('str-im: a needle must be a string or a code point');
|
|
698
746
|
if (t.length === 0) return; //an empty needle would match everywhere and hang the automaton
|
|
699
|
-
|
|
700
|
-
|
|
747
|
+
let a;
|
|
748
|
+
if (dec === 1) a = Int32Array.from(U8ENC.encode(t));
|
|
749
|
+
else if (dec === 2) a = Int32Array.from(t, (c) => fold ? this._fold(c.codePointAt(0)) : c.codePointAt(0));
|
|
750
|
+
else {
|
|
751
|
+
a = new Int32Array(t.length);
|
|
752
|
+
for (let i = 0; i < t.length; i++) a[i] = fold ? this._fold(t.charCodeAt(i)) : t.charCodeAt(i);
|
|
753
|
+
}
|
|
701
754
|
list.push(a);
|
|
702
755
|
};
|
|
703
756
|
if (typeof target === 'string' || typeof target === 'number') one(target);
|
|
@@ -716,9 +769,12 @@ class strim {
|
|
|
716
769
|
//The core for find, lfind, ifind, omit, omitn, clear, split, splitn.
|
|
717
770
|
//For a single needle the automaton degenerates into KMP, no separate code needed.
|
|
718
771
|
_ac(needles) {
|
|
719
|
-
//cache key — the needles themselves
|
|
772
|
+
//cache key — the needles themselves, as decimal units with ',' inside a needle and ';'
|
|
773
|
+
//after it. Both separators are outside the digit alphabet, so the key is injective:
|
|
774
|
+
//['a', 'b'] and ['a b'] MUST NOT share an automaton (a raw-character key with a space
|
|
775
|
+
//separator once let them, and the second call silently got the first one's matches).
|
|
720
776
|
let key = '';
|
|
721
|
-
for (const n of needles)
|
|
777
|
+
for (const n of needles) key += n.join(',') + ';';
|
|
722
778
|
const hit = ACS.get(key);
|
|
723
779
|
if (hit) { ACS.delete(key); ACS.set(key, hit); return hit; } //LRU: refresh
|
|
724
780
|
//--- build the trie on temporary Maps (build stage only) ---
|
|
@@ -1004,15 +1060,10 @@ class strim {
|
|
|
1004
1060
|
return c === 0 ? 0 : c - 1;
|
|
1005
1061
|
}
|
|
1006
1062
|
//visual width in columns: width is taken for the cluster as a whole (by its base
|
|
1007
|
-
//code point); combining marks inside give 0 and don't enter the sum
|
|
1063
|
+
//code point); combining marks inside give 0 and don't enter the sum; VS16 and flag
|
|
1064
|
+
//pairs widen a cluster to 2 (see _cpsw).
|
|
1008
1065
|
dlen(buf) {
|
|
1009
|
-
|
|
1010
|
-
let w = 0, prev = -1;
|
|
1011
|
-
for (const b of this._graph(buf, adp)) {
|
|
1012
|
-
if (prev >= 0) w += this._width(this._at(buf, adp, prev));
|
|
1013
|
-
prev = b;
|
|
1014
|
-
}
|
|
1015
|
-
return w;
|
|
1066
|
+
return this._cpsw(this._cps(buf, this._adapter(buf)));
|
|
1016
1067
|
}
|
|
1017
1068
|
|
|
1018
1069
|
//=========================================================================
|
|
@@ -1027,7 +1078,7 @@ class strim {
|
|
|
1027
1078
|
omit(str, omits) { return this._prime(this._gomit(str, omits)); }
|
|
1028
1079
|
*_gomit(str, omits) {
|
|
1029
1080
|
const adp = this._adapter(str);
|
|
1030
|
-
const ac = this._ac(this._needles(omits, false));
|
|
1081
|
+
const ac = this._ac(this._needles(omits, false, adp.dec));
|
|
1031
1082
|
yield; //barrier (point 6): validation of the source and needles has already happened
|
|
1032
1083
|
const seg = this._seg(str, adp, ac);
|
|
1033
1084
|
for (let s = seg.next(); !s.done; s = seg.next()) {
|
|
@@ -1045,7 +1096,7 @@ class strim {
|
|
|
1045
1096
|
omitn(str, omits) { return this._prime(this._gomitn(str, omits)); }
|
|
1046
1097
|
*_gomitn(str, omits) {
|
|
1047
1098
|
const adp = this._adapter(str);
|
|
1048
|
-
const ac = this._ac(this._needles(omits, false));
|
|
1099
|
+
const ac = this._ac(this._needles(omits, false, adp.dec));
|
|
1049
1100
|
yield;
|
|
1050
1101
|
const seg = this._seg(str, adp, ac);
|
|
1051
1102
|
let prevEnd = -1;
|
|
@@ -1064,7 +1115,7 @@ class strim {
|
|
|
1064
1115
|
clear(str, omits) {
|
|
1065
1116
|
if (typeof str !== 'string') throw new TypeError(`str-im: str must be a string, got ${typeof str}`);
|
|
1066
1117
|
const adp = this._adapter(str);
|
|
1067
|
-
const ac = this._ac(this._needles(omits, false));
|
|
1118
|
+
const ac = this._ac(this._needles(omits, false, adp.dec));
|
|
1068
1119
|
const seg = this._seg(str, adp, ac);
|
|
1069
1120
|
const parts = [];
|
|
1070
1121
|
let pairs = 0;
|
|
@@ -1306,17 +1357,17 @@ class strim {
|
|
|
1306
1357
|
cut(src, max, ell) { return this._cut(src, max, ell, 0); }
|
|
1307
1358
|
bcut(src, max, ell) { return this._cut(src, max, ell, 1); }
|
|
1308
1359
|
wcut(src, max, ell) { return this._cut(src, max, ell, 2); }
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
let wsum = 0, cutIdx = 0
|
|
1360
|
+
//where to cut: the unit index up to which the source stays within `limit` (max minus
|
|
1361
|
+
//the ellipsis weight), or -1 when the whole source fits in `max` and nothing is cut.
|
|
1362
|
+
//Shared by _cut and Mut._cut (point 13): the walk is the same, only what happens to
|
|
1363
|
+
//the head differs — a slice there, a length change in place here.
|
|
1364
|
+
_cutAt(src, adp, max, limit, mode) {
|
|
1365
|
+
let wsum = 0, cutIdx = 0;
|
|
1315
1366
|
if (mode === 2) {
|
|
1316
1367
|
let prev = -1;
|
|
1317
1368
|
for (const b of this._graph(src, adp)) {
|
|
1318
1369
|
if (prev >= 0) {
|
|
1319
|
-
if (wsum + 1 > max)
|
|
1370
|
+
if (wsum + 1 > max) return cutIdx;
|
|
1320
1371
|
wsum += 1;
|
|
1321
1372
|
if (wsum <= limit) cutIdx = b;
|
|
1322
1373
|
}
|
|
@@ -1325,12 +1376,19 @@ class strim {
|
|
|
1325
1376
|
} else {
|
|
1326
1377
|
for (const [, end, cp] of this._cpwalk(src, adp)) {
|
|
1327
1378
|
const w = mode === 1 ? this._cplen(cp) : 1;
|
|
1328
|
-
if (wsum + w > max)
|
|
1379
|
+
if (wsum + w > max) return cutIdx;
|
|
1329
1380
|
wsum += w;
|
|
1330
1381
|
if (wsum <= limit) cutIdx = end;
|
|
1331
1382
|
}
|
|
1332
1383
|
}
|
|
1333
|
-
|
|
1384
|
+
return -1;
|
|
1385
|
+
}
|
|
1386
|
+
_cut(src, max, ell, mode) {
|
|
1387
|
+
max = this._max(max);
|
|
1388
|
+
const adp = this._adapter(src);
|
|
1389
|
+
const ellW = ell == null ? 0 : (mode === 0 ? this.len(ell) : mode === 1 ? this.blen(ell) : this.glen(ell));
|
|
1390
|
+
const cutIdx = this._cutAt(src, adp, max, max - ellW, mode);
|
|
1391
|
+
if (cutIdx < 0) return src;
|
|
1334
1392
|
if (typeof src === 'string') return src.slice(0, cutIdx) + (ell == null ? '' : String(ell));
|
|
1335
1393
|
if (src instanceof Uint8Array) {
|
|
1336
1394
|
const head = src.subarray(0, cutIdx);
|
|
@@ -1360,7 +1418,7 @@ class strim {
|
|
|
1360
1418
|
ifind(str, target, opts) { return this._prime(this._gfind(str, target, false, true, opts?.all === true)); }
|
|
1361
1419
|
*_gfind(str, target, rev, fold, all) {
|
|
1362
1420
|
const adp = this._adapter(str);
|
|
1363
|
-
let needles = this._needles(target, fold);
|
|
1421
|
+
let needles = this._needles(target, fold, adp.dec);
|
|
1364
1422
|
if (rev) needles = needles.map((a) => Int32Array.from(a).reverse());
|
|
1365
1423
|
const ac = this._ac(needles);
|
|
1366
1424
|
yield; //barrier (point 6)
|
|
@@ -1469,7 +1527,7 @@ class strim {
|
|
|
1469
1527
|
const quoteOn = this._quoteOn(opts);
|
|
1470
1528
|
const limit = opts?.limit;
|
|
1471
1529
|
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));
|
|
1530
|
+
const ac = sep == null ? null : this._ac(this._needles(sep, false, adp.dec));
|
|
1473
1531
|
yield; //barrier (point 6)
|
|
1474
1532
|
const size = adp.size(str);
|
|
1475
1533
|
const qit = quoteOn ? this._quote(this._units(str, adp), opts)[Symbol.iterator]() : null;
|
|
@@ -1638,8 +1696,9 @@ class strim {
|
|
|
1638
1696
|
}
|
|
1639
1697
|
|
|
1640
1698
|
//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 —
|
|
1699
|
+
//stopping at the first non-matching character. trim — both edges, ltrim / rtrim — one.
|
|
1642
1700
|
trim(str, chars) { return this._trim(str, chars, true, true); }
|
|
1701
|
+
ltrim(str, chars) { return this._trim(str, chars, true, false); }
|
|
1643
1702
|
rtrim(str, chars) { return this._trim(str, chars, false, true); }
|
|
1644
1703
|
_trimtest(chars) {
|
|
1645
1704
|
if (chars == null) return (cp) => this._is('WS', cp);
|
|
@@ -1858,16 +1917,371 @@ class strim {
|
|
|
1858
1917
|
//visual width of a string in columns, stripping ANSI-CSI (ESC '[' … final byte @-~).
|
|
1859
1918
|
_vwidth(s) {
|
|
1860
1919
|
const adp = this._adapter(s);
|
|
1861
|
-
const cps = [...this._cps(s, adp)];
|
|
1862
|
-
let w = 0;
|
|
1920
|
+
const cps = [...this._cps(s, adp)], out = [];
|
|
1863
1921
|
for (let i = 0; i < cps.length; i++) {
|
|
1864
1922
|
if (cps[i] === 0x1b) { i++; if (cps[i] === 0x5b) { i++; while (i < cps.length && !(cps[i] >= 0x40 && cps[i] <= 0x7e)) i++; } continue; }
|
|
1865
|
-
|
|
1923
|
+
out.push(cps[i]);
|
|
1866
1924
|
}
|
|
1867
|
-
return
|
|
1925
|
+
return this._cpsw(out);
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
|
|
1929
|
+
//=========================================================================
|
|
1930
|
+
//=== 14. MUTABLE STRING (point 13). The only method that hands out something writable.
|
|
1931
|
+
//=========================================================================
|
|
1932
|
+
|
|
1933
|
+
//a string is decoded ONCE into a Uint16Array of code units — the single allocation on the
|
|
1934
|
+
//way in; a utf-8 buffer is edited in place, the caller's bytes, no copy at all. Anything
|
|
1935
|
+
//else is a TypeError (point 6). The Mut remembers `this`, so a configured engine
|
|
1936
|
+
//(_strim) edits with its own overrides (point 11).
|
|
1937
|
+
mut(src) {
|
|
1938
|
+
if (typeof src === 'string') {
|
|
1939
|
+
const b = new Uint16Array(src.length);
|
|
1940
|
+
for (let i = 0; i < src.length; i++) b[i] = src.charCodeAt(i);
|
|
1941
|
+
return new MutU16(this, b, b.length);
|
|
1942
|
+
}
|
|
1943
|
+
if (src instanceof Uint8Array) return new MutU8(this, src, src.length);
|
|
1944
|
+
throw new TypeError(`str-im: mut(src) — a string or a utf-8 Uint8Array, got ${src === null ? 'null' : typeof src}`);
|
|
1868
1945
|
}
|
|
1869
1946
|
}
|
|
1870
1947
|
|
|
1948
|
+
|
|
1949
|
+
//=========================================================================
|
|
1950
|
+
//=== MUTABLE STRING (point 13). The engine READS; these WRITE, in place.
|
|
1951
|
+
//=========================================================================
|
|
1952
|
+
|
|
1953
|
+
//The shared part: everything that can be said in unit indices and the engine's index streams.
|
|
1954
|
+
//What differs between utf-16 and utf-8 — how many units a code point takes, how to write one,
|
|
1955
|
+
//where the previous one starts, how to materialize — lives in the two subclasses, and each is
|
|
1956
|
+
//registered as its own source: an adapter's dec is fixed per constructor (point 4).
|
|
1957
|
+
class Mut {
|
|
1958
|
+
constructor(engine, buf, n) {
|
|
1959
|
+
this.engine = engine; //the instance that made us: every call dispatches through it (point 11)
|
|
1960
|
+
this.buf = buf; //the one buffer; never reallocated
|
|
1961
|
+
this.n = n; //live length in units; only ever goes down
|
|
1962
|
+
}
|
|
1963
|
+
get length() { return this.n; }
|
|
1964
|
+
get [Symbol.toStringTag]() { return 'Mut'; }
|
|
1965
|
+
[Symbol.toPrimitive]() { return this.toString(); }
|
|
1966
|
+
toJSON() { return this.toString(); }
|
|
1967
|
+
|
|
1968
|
+
//--- 0. the compaction primitive ---
|
|
1969
|
+
|
|
1970
|
+
//copy [a, b) down to the write pointer w and return the new w. copyWithin is a memmove.
|
|
1971
|
+
//Every editing method streams over one of the engine's index generators and keeps the
|
|
1972
|
+
//ranges it wants. w <= a always holds because kept ranges arrive in ascending order, so a
|
|
1973
|
+
//write never lands at or beyond the generator's read position — the buffer being read IS
|
|
1974
|
+
//the buffer being written, and this ordering is exactly what makes that safe.
|
|
1975
|
+
_keep(w, a, b) {
|
|
1976
|
+
if (w !== a) this.buf.copyWithin(w, a, b);
|
|
1977
|
+
return w + (b - a);
|
|
1978
|
+
}
|
|
1979
|
+
//code points as [start, end) unit ranges without allocating a pair per element (point 8):
|
|
1980
|
+
//the engine yields starts, the end of one is the start of the next, the last ends at n.
|
|
1981
|
+
_walk(fn) {
|
|
1982
|
+
const e = this.engine, adp = e._adapter(this);
|
|
1983
|
+
let prev = -1;
|
|
1984
|
+
for (const i of e._pointn(this, adp)) {
|
|
1985
|
+
if (prev >= 0) fn(prev, i, e._at(this, adp, prev));
|
|
1986
|
+
prev = i;
|
|
1987
|
+
}
|
|
1988
|
+
if (prev >= 0) fn(prev, this.n, e._at(this, adp, prev));
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
//--- 1. slices: keep a part ---
|
|
1992
|
+
|
|
1993
|
+
//keep [start, end) in units. Out of range is a RangeError, not a clamp (point 6).
|
|
1994
|
+
slice(start, end = this.n) {
|
|
1995
|
+
if (!Number.isInteger(start) || !Number.isInteger(end)) throw new TypeError(`str-im: slice(start, end) — integers required, got ${start}, ${end}`);
|
|
1996
|
+
if (start < 0 || end > this.n || start > end) throw new RangeError(`str-im: slice(${start}, ${end}) out of range 0..${this.n}`);
|
|
1997
|
+
if (start > 0) this.buf.copyWithin(0, start, end);
|
|
1998
|
+
this.n = end - start;
|
|
1999
|
+
return this;
|
|
2000
|
+
}
|
|
2001
|
+
//keep only the piece after / before the first / last `target` — the substr family, in place.
|
|
2002
|
+
//A string target is searched through the engine (find / lfind), so it works on utf-8 too;
|
|
2003
|
+
//a number is a position. Not found — NotFound, exactly as in the engine (point 6).
|
|
2004
|
+
substr(target, offset = Infinity) { return this._sub(target, offset, false, false); }
|
|
2005
|
+
lsubstr(target, offset = Infinity) { return this._sub(target, offset, true, false); }
|
|
2006
|
+
substrb(target, offset = Infinity) { return this._sub(target, offset, false, true); }
|
|
2007
|
+
lsubstrb(target, offset = Infinity) { return this._sub(target, offset, true, true); }
|
|
2008
|
+
_sub(target, offset, last, back) {
|
|
2009
|
+
const e = this.engine;
|
|
2010
|
+
offset = e._offset(offset);
|
|
2011
|
+
let i, tlen = 0;
|
|
2012
|
+
if (typeof target === 'number') {
|
|
2013
|
+
if (!Number.isInteger(target)) throw new TypeError(`str-im: a numeric target must be an integer, got ${target}`);
|
|
2014
|
+
if (target < 0 || target > this.n) throw new RangeError(`str-im: position ${target} out of range 0..${this.n}`);
|
|
2015
|
+
i = target;
|
|
2016
|
+
} else if (typeof target !== 'string') {
|
|
2017
|
+
throw new TypeError(`str-im: target must be a string or a position, got ${typeof target}`);
|
|
2018
|
+
} else if (target === '') {
|
|
2019
|
+
i = last ? this.n : 0; //indexOf('') is 0, lastIndexOf('') is the length
|
|
2020
|
+
} else {
|
|
2021
|
+
const r = (last ? e.lfind(this, target) : e.find(this, target)).next();
|
|
2022
|
+
if (r.done) throw new NotFound(JSON.stringify(target));
|
|
2023
|
+
i = r.value;
|
|
2024
|
+
tlen = e._needles(target, false, e._adapter(this).dec)[0].length;
|
|
2025
|
+
}
|
|
2026
|
+
if (back) return this.slice(offset === Infinity ? 0 : Math.max(0, i - offset), i);
|
|
2027
|
+
const start = i + tlen;
|
|
2028
|
+
return this.slice(start, offset === Infinity ? this.n : Math.min(this.n, start + offset));
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
//--- 2. dropping ---
|
|
2032
|
+
|
|
2033
|
+
//remove every occurrence of the needles (leftmost-longest, non-overlapping) — clear, in place.
|
|
2034
|
+
//splitn yields exactly the pieces BETWEEN matches, validated at the call.
|
|
2035
|
+
drop(needles) {
|
|
2036
|
+
if (needles == null) throw new TypeError('str-im: drop(needles) — needles are required');
|
|
2037
|
+
const it = this.engine.splitn(this, needles);
|
|
2038
|
+
let w = 0;
|
|
2039
|
+
for (let a = it.next(); !a.done; a = it.next()) w = this._keep(w, a.value, it.next().value);
|
|
2040
|
+
this.n = w;
|
|
2041
|
+
return this;
|
|
2042
|
+
}
|
|
2043
|
+
//collapse runs to `keep` (default 1); chars — only these characters. flat, in place.
|
|
2044
|
+
flat(chars, keep = 1) {
|
|
2045
|
+
const e = this.engine;
|
|
2046
|
+
keep = e._max(keep);
|
|
2047
|
+
let set = null;
|
|
2048
|
+
if (chars != null) { set = new Set(); for (const ch of String(chars)) set.add(ch.codePointAt(0)); }
|
|
2049
|
+
let w = 0, prev = -1, run = 0;
|
|
2050
|
+
this._walk((a, b, cp) => {
|
|
2051
|
+
run = cp === prev ? run + 1 : 1;
|
|
2052
|
+
prev = cp;
|
|
2053
|
+
if (run <= (set === null || set.has(cp) ? keep : Infinity)) w = this._keep(w, a, b);
|
|
2054
|
+
});
|
|
2055
|
+
this.n = w;
|
|
2056
|
+
return this;
|
|
2057
|
+
}
|
|
2058
|
+
//drop the escape character and keep what follows it literally — unesc, in place.
|
|
2059
|
+
//A trailing lone escape stays, as in the engine.
|
|
2060
|
+
unesc(opts) {
|
|
2061
|
+
const ec = (opts?.esc ?? '\\').codePointAt(0);
|
|
2062
|
+
let w = 0, lit = false;
|
|
2063
|
+
this._walk((a, b, cp) => {
|
|
2064
|
+
if (lit) { lit = false; w = this._keep(w, a, b); }
|
|
2065
|
+
else if (cp === ec && b < this.n) lit = true;
|
|
2066
|
+
else w = this._keep(w, a, b);
|
|
2067
|
+
});
|
|
2068
|
+
this.n = w;
|
|
2069
|
+
return this;
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
//--- 3. edges ---
|
|
2073
|
+
|
|
2074
|
+
//trim a set (\p{White_Space} by default) from the edges — trim / ltrim / rtrim, in place.
|
|
2075
|
+
//The left edge walks forward on the engine's index stream; the right edge walks back one
|
|
2076
|
+
//code point at a time (_back), and a stray unit that is not a whole character stops it.
|
|
2077
|
+
trim(chars) { return this._trim(chars, true, true); }
|
|
2078
|
+
ltrim(chars) { return this._trim(chars, true, false); }
|
|
2079
|
+
rtrim(chars) { return this._trim(chars, false, true); }
|
|
2080
|
+
_trim(chars, left, right) {
|
|
2081
|
+
const e = this.engine, adp = e._adapter(this), test = e._trimtest(chars);
|
|
2082
|
+
let a = 0, b = this.n;
|
|
2083
|
+
if (left) {
|
|
2084
|
+
a = b; //until a character says otherwise, everything is trimmable
|
|
2085
|
+
for (const i of e._pointn(this, adp)) if (!test(e._at(this, adp, i))) { a = i; break; }
|
|
2086
|
+
}
|
|
2087
|
+
if (right) while (b > a) {
|
|
2088
|
+
const s = this._back(b, a), cp = e._at(this, adp, s);
|
|
2089
|
+
if (s + this._units(cp) !== b || !test(cp)) break;
|
|
2090
|
+
b = s;
|
|
2091
|
+
}
|
|
2092
|
+
if (a === 0 && b === this.n) return this;
|
|
2093
|
+
if (a > 0) this.buf.copyWithin(0, a, b);
|
|
2094
|
+
this.n = b - a;
|
|
2095
|
+
return this;
|
|
2096
|
+
}
|
|
2097
|
+
//truncate to `max` code points / utf-8 bytes / grapheme clusters — cut / bcut / wcut, in
|
|
2098
|
+
//place. The walk is the engine's own (_cutAt). An ellipsis is written over the cut region
|
|
2099
|
+
//and must fit in it: the buffer never grows, and the check comes before the write.
|
|
2100
|
+
cut(max, ell) { return this._cut(max, ell, 0); }
|
|
2101
|
+
bcut(max, ell) { return this._cut(max, ell, 1); }
|
|
2102
|
+
wcut(max, ell) { return this._cut(max, ell, 2); }
|
|
2103
|
+
_cut(max, ell, mode) {
|
|
2104
|
+
const e = this.engine, adp = e._adapter(this);
|
|
2105
|
+
max = e._max(max);
|
|
2106
|
+
const ellW = ell == null ? 0 : (mode === 0 ? e.len(ell) : mode === 1 ? e.blen(ell) : e.glen(ell));
|
|
2107
|
+
const cutIdx = e._cutAt(this, adp, max, max - ellW, mode);
|
|
2108
|
+
if (cutIdx < 0) return this; //fits — untouched
|
|
2109
|
+
if (ell == null) { this.n = cutIdx; return this; }
|
|
2110
|
+
const tail = this._encode(ell);
|
|
2111
|
+
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`);
|
|
2112
|
+
this.buf.set(tail, cutIdx);
|
|
2113
|
+
this.n = cutIdx + tail.length;
|
|
2114
|
+
return this;
|
|
2115
|
+
}
|
|
2116
|
+
//strip the indent common to all non-empty lines — dedent, in place. Two passes: find the
|
|
2117
|
+
//prefix (spaces and tabs are single units in both encodings, so this is a plain unit scan),
|
|
2118
|
+
//then compact. The prefix lives in the first non-empty line, which compaction overwrites,
|
|
2119
|
+
//so it is copied out first — the one small allocation here besides an ellipsis.
|
|
2120
|
+
dedent() {
|
|
2121
|
+
const buf = this.buf, n = this.n;
|
|
2122
|
+
let pStart = -1, pLen = 0;
|
|
2123
|
+
for (let ls = 0; ls < n;) {
|
|
2124
|
+
let k = ls;
|
|
2125
|
+
while (k < n && (buf[k] === 32 || buf[k] === 9)) k++;
|
|
2126
|
+
let le = k;
|
|
2127
|
+
while (le < n && buf[le] !== 10) le++;
|
|
2128
|
+
if (k < le) { //a line with something after its indent constrains the prefix
|
|
2129
|
+
if (pStart < 0) { pStart = ls; pLen = k - ls; }
|
|
2130
|
+
else { let j = 0; while (j < pLen && ls + j < k && buf[pStart + j] === buf[ls + j]) j++; pLen = j; }
|
|
2131
|
+
if (pLen === 0) return this;
|
|
2132
|
+
}
|
|
2133
|
+
ls = le + 1;
|
|
2134
|
+
}
|
|
2135
|
+
if (pStart < 0) return this;
|
|
2136
|
+
const pre = buf.slice(pStart, pStart + pLen);
|
|
2137
|
+
let w = 0;
|
|
2138
|
+
for (let ls = 0; ls < n;) {
|
|
2139
|
+
let le = ls;
|
|
2140
|
+
while (le < n && buf[le] !== 10) le++;
|
|
2141
|
+
let j = 0;
|
|
2142
|
+
while (j < pLen && ls + j < le && buf[ls + j] === pre[j]) j++;
|
|
2143
|
+
w = this._keep(w, j === pLen ? ls + pLen : ls, le < n ? le + 1 : le);
|
|
2144
|
+
ls = le + 1;
|
|
2145
|
+
}
|
|
2146
|
+
this.n = w;
|
|
2147
|
+
return this;
|
|
2148
|
+
}
|
|
2149
|
+
|
|
2150
|
+
//--- 4. same-length rewrites ---
|
|
2151
|
+
|
|
2152
|
+
//wrap by display width, in place: the space before a word that no longer fits becomes a
|
|
2153
|
+
//newline. Same words, same length, same rule as the engine's wrap — the engine yields
|
|
2154
|
+
//lines, this rewrites separators. Paragraphs (\n) are kept; a long word overflows.
|
|
2155
|
+
//Space and newline are one unit in utf-16 and utf-8 alike, so the scan is on raw units.
|
|
2156
|
+
wrap(width) {
|
|
2157
|
+
if (!Number.isInteger(width) || width < 1) throw new RangeError(`str-im: width must be an integer >= 1, got ${width}`);
|
|
2158
|
+
const buf = this.buf, n = this.n;
|
|
2159
|
+
let lineW = 0, first = true;
|
|
2160
|
+
for (let ws = 0; ws <= n;) {
|
|
2161
|
+
let we = ws;
|
|
2162
|
+
while (we < n && buf[we] !== 32 && buf[we] !== 10) we++;
|
|
2163
|
+
const ww = this._vwidth(ws, we);
|
|
2164
|
+
if (first) { lineW = ww; first = false; }
|
|
2165
|
+
else if (lineW + 1 + ww <= width) lineW += 1 + ww;
|
|
2166
|
+
else { buf[ws - 1] = 10; lineW = ww; }
|
|
2167
|
+
if (we >= n) break;
|
|
2168
|
+
if (buf[we] === 10) first = true;
|
|
2169
|
+
ws = we + 1;
|
|
2170
|
+
}
|
|
2171
|
+
return this;
|
|
2172
|
+
}
|
|
2173
|
+
//display width of [a, b) — the engine's _vwidth over a range, ANSI-CSI excluded
|
|
2174
|
+
_vwidth(a, b) {
|
|
2175
|
+
const e = this.engine, adp = e._adapter(this);
|
|
2176
|
+
const out = [];
|
|
2177
|
+
for (let i = a; i < b;) {
|
|
2178
|
+
const cp = e._at(this, adp, i);
|
|
2179
|
+
i = this._next(i);
|
|
2180
|
+
if (cp === 0x1b) {
|
|
2181
|
+
if (i < b) {
|
|
2182
|
+
const c1 = e._at(this, adp, i);
|
|
2183
|
+
i = this._next(i);
|
|
2184
|
+
if (c1 === 0x5b) while (i < b) { const c = e._at(this, adp, i); i = this._next(i); if (c >= 0x40 && c <= 0x7e) break; }
|
|
2185
|
+
}
|
|
2186
|
+
continue;
|
|
2187
|
+
}
|
|
2188
|
+
out.push(cp);
|
|
2189
|
+
}
|
|
2190
|
+
return e._cpsw(out);
|
|
2191
|
+
}
|
|
2192
|
+
//simple case folding in place, by the engine's table. Pass one proves every folded code
|
|
2193
|
+
//point fits the slot of the original (utf-16 never changes width; in utf-8 a few do — Ⱥ
|
|
2194
|
+
//U+023A is 2 bytes, ⱥ U+2C65 is 3) — a RangeError before the first write, never a
|
|
2195
|
+
//half-folded buffer. Pass two writes, compacting where a fold got narrower.
|
|
2196
|
+
fold() {
|
|
2197
|
+
const e = this.engine, adp = e._adapter(this);
|
|
2198
|
+
for (let i = 0; i < this.n;) {
|
|
2199
|
+
const cp = e._at(this, adp, i), next = this._next(i), f = e._fold(cp);
|
|
2200
|
+
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`);
|
|
2201
|
+
i = next;
|
|
2202
|
+
}
|
|
2203
|
+
let w = 0;
|
|
2204
|
+
this._walk((a, b, cp) => {
|
|
2205
|
+
const f = e._fold(cp);
|
|
2206
|
+
w = f === cp ? this._keep(w, a, b) : w + this._put(w, f);
|
|
2207
|
+
});
|
|
2208
|
+
this.n = w;
|
|
2209
|
+
return this;
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
|
|
2213
|
+
//utf-16 code units over a Uint16Array. Materialization is String.fromCharCode in chunks:
|
|
2214
|
+
//one call, one string for anything up to 8 K units; a TextDecoder would be as cheap but
|
|
2215
|
+
//replaces a lone surrogate with U+FFFD, and the user's data is not ours to repair.
|
|
2216
|
+
class MutU16 extends Mut {
|
|
2217
|
+
_units(cp) { return cp >= 0x10000 ? 2 : 1; }
|
|
2218
|
+
_put(i, cp) {
|
|
2219
|
+
if (cp < 0x10000) { this.buf[i] = cp; return 1; }
|
|
2220
|
+
cp -= 0x10000;
|
|
2221
|
+
this.buf[i] = 0xd800 + (cp >> 10);
|
|
2222
|
+
this.buf[i + 1] = 0xdc00 + (cp & 0x3ff);
|
|
2223
|
+
return 2;
|
|
2224
|
+
}
|
|
2225
|
+
//start of the code point that ends at b (b > a): one unit, or two for a surrogate pair
|
|
2226
|
+
_back(b, a) {
|
|
2227
|
+
const s = b - 1, u = this.buf[s];
|
|
2228
|
+
if (u >= 0xdc00 && u <= 0xdfff && s > a) { const h = this.buf[s - 1]; if (h >= 0xd800 && h <= 0xdbff) return s - 1; }
|
|
2229
|
+
return s;
|
|
2230
|
+
}
|
|
2231
|
+
//start of the code point after the one at i
|
|
2232
|
+
_next(i) {
|
|
2233
|
+
const u = this.buf[i];
|
|
2234
|
+
if (u >= 0xd800 && u <= 0xdbff && i + 1 < this.n) { const l = this.buf[i + 1]; if (l >= 0xdc00 && l <= 0xdfff) return i + 2; }
|
|
2235
|
+
return i + 1;
|
|
2236
|
+
}
|
|
2237
|
+
_encode(ell) {
|
|
2238
|
+
const s = ell instanceof Uint8Array ? U8DEC.decode(ell) : String(ell);
|
|
2239
|
+
const out = new Uint16Array(s.length);
|
|
2240
|
+
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
|
|
2241
|
+
return out;
|
|
2242
|
+
}
|
|
2243
|
+
toString() {
|
|
2244
|
+
const b = this.buf, n = this.n;
|
|
2245
|
+
if (n <= 8192) return String.fromCharCode.apply(null, n === b.length ? b : b.subarray(0, n));
|
|
2246
|
+
const parts = [];
|
|
2247
|
+
for (let i = 0; i < n; i += 8192) parts.push(String.fromCharCode.apply(null, b.subarray(i, Math.min(n, i + 8192))));
|
|
2248
|
+
return parts.join('');
|
|
2249
|
+
}
|
|
2250
|
+
value() { return this.toString(); }
|
|
2251
|
+
}
|
|
2252
|
+
|
|
2253
|
+
//utf-8 bytes over the caller's own Uint8Array. value() is a view of the live prefix — no
|
|
2254
|
+
//copy; toString() decodes it once.
|
|
2255
|
+
class MutU8 extends Mut {
|
|
2256
|
+
_units(cp) { return this.engine._cplen(cp); }
|
|
2257
|
+
_put(i, cp) {
|
|
2258
|
+
const b = this.buf;
|
|
2259
|
+
if (cp < 0x80) { b[i] = cp; return 1; }
|
|
2260
|
+
if (cp < 0x800) { b[i] = 0xc0 | (cp >> 6); b[i + 1] = 0x80 | (cp & 0x3f); return 2; }
|
|
2261
|
+
if (cp < 0x10000) { b[i] = 0xe0 | (cp >> 12); b[i + 1] = 0x80 | ((cp >> 6) & 0x3f); b[i + 2] = 0x80 | (cp & 0x3f); return 3; }
|
|
2262
|
+
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);
|
|
2263
|
+
return 4;
|
|
2264
|
+
}
|
|
2265
|
+
//start of the character that ends at b: step back over continuation bytes to the lead
|
|
2266
|
+
_back(b, a) {
|
|
2267
|
+
let s = b - 1;
|
|
2268
|
+
while (s > a && (this.buf[s] & 0xc0) === 0x80) s--;
|
|
2269
|
+
return s;
|
|
2270
|
+
}
|
|
2271
|
+
_next(i) {
|
|
2272
|
+
i++;
|
|
2273
|
+
while (i < this.n && (this.buf[i] & 0xc0) === 0x80) i++;
|
|
2274
|
+
return i;
|
|
2275
|
+
}
|
|
2276
|
+
_encode(ell) { return ell instanceof Uint8Array ? ell : U8ENC.encode(String(ell)); }
|
|
2277
|
+
toString() { return U8DEC.decode(this.buf.subarray(0, this.n)); }
|
|
2278
|
+
value() { return this.buf.subarray(0, this.n); }
|
|
2279
|
+
}
|
|
2280
|
+
|
|
2281
|
+
//both are sources (point 4): size is the live length, units are the buffer's own
|
|
2282
|
+
strim.use(MutU16, { size: (m) => m.n, at: (m, i) => m.buf[i], dec: 0 });
|
|
2283
|
+
strim.use(MutU8, { size: (m) => m.n, at: (m, i) => m.buf[i], dec: 1 });
|
|
2284
|
+
|
|
1871
2285
|
//a built-in set of cross-script homoglyphs for skel: Cyrillic and Greek characters that
|
|
1872
2286
|
//look identical to Latin ones -> Latin. There is no full TR39 table in the package;
|
|
1873
2287
|
//this is a practical minimum for catching fake domains/handles. Extended via confuse().
|
|
@@ -1917,4 +2331,4 @@ strim.alphabet('semivowel', 'yYйЙыЫ', '');
|
|
|
1917
2331
|
//the default export is a ready instance, the class is available as a named export for str-ez.
|
|
1918
2332
|
const SINGLETON = new strim();
|
|
1919
2333
|
export default SINGLETON;
|
|
1920
|
-
export { strim };
|
|
2334
|
+
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;
|