Commit 81992038

8199203815e6Merged

NHH <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified

Description

Fix String#chomp no-arg and paragraph mode

No-arg chomp stripped ALL trailing \r\n (e.g. "a\r\n\r\n".chomp returned "a"), but CRuby strips exactly one separator. Now uses priority: \r\n > \n > \r, strips one.

Paragraph mode chomp("") stripped standalone \r (e.g. "a\r".chomp("") returned "a"), but CRuby only strips trailing \r\n pairs and \n's, not standalone \r's. Rewrote to skip \r\n pairs and standalone \n's while preserving trailing \r's that aren't part of a \r\n pair.

Details

Commit
8199203815e6
Parent
2b5da1b0fd56

lib/sp_runtime.hmodifiedView file

@@ -1247,7 +1247,7 @@
12471247 static const char*sp_gets(void){char buf[4096];if(!fgets(buf,sizeof(buf),stdin))return NULL;size_t l=strlen(buf);char*r=sp_str_alloc_raw(l+1);memcpy(r,buf,l+1);return r;}
12481248 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;}
12491249 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;}
1250-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;}
1250+static const char*sp_str_chomp(const char*s){if(!s)return sp_str_empty;size_t l=strlen(s);if(l>=2&&s[l-2]=='\r'&&s[l-1]=='\n')l-=2;else if(l>0&&s[l-1]=='\n')l--;else if(l>0&&s[l-1]=='\r')l--;char*r=sp_str_alloc_raw(l+1);memcpy(r,s,l);r[l]=0;return r;}
12511251
12521252 /* Issue #881: `"hello!".chomp("!")` strips the explicit separator.
12531253 Empty sep strips any trailing newlines (CRuby paragraph mode).
@@ -1257,8 +1257,14 @@
12571257 if (!s) return sp_str_empty;
12581258 size_t l = strlen(s);
12591259 if (!sep || !*sep) {
1260- /* Empty sep = strip all trailing \n / \r\n / \r repeatedly. */
1261- while (l > 0 && (s[l-1] == '\n' || s[l-1] == '\r')) l--;
1260+ /* Empty sep = paragraph mode: strip trailing \r\n pairs and
1261+ standalone \n's, but NOT standalone \r's. A trailing \r that
1262+ is not part of a \r\n pair stops the stripping. */
1263+ while (l > 0) {
1264+ if (l >= 2 && s[l-2] == '\r' && s[l-1] == '\n') { l -= 2; continue; }
1265+ if (s[l-1] == '\n') { l--; continue; }
1266+ break;
1267+ }
12621268 } else {
12631269 size_t sl = strlen(sep);
12641270 if (sl <= l && memcmp(s + l - sl, sep, sl) == 0) l -= sl;