42 Value repl = pop_value(vm);
46 fprintf(stderr,
"Runtime type error: REGEX_REPLACE expects (string, string, string)\n");
70 const char *
s =
str.s ?
str.s :
"";
71 const char *
r = repl.
s ? repl.
s :
"";
73 size_t out_cap = strlen(
s) + 1;
74 char *outbuf = (
char *)malloc(out_cap);
78 enum { MAX_CAP = 16 };
79 regmatch_t caps[MAX_CAP];
82 if (regexec(&rx,
s + pos, MAX_CAP, caps, 0) != 0) {
84 size_t rest = strlen(
s + pos);
85 if (out_len + rest + 1 > out_cap) {
86 out_cap = out_len + rest + 1;
87 outbuf = (
char *)realloc(outbuf, out_cap);
89 memcpy(outbuf + out_len,
s + pos, rest + 1);
93 int mstart = (int)caps[0].rm_so;
94 int mend = (int)caps[0].rm_eo;
95 if (mstart < 0 || mend < mstart) {
100 size_t pre_len = (size_t)mstart;
101 if (out_len + pre_len + 1 > out_cap) {
102 out_cap = (out_len + pre_len + 1) * 2;
103 outbuf = (
char *)realloc(outbuf, out_cap);
105 memcpy(outbuf + out_len,
s + pos, pre_len);
109 size_t rlen = strlen(
r);
110 if (out_len + rlen + 1 > out_cap) {
111 out_cap = (out_len + rlen + 1) * 2;
112 outbuf = (
char *)realloc(outbuf, out_cap);
114 memcpy(outbuf + out_len,
r, rlen);
120 if (pos < strlen(
s)) {
121 if (out_len + 1 > out_cap) {
122 out_cap = out_len + 2;
123 outbuf = (
char *)realloc(outbuf, out_cap);
125 outbuf[out_len++] =
s[pos++];
133 if (outbuf)
free(outbuf);
Tagged union representing a Fun value.
Value make_string(const char *s)
Construct a string Value by duplicating the given C string.