Debian Codegraph @

strings/replace.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use bytes;
5
6 // Returns a new string duplicated from 's', but with all instances of 'needle'
7 // replaced with 'target'. The caller must free the return value.
8 export fn replace(s: str, needle: str, target: str) (str | nomem) = {
9 return multireplace(s, (needle, target));
10 };
11
12 // Performs a replacement in 's' of each tuple given by 'repls'. Replacement
13 // occurs in a single pass of 's', and works like in [[replace]], except that
14 // replacement pairs found earlier in 'repls' will take precedence over later
15 // ones. For example:
16 //
17 // assert(multireplace("hello there", ("e", "a"), ("a", "x"), ("ell", "eww")) == "hallo thara");
18 // assert(multireplace("hello there", ("ell", "eww"), ("e", "a")) == "hewwo thara");
19 //
20 // The caller must free the return value.
21 export fn multireplace(s: str, repls: (str, str)...) (str | nomem) = {
22 let b = toutf8(s);
23 let res: []u8 = [];
24 let ok = false;
25 defer if (!ok) free(res);
26 let i = 0z;
27 let prev = 0z; // end of previous match, so we can append in chunks
28 for :step (i < len(b)) {
29 for (let (replace, with) .. repls) {
30 const replb = (toutf8(replace), toutf8(with));
31 if (bytes::hasprefix(b[i..], replb.0)) {
32 append(res, b[prev..i]...)?;
33 append(res, replb.1...)?;
34 i += len(replb.0);
35 prev = i;
36 continue :step;
37 };
38 };
39 i += 1;
40 };
41 append(res, b[prev..i]...)?;
42 ok = true;
43 return fromutf8_unsafe(res);
44 };
45
46 @test fn replace() void = {
47 const s = replace("Hello world!", "world", "there")!;
48 defer free(s);
49 assert(s == "Hello there!");
50
51 const s = replace("I like dogs, dogs, birds, dogs", "dogs", "cats")!;
52 defer free(s);
53 assert(s == "I like cats, cats, birds, cats");
54
55 const s = replace("aaaaaa", "aa", "a")!;
56 defer free(s);
57 assert(s == "aaa");
58
59 const s = replace("aaa", "a", "aa")!;
60 defer free(s);
61 assert(s == "aaaaaa");
62
63 const s = replace("こんにちは", "にち", "ばん")!;
64 defer free(s);
65 assert(s == "こんばんは");
66 };
67
68 @test fn multireplace() void = {
69 const s = multireplace("Hello world",
70 ("Hello", "Greetings"), ("world", "globe"))!;
71 defer free(s);
72 assert(s == "Greetings globe");
73
74 const s = multireplace("ababa", ("a", "ba"), ("b", "a"), ("a", "c"))!;
75 defer free(s);
76 assert(s == "baabaaba");
77
78 const s = multireplace("hello there", ("e", "a"),
79 ("a", "x"), ("ell", "eww"))!;
80 defer free(s);
81 assert(s == "hallo thara");
82
83 const s = multireplace("hello there", ("ell", "eww"), ("e", "a"))!;
84 defer free(s);
85 assert(s == "hewwo thara");
86 };