From c4d7a5eab2245119ffa411546ebfd84c14372f3e Mon Sep 17 00:00:00 2001 From: Stephan Hadinger Date: Thu, 9 Dec 2021 23:33:05 +0100 Subject: [PATCH] Berry `string.tr` accepts removing chars --- lib/libesp32/Berry/src/be_strlib.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/lib/libesp32/Berry/src/be_strlib.c b/lib/libesp32/Berry/src/be_strlib.c index 53f35607b..e0636c100 100644 --- a/lib/libesp32/Berry/src/be_strlib.c +++ b/lib/libesp32/Berry/src/be_strlib.c @@ -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 */