Last active
June 30, 2016 22:34
-
-
Save Ke-/5d536cc2e9b196b3629585cfc2ae1754 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*///////////////////////////////////////////////////////////////////////////// | |
| // | |
| // JSON encoder for Lasso 9 (UTF-8) | |
| // | |
| /////////////////////////////////////////////////////////////////////////////// | |
| Skips encoding non-ASCII characters instead relies | |
| on requirement specified in the spec. | |
| From the spec: http://www.ietf.org/rfc/rfc4627.txt | |
| " 2.5 Any character * may * be escaped. " | |
| " 3. JSON text SHALL be encoded in Unicode. The default encoding is UTF-8." | |
| Performance: 5x - 20x+ faster than default encoder depending on data. | |
| /////////////////////////////////////////////////////////////////////////////*/ | |
| define json_encode_utf8 => type { | |
| data private out = '' | |
| public oncreate(val) => { | |
| .encode(#val) | |
| return .out | |
| } | |
| protected append(p::string) => .'out'->append(#p) | |
| protected appendcomma() => .append(',') | |
| protected appendcolon() => .append(':') | |
| protected encode(p::trait_keyedforeach,c=0) => { | |
| .append('{') | |
| #p->foreachpair => { | |
| #c ? .appendcomma | #c = 1 | |
| .encode(#1->first->asstring) | |
| .appendcolon | |
| .encode(#1->second) | |
| } | |
| .append('}') | |
| } | |
| protected encode(p::trait_positionallykeyed,c=0) => { | |
| .append('[') | |
| #p->foreach => { | |
| #c ? .appendComma | #c = 1 | |
| .encode(#1) | |
| } | |
| .append(']') | |
| } | |
| protected encode(p::string) => { | |
| // Don't modify original string (!) | |
| #p = #p->ascopy | |
| // We could also remove escape characters here: | |
| // #p->replace('\0',``) | |
| // #p->replace('\v',``) | |
| // #p->replace('\e',``) | |
| #p->replace('\\',`\\`) | |
| #p->replace('\"',`\"`) | |
| #p->replace('\b',`\b`) | |
| #p->replace('\f',`\f`) | |
| #p->replace('\n',`\n`) | |
| #p->replace('\r',`\r`) | |
| #p->replace('\t',`\t`) | |
| .append('"') | |
| .append(#p) | |
| .append('"') | |
| } | |
| protected encode(i::integer) => .append(#i->asstring) | |
| protected encode(d::decimal) => .append(#d->asstring) | |
| protected encode(b::boolean) => .append(#b ? 'true' | 'false') | |
| protected encode(n::null) => .append('null') | |
| protected encode(n::void) => .append('null') | |
| protected encode(o) => .encode(#o->asstring) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment