Commit 88737669
887376694b63Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 4 files · +2 added · ~2 modified
Description
runtime,codegen: String#<< int appends UTF-8 char, not digits
s << 33 should append the character at codepoint 33 (!), not
the literal "33". The int-arg arm of mutable_str << routed to
sp_int_to_s, producing the latter.
Add sp_int_codepoint_to_str which UTF-8 encodes the codepoint (1..4 bytes) and route the int arm through it.
Refs #882
Co-Authored-By: Claude Opus 4.7 [email protected]
Details
- Commit
- 887376694b63
- Parent
- a1695f59a10a
lib/sp_runtime.hmodifiedView file
@@ -509,6 +509,16 @@
509509
static inline int sp_utf8_advance(const char*p){int cn=sp_utf8_char_len((unsigned char)*p);int i=1;while(i<cn&&((unsigned char)p[i]&0xC0)==0x80)i++;return i;}510510
static inline int sp_utf8_decode(const char*p,uint32_t*out){unsigned char c=(unsigned char)p[0];if(c<0x80){*out=c;return 1;}if(c<0xC0){*out=c;return 1;}unsigned char c1=(unsigned char)p[1];if((c1&0xC0)!=0x80){*out=c;return 1;}if(c<0xE0){*out=((uint32_t)(c&0x1F)<<6)|(c1&0x3F);return 2;}unsigned char c2=(unsigned char)p[2];if((c2&0xC0)!=0x80){*out=c;return 1;}if(c<0xF0){*out=((uint32_t)(c&0x0F)<<12)|((uint32_t)(c1&0x3F)<<6)|(c2&0x3F);return 3;}unsigned char c3=(unsigned char)p[3];if((c3&0xC0)!=0x80){*out=c;return 1;}*out=((uint32_t)(c&0x07)<<18)|((uint32_t)(c1&0x3F)<<12)|((uint32_t)(c2&0x3F)<<6)|(c3&0x3F);return 4;}511511
static inline int sp_utf8_encode(uint32_t cp,char*out){if(cp<0x80){out[0]=(char)cp;return 1;}if(cp<0x800){out[0]=(char)(0xC0|(cp>>6));out[1]=(char)(0x80|(cp&0x3F));return 2;}if(cp<0x10000){out[0]=(char)(0xE0|(cp>>12));out[1]=(char)(0x80|((cp>>6)&0x3F));out[2]=(char)(0x80|(cp&0x3F));return 3;}out[0]=(char)(0xF0|(cp>>18));out[1]=(char)(0x80|((cp>>12)&0x3F));out[2]=(char)(0x80|((cp>>6)&0x3F));out[3]=(char)(0x80|(cp&0x3F));return 4;}512+
/* Issue #882: `"hello" << 33` should append the character with513+
that codepoint, not the decimal digits. UTF-8 encode (1..4 bytes)514+
and return a NUL-terminated string. */515+
static const char *sp_int_codepoint_to_str(mrb_int n) {516+
char *s = sp_str_alloc_raw(5);517+
if (n < 0 || n > 0x10FFFF) { s[0] = 0; return s; }518+
int len = sp_utf8_encode((uint32_t)n, s);519+
s[len] = 0;520+
return s;521+
}512522
/* Direct-mapped pointer-keyed cache for (byte_len, char_len). Populated lazily513523
by sp_str_length / sp_utf8_byte_offset; the same entries unlock both calls514524
so iterating a single string with `s.length` + `s[i]` walks UTF-8 oncespinel_codegen.rbmodifiedView file
Loading diff…
test/string_lshift_int_codepoint.rbaddedView file
Loading diff…
test/string_lshift_int_codepoint.rb.expectedaddedView file
Loading diff…