Merge pull request #13985 from s-hadinger/berry_tr_remove

Berry `string.tr` accepts removing chars
This commit is contained in:
s-hadinger 2021-12-09 23:41:17 +01:00 committed by GitHub
commit 5cc81c1d60
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 8 additions and 5 deletions

View File

@ -793,9 +793,6 @@ static int str_tr(bvm *vm)
const char *p, *s = be_tostring(vm, 1);
const char *t1 = be_tostring(vm, 2);
const char *t2 = be_tostring(vm, 3);
if (strlen(t2) < strlen(t1)) {
be_raise(vm, "value_error", "invalid translation pattern");
}
size_t len = (size_t)be_strlen(vm, 1);
char *buf, *q;
buf = be_pushbuffer(vm, len);
@ -803,11 +800,17 @@ static int str_tr(bvm *vm)
for (p = s, q = buf; *p != '\0'; ++p, ++q) {
const char *p1, *p2;
*q = *p; /* default to no change */
for (p1=t1, p2=t2; *p1 != '\0'; ++p1, ++p2) {
for (p1=t1, p2=t2; *p1 != '\0'; ++p1) {
if (*p == *p1) {
if (*p2) {
*q = *p2;
} else {
q--; /* remove this char */
len--;
}
break;
}
if (*p2) { p2++; }
}
}
be_pushnstring(vm, buf, len); /* make escape string from buffer */