Commit 01f2ec72
01f2ec72af04Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified
Description
Merge pull request #1069 from neidiom/fix/str-chomp-paragraph-mode
Fix String#chomp no-arg and paragraph mode
Details
- Commit
- 01f2ec72af04
- Parent
- 245d6db3f804
- Merge parent
- 8199203815e6
lib/sp_runtime.hmodifiedView file
@@ -1251,7 +1251,7 @@
12511251
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;}12521252
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;}12531253
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;}1254-
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;}1254+
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;}12551255
12561256
/* Issue #881: `"hello!".chomp("!")` strips the explicit separator.12571257
Empty sep strips any trailing newlines (CRuby paragraph mode).@@ -1261,8 +1261,14 @@
12611261
if (!s) return sp_str_empty;12621262
size_t l = strlen(s);12631263
if (!sep || !*sep) {1264-
/* Empty sep = strip all trailing \n / \r\n / \r repeatedly. */1265-
while (l > 0 && (s[l-1] == '\n' || s[l-1] == '\r')) l--;1264+
/* Empty sep = paragraph mode: strip trailing \r\n pairs and1265+
standalone \n's, but NOT standalone \r's. A trailing \r that1266+
is not part of a \r\n pair stops the stripping. */1267+
while (l > 0) {1268+
if (l >= 2 && s[l-2] == '\r' && s[l-1] == '\n') { l -= 2; continue; }1269+
if (s[l-1] == '\n') { l--; continue; }1270+
break;1271+
}12661272
} else {12671273
size_t sl = strlen(sep);12681274
if (sl <= l && memcmp(s + l - sl, sep, sl) == 0) l -= sl;test/str_chomp_paragraph_mode.rbaddedView file
Loading diff…
test/str_chomp_paragraph_mode.rb.expectedaddedView file
Loading diff…