Commit d1f96a3e

d1f96a3ec8adMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 4 files · +2 added · ~2 modified

Description

runtime,codegen: String#chomp with explicit separator argument

"hello!".chomp("!") used to drop the arg and apply the default \n/\r\n/\r rules. Add sp_str_chomp_sep that strips the explicit suffix (empty sep = paragraph mode, strip trailing newlines).

Refs #881

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
d1f96a3ec8ad
Parent
6c7a9c2a1e2d

lib/sp_runtime.hmodifiedView file

@@ -1334,6 +1334,26 @@
13341334 static sp_StrArray*sp_readlines(void){sp_StrArray*a=sp_StrArray_new();char buf[4096];while(fgets(buf,sizeof(buf),stdin)){size_t l=strlen(buf);char*r=sp_str_alloc_raw(l+1);memcpy(r,buf,l+1);sp_StrArray_push(a,r);}return a;}
13351335 static const char*sp_str_strip(const char*s){if(!s)return sp_str_empty;while(*s&&isspace((unsigned char)*s))s++;size_t l=strlen(s);while(l>0&&isspace((unsigned char)s[l-1]))l--;char*r=sp_str_alloc_raw(l+1);memcpy(r,s,l);r[l]=0;return r;}
13361336 static const char*sp_str_chomp(const char*s){if(!s)return sp_str_empty;size_t l=strlen(s);while(l>0&&(s[l-1]=='\n'||s[l-1]=='\r'))l--;char*r=sp_str_alloc_raw(l+1);memcpy(r,s,l);r[l]=0;return r;}
1337+
1338+/* Issue #881: `"hello!".chomp("!")` strips the explicit separator.
1339+ Empty sep strips any trailing newlines (CRuby paragraph mode).
1340+ NULL sep is caller's responsibility (codegen routes nil to a
1341+ no-op before calling). */
1342+static const char *sp_str_chomp_sep(const char *s, const char *sep) {
1343+ if (!s) return sp_str_empty;
1344+ size_t l = strlen(s);
1345+ if (!sep || !*sep) {
1346+ /* Empty sep = strip all trailing \n / \r\n / \r repeatedly. */
1347+ while (l > 0 && (s[l-1] == '\n' || s[l-1] == '\r')) l--;
1348+ } else {
1349+ size_t sl = strlen(sep);
1350+ if (sl <= l && memcmp(s + l - sl, sep, sl) == 0) l -= sl;
1351+ }
1352+ char *r = sp_str_alloc_raw(l + 1);
1353+ memcpy(r, s, l);
1354+ r[l] = 0;
1355+ return r;
1356+}
13371357 static const char*sp_str_chop(const char*s){if(!s)return sp_str_empty;size_t l=strlen(s);if(l>0){if(l>=2&&s[l-2]=='\r'&&s[l-1]=='\n')l-=2;else l--;}char*r=sp_str_alloc_raw(l+1);memcpy(r,s,l);r[l]=0;return r;}
13381358 static mrb_bool sp_str_include(const char*s,const char*sub){if(!s||!sub)return FALSE;return strstr(s,sub)!=NULL;}
13391359 static mrb_bool sp_str_start_with(const char*s,const char*p){if(!s||!p)return FALSE;return strncmp(s,p,strlen(p))==0;}