Berry `string.tr` accepts removing chars

This commit is contained in:
Stephan Hadinger 2021-12-09 23:33:05 +01:00
parent a7f96c4e69
commit c4d7a5eab2
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) {
*q = *p2;
if (*p2) {
*q = *p2;
} else {
q--; /* remove this char */
len--;
}
break;
}
if (*p2) { p2++; }
}
}
be_pushnstring(vm, buf, len); /* make escape string from buffer */