Commit 83f93d0c

83f93d0cd5b3Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · ~3 modified

Description

String#dump as the inverse of String#undump

Add sp_str_dump (double-quoted, escaped form that sp_str_undump reverses; UTF-8 high bytes pass through so a round-trip is byte-exact) and dispatch String#dump / #undump in both passes. JSON.dump (a JSON receiver) is unaffected.

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

Details

Commit
83f93d0cd5b3
Parent
2e40ef97c00e

lib/sp_runtime.hmodifiedView file

@@ -1302,6 +1302,33 @@
13021302 \" \\ \# \xHH \uHHHH \u{...}) are decoded back to bytes. The decoded
13031303 string is never longer than the dumped form, so one buffer suffices. */
13041304 static int _sp_hexval(unsigned char d){return (d<='9')?(d-'0'):(tolower(d)-'a'+10);}
1305+/* String#dump: a double-quoted, escaped form that sp_str_undump reverses.
1306+ UTF-8 high bytes pass through literally (undump copies them back), so a
1307+ dump/undump round-trip is byte-identical. */
1308+static const char*sp_str_dump(const char*s){
1309+ if(!s)return sp_str_empty;
1310+ size_t n=strlen(s);
1311+ char*out=sp_str_alloc_raw(n*4+3);size_t oi=0;
1312+ out[oi++]='"';
1313+ for(size_t i=0;i<n;i++){
1314+ unsigned char c=(unsigned char)s[i];
1315+ if(c=='"'){out[oi++]='\\';out[oi++]='"';}
1316+ else if(c=='\\'){out[oi++]='\\';out[oi++]='\\';}
1317+ else if(c=='#'){out[oi++]='\\';out[oi++]='#';}
1318+ else if(c=='\n'){out[oi++]='\\';out[oi++]='n';}
1319+ else if(c=='\t'){out[oi++]='\\';out[oi++]='t';}
1320+ else if(c=='\r'){out[oi++]='\\';out[oi++]='r';}
1321+ else if(c=='\f'){out[oi++]='\\';out[oi++]='f';}
1322+ else if(c=='\v'){out[oi++]='\\';out[oi++]='v';}
1323+ else if(c=='\a'){out[oi++]='\\';out[oi++]='a';}
1324+ else if(c=='\b'){out[oi++]='\\';out[oi++]='b';}
1325+ else if(c==27){out[oi++]='\\';out[oi++]='e';}
1326+ else if(c==0){out[oi++]='\\';out[oi++]='0';}
1327+ else if(c<0x20){oi+=(size_t)sprintf(out+oi,"\\x%02X",c);}
1328+ else{out[oi++]=(char)c;}
1329+ }
1330+ out[oi++]='"';out[oi]=0;return out;
1331+}
13051332 static const char*sp_str_undump(const char*s){
13061333 if(!s)return sp_str_empty;
13071334 size_t n=strlen(s);