ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
Revision: 1.28
Committed: Wed Apr 11 12:23:02 2007 UTC (17 years, 1 month ago) by root
Branch: MAIN
Changes since 1.27: +2 -3 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 #include "EXTERN.h"
2     #include "perl.h"
3     #include "XSUB.h"
4    
5     #include "assert.h"
6     #include "string.h"
7     #include "stdlib.h"
8 root 1.26 #include "stdio.h"
9    
10     #if defined(__BORLANDC__) || defined(_MSC_VER)
11     # define snprintf _snprintf // C compilers have this in stdio.h
12     #endif
13 root 1.1
14 root 1.18 #define F_ASCII 0x00000001UL
15     #define F_UTF8 0x00000002UL
16     #define F_INDENT 0x00000004UL
17     #define F_CANONICAL 0x00000008UL
18     #define F_SPACE_BEFORE 0x00000010UL
19     #define F_SPACE_AFTER 0x00000020UL
20     #define F_ALLOW_NONREF 0x00000080UL
21     #define F_SHRINK 0x00000100UL
22     #define F_MAXDEPTH 0xf8000000UL
23     #define S_MAXDEPTH 27
24    
25     #define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
26    
27     // F_SELFCONVERT? <=> to_json/toJson
28     // F_BLESSED? <=> { $__class__$ => }
29 root 1.16
30 root 1.2 #define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
31 root 1.24 #define F_DEFAULT (9UL << S_MAXDEPTH)
32 root 1.1
33     #define INIT_SIZE 32 // initial scalar size to be allocated
34 root 1.12 #define INDENT_STEP 3 // spaces per indentation level
35    
36 root 1.14 #define SHORT_STRING_LEN 512 // special-case strings of up to this size
37 root 1.1
38     #define SB do {
39     #define SE } while (0)
40    
41 root 1.12 static HV *json_stash; // JSON::XS::
42 root 1.1
43 root 1.12 /////////////////////////////////////////////////////////////////////////////
44     // utility functions
45 root 1.1
46     static UV *
47     SvJSON (SV *sv)
48     {
49     if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
50     croak ("object is not of type JSON::XS");
51    
52     return &SvUVX (SvRV (sv));
53     }
54    
55 root 1.7 static void
56     shrink (SV *sv)
57     {
58     sv_utf8_downgrade (sv, 1);
59 root 1.12 if (SvLEN (sv) > SvCUR (sv) + 1)
60     {
61 root 1.7 #ifdef SvPV_shrink_to_cur
62 root 1.12 SvPV_shrink_to_cur (sv);
63     #elif defined (SvPV_renew)
64     SvPV_renew (sv, SvCUR (sv) + 1);
65 root 1.7 #endif
66 root 1.12 }
67 root 1.7 }
68    
69 root 1.13 // decode an utf-8 character and return it, or (UV)-1 in
70     // case of an error.
71     // we special-case "safe" characters from U+80 .. U+7FF,
72     // but use the very good perl function to parse anything else.
73     // note that we never call this function for a ascii codepoints
74     static UV
75     decode_utf8 (unsigned char *s, STRLEN len, STRLEN *clen)
76     {
77     if (s[0] > 0xdf || s[0] < 0xc2)
78     return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY);
79     else if (len > 1 && s[1] >= 0x80 && s[1] <= 0xbf)
80     {
81     *clen = 2;
82     return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
83     }
84     else
85 root 1.23 {
86     *clen = (STRLEN)-1;
87     return (UV)-1;
88     }
89 root 1.13 }
90    
91 root 1.1 /////////////////////////////////////////////////////////////////////////////
92 root 1.12 // encoder
93    
94     // structure used for encoding JSON
95     typedef struct
96     {
97     char *cur; // SvPVX (sv) + current output position
98     char *end; // SvEND (sv)
99     SV *sv; // result scalar
100 root 1.18 U32 flags; // F_*
101     U32 indent; // indentation level
102     U32 maxdepth; // max. indentation/recursion level
103 root 1.12 } enc_t;
104 root 1.1
105     static void
106     need (enc_t *enc, STRLEN len)
107     {
108     if (enc->cur + len >= enc->end)
109     {
110     STRLEN cur = enc->cur - SvPVX (enc->sv);
111     SvGROW (enc->sv, cur + len + 1);
112     enc->cur = SvPVX (enc->sv) + cur;
113 root 1.27 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
114 root 1.1 }
115     }
116    
117     static void
118     encode_ch (enc_t *enc, char ch)
119     {
120     need (enc, 1);
121     *enc->cur++ = ch;
122     }
123    
124     static void
125     encode_str (enc_t *enc, char *str, STRLEN len, int is_utf8)
126     {
127     char *end = str + len;
128    
129 root 1.4 need (enc, len);
130    
131 root 1.1 while (str < end)
132     {
133     unsigned char ch = *(unsigned char *)str;
134 root 1.4
135 root 1.6 if (ch >= 0x20 && ch < 0x80) // most common case
136 root 1.4 {
137 root 1.6 if (ch == '"') // but with slow exceptions
138     {
139     need (enc, len += 1);
140     *enc->cur++ = '\\';
141     *enc->cur++ = '"';
142     }
143     else if (ch == '\\')
144     {
145     need (enc, len += 1);
146     *enc->cur++ = '\\';
147     *enc->cur++ = '\\';
148     }
149     else
150     *enc->cur++ = ch;
151    
152 root 1.4 ++str;
153 root 1.1 }
154     else
155     {
156 root 1.6 switch (ch)
157 root 1.1 {
158 root 1.6 case '\010': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'b'; ++str; break;
159     case '\011': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 't'; ++str; break;
160     case '\012': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'n'; ++str; break;
161     case '\014': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'f'; ++str; break;
162     case '\015': need (enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'r'; ++str; break;
163 root 1.1
164 root 1.6 default:
165 root 1.1 {
166 root 1.6 STRLEN clen;
167     UV uch;
168    
169     if (is_utf8)
170     {
171 root 1.13 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
172     uch = decode_utf8 (str, end - str, &clen);
173 root 1.6 if (clen == (STRLEN)-1)
174 root 1.9 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
175 root 1.6 }
176     else
177     {
178     uch = ch;
179     clen = 1;
180     }
181    
182 root 1.9 if (uch > 0x10FFFFUL)
183     croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
184    
185 root 1.6 if (uch < 0x80 || enc->flags & F_ASCII)
186     {
187     if (uch > 0xFFFFUL)
188     {
189     need (enc, len += 11);
190     sprintf (enc->cur, "\\u%04x\\u%04x",
191 root 1.10 (int)((uch - 0x10000) / 0x400 + 0xD800),
192     (int)((uch - 0x10000) % 0x400 + 0xDC00));
193 root 1.6 enc->cur += 12;
194     }
195     else
196     {
197     static char hexdigit [16] = "0123456789abcdef";
198     need (enc, len += 5);
199     *enc->cur++ = '\\';
200     *enc->cur++ = 'u';
201     *enc->cur++ = hexdigit [ uch >> 12 ];
202     *enc->cur++ = hexdigit [(uch >> 8) & 15];
203     *enc->cur++ = hexdigit [(uch >> 4) & 15];
204     *enc->cur++ = hexdigit [(uch >> 0) & 15];
205     }
206 root 1.4
207 root 1.6 str += clen;
208     }
209     else if (is_utf8)
210     {
211     need (enc, len += clen);
212     do
213     {
214     *enc->cur++ = *str++;
215     }
216     while (--clen);
217     }
218     else
219     {
220 root 1.28 need (enc, len += UTF8_MAXBYTES - 1); // never more than 11 bytes needed
221 root 1.6 enc->cur = uvuni_to_utf8_flags (enc->cur, uch, 0);
222     ++str;
223     }
224 root 1.5 }
225 root 1.4 }
226 root 1.1 }
227    
228     --len;
229     }
230     }
231    
232 root 1.12 static void
233     encode_indent (enc_t *enc)
234     {
235     if (enc->flags & F_INDENT)
236     {
237     int spaces = enc->indent * INDENT_STEP;
238    
239     need (enc, spaces);
240     memset (enc->cur, ' ', spaces);
241     enc->cur += spaces;
242     }
243     }
244    
245     static void
246     encode_space (enc_t *enc)
247     {
248     need (enc, 1);
249     encode_ch (enc, ' ');
250     }
251    
252     static void
253     encode_nl (enc_t *enc)
254     {
255     if (enc->flags & F_INDENT)
256     {
257     need (enc, 1);
258     encode_ch (enc, '\n');
259     }
260     }
261    
262     static void
263     encode_comma (enc_t *enc)
264     {
265     encode_ch (enc, ',');
266 root 1.1
267 root 1.12 if (enc->flags & F_INDENT)
268     encode_nl (enc);
269     else if (enc->flags & F_SPACE_AFTER)
270     encode_space (enc);
271     }
272 root 1.1
273     static void encode_sv (enc_t *enc, SV *sv);
274    
275     static void
276     encode_av (enc_t *enc, AV *av)
277     {
278     int i, len = av_len (av);
279    
280 root 1.21 if (enc->indent >= enc->maxdepth)
281     croak ("data structure too deep (hit recursion limit)");
282    
283 root 1.12 encode_ch (enc, '['); encode_nl (enc);
284 root 1.1 ++enc->indent;
285    
286     for (i = 0; i <= len; ++i)
287     {
288 root 1.12 encode_indent (enc);
289 root 1.1 encode_sv (enc, *av_fetch (av, i, 0));
290    
291     if (i < len)
292 root 1.12 encode_comma (enc);
293 root 1.1 }
294    
295 root 1.12 encode_nl (enc);
296 root 1.1
297     --enc->indent;
298 root 1.12 encode_indent (enc); encode_ch (enc, ']');
299 root 1.1 }
300    
301     static void
302     encode_he (enc_t *enc, HE *he)
303     {
304     encode_ch (enc, '"');
305    
306     if (HeKLEN (he) == HEf_SVKEY)
307     {
308     SV *sv = HeSVKEY (he);
309     STRLEN len;
310 root 1.4 char *str;
311    
312     SvGETMAGIC (sv);
313     str = SvPV (sv, len);
314 root 1.1
315     encode_str (enc, str, len, SvUTF8 (sv));
316     }
317     else
318     encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
319    
320     encode_ch (enc, '"');
321    
322 root 1.12 if (enc->flags & F_SPACE_BEFORE) encode_space (enc);
323 root 1.1 encode_ch (enc, ':');
324 root 1.12 if (enc->flags & F_SPACE_AFTER ) encode_space (enc);
325 root 1.1 encode_sv (enc, HeVAL (he));
326     }
327    
328     // compare hash entries, used when all keys are bytestrings
329     static int
330     he_cmp_fast (const void *a_, const void *b_)
331     {
332     int cmp;
333    
334     HE *a = *(HE **)a_;
335     HE *b = *(HE **)b_;
336    
337     STRLEN la = HeKLEN (a);
338     STRLEN lb = HeKLEN (b);
339    
340 root 1.11 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb)))
341     cmp = la - lb;
342 root 1.1
343     return cmp;
344     }
345    
346     // compare hash entries, used when some keys are sv's or utf-x
347     static int
348     he_cmp_slow (const void *a, const void *b)
349     {
350     return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b));
351     }
352    
353     static void
354     encode_hv (enc_t *enc, HV *hv)
355     {
356     int count, i;
357    
358 root 1.21 if (enc->indent >= enc->maxdepth)
359     croak ("data structure too deep (hit recursion limit)");
360    
361 root 1.12 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent;
362 root 1.1
363     if ((count = hv_iterinit (hv)))
364     {
365     // for canonical output we have to sort by keys first
366     // actually, this is mostly due to the stupid so-called
367     // security workaround added somewhere in 5.8.x.
368     // that randomises hash orderings
369     if (enc->flags & F_CANONICAL)
370     {
371 root 1.12 HE *he, *hes [count]; // if your compiler dies here, you need to enable C99 mode
372 root 1.1 int fast = 1;
373    
374     i = 0;
375     while ((he = hv_iternext (hv)))
376     {
377     hes [i++] = he;
378     if (HeKLEN (he) < 0 || HeKUTF8 (he))
379     fast = 0;
380     }
381    
382     assert (i == count);
383    
384     if (fast)
385     qsort (hes, count, sizeof (HE *), he_cmp_fast);
386     else
387     {
388 root 1.8 // hack to forcefully disable "use bytes"
389     COP cop = *PL_curcop;
390 root 1.1 cop.op_private = 0;
391 root 1.8
392     ENTER;
393     SAVETMPS;
394    
395     SAVEVPTR (PL_curcop);
396 root 1.1 PL_curcop = &cop;
397    
398     qsort (hes, count, sizeof (HE *), he_cmp_slow);
399 root 1.8
400 root 1.1 FREETMPS;
401 root 1.8 LEAVE;
402 root 1.1 }
403    
404     for (i = 0; i < count; ++i)
405     {
406 root 1.12 encode_indent (enc);
407 root 1.1 encode_he (enc, hes [i]);
408    
409     if (i < count - 1)
410 root 1.12 encode_comma (enc);
411 root 1.1 }
412    
413 root 1.12 encode_nl (enc);
414 root 1.1 }
415     else
416     {
417     HE *he = hv_iternext (hv);
418    
419     for (;;)
420     {
421 root 1.12 encode_indent (enc);
422 root 1.1 encode_he (enc, he);
423    
424     if (!(he = hv_iternext (hv)))
425     break;
426    
427 root 1.12 encode_comma (enc);
428 root 1.1 }
429    
430 root 1.12 encode_nl (enc);
431 root 1.1 }
432     }
433    
434 root 1.12 --enc->indent; encode_indent (enc); encode_ch (enc, '}');
435 root 1.1 }
436    
437 root 1.21 // encode objects, arrays and special \0=false and \1=true values.
438     static void
439     encode_rv (enc_t *enc, SV *sv)
440     {
441 root 1.25 svtype svt;
442    
443 root 1.21 SvGETMAGIC (sv);
444 root 1.25 svt = SvTYPE (sv);
445 root 1.21
446     if (svt == SVt_PVHV)
447     encode_hv (enc, (HV *)sv);
448     else if (svt == SVt_PVAV)
449     encode_av (enc, (AV *)sv);
450     else if (svt < SVt_PVAV)
451     {
452     if (SvNIOK (sv) && SvIV (sv) == 0)
453     encode_str (enc, "false", 5, 0);
454     else if (SvNIOK (sv) && SvIV (sv) == 1)
455     encode_str (enc, "true", 4, 0);
456     else
457     croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
458     SvPV_nolen (sv_2mortal (newRV_inc (sv))));
459     }
460     else
461     croak ("encountered %s, but JSON can only represent references to arrays or hashes",
462     SvPV_nolen (sv_2mortal (newRV_inc (sv))));
463     }
464    
465 root 1.1 static void
466     encode_sv (enc_t *enc, SV *sv)
467     {
468 root 1.4 SvGETMAGIC (sv);
469    
470 root 1.1 if (SvPOKp (sv))
471     {
472     STRLEN len;
473     char *str = SvPV (sv, len);
474     encode_ch (enc, '"');
475     encode_str (enc, str, len, SvUTF8 (sv));
476     encode_ch (enc, '"');
477     }
478     else if (SvNOKp (sv))
479     {
480     need (enc, NV_DIG + 32);
481     Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
482     enc->cur += strlen (enc->cur);
483     }
484     else if (SvIOKp (sv))
485     {
486     need (enc, 64);
487     enc->cur +=
488     SvIsUV(sv)
489     ? snprintf (enc->cur, 64, "%"UVuf, (UV)SvUVX (sv))
490     : snprintf (enc->cur, 64, "%"IVdf, (IV)SvIVX (sv));
491     }
492     else if (SvROK (sv))
493 root 1.21 encode_rv (enc, SvRV (sv));
494 root 1.1 else if (!SvOK (sv))
495     encode_str (enc, "null", 4, 0);
496     else
497 root 1.9 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
498     SvPV_nolen (sv), SvFLAGS (sv));
499 root 1.1 }
500    
501     static SV *
502 root 1.18 encode_json (SV *scalar, U32 flags)
503 root 1.1 {
504 root 1.25 enc_t enc;
505    
506 root 1.3 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar))
507 root 1.9 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
508 root 1.3
509 root 1.12 enc.flags = flags;
510     enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
511     enc.cur = SvPVX (enc.sv);
512     enc.end = SvEND (enc.sv);
513     enc.indent = 0;
514 root 1.18 enc.maxdepth = DEC_DEPTH (flags);
515 root 1.1
516     SvPOK_only (enc.sv);
517     encode_sv (&enc, scalar);
518    
519     if (!(flags & (F_ASCII | F_UTF8)))
520     SvUTF8_on (enc.sv);
521    
522     SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
523 root 1.27 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
524 root 1.6
525     if (enc.flags & F_SHRINK)
526 root 1.7 shrink (enc.sv);
527    
528 root 1.1 return enc.sv;
529     }
530    
531     /////////////////////////////////////////////////////////////////////////////
532 root 1.12 // decoder
533 root 1.1
534 root 1.12 // structure used for decoding JSON
535     typedef struct
536     {
537     char *cur; // current parser pointer
538     char *end; // end of input string
539     const char *err; // parse error, if != 0
540 root 1.18 U32 flags; // F_*
541     U32 depth; // recursion depth
542     U32 maxdepth; // recursion depth limit
543 root 1.12 } dec_t;
544    
545     static void
546     decode_ws (dec_t *dec)
547     {
548     for (;;)
549     {
550     char ch = *dec->cur;
551    
552     if (ch > 0x20
553     || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09))
554     break;
555    
556     ++dec->cur;
557 root 1.1 }
558 root 1.12 }
559 root 1.1
560     #define ERR(reason) SB dec->err = reason; goto fail; SE
561 root 1.18
562 root 1.1 #define EXPECT_CH(ch) SB \
563     if (*dec->cur != ch) \
564     ERR (# ch " expected"); \
565     ++dec->cur; \
566     SE
567    
568 root 1.18 #define DEC_INC_DEPTH if (++dec->depth > dec->maxdepth) ERR ("json datastructure exceeds maximum nesting level (set a higher max_depth)")
569     #define DEC_DEC_DEPTH --dec->depth
570    
571 root 1.1 static SV *decode_sv (dec_t *dec);
572    
573     static signed char decode_hexdigit[256];
574    
575     static UV
576     decode_4hex (dec_t *dec)
577     {
578     signed char d1, d2, d3, d4;
579 root 1.12 unsigned char *cur = (unsigned char *)dec->cur;
580 root 1.1
581 root 1.12 d1 = decode_hexdigit [cur [0]]; if (d1 < 0) ERR ("four hexadecimal digits expected");
582     d2 = decode_hexdigit [cur [1]]; if (d2 < 0) ERR ("four hexadecimal digits expected");
583     d3 = decode_hexdigit [cur [2]]; if (d3 < 0) ERR ("four hexadecimal digits expected");
584     d4 = decode_hexdigit [cur [3]]; if (d4 < 0) ERR ("four hexadecimal digits expected");
585 root 1.1
586     dec->cur += 4;
587    
588     return ((UV)d1) << 12
589     | ((UV)d2) << 8
590     | ((UV)d3) << 4
591     | ((UV)d4);
592    
593     fail:
594     return (UV)-1;
595     }
596    
597     static SV *
598     decode_str (dec_t *dec)
599     {
600 root 1.12 SV *sv = 0;
601 root 1.1 int utf8 = 0;
602    
603 root 1.12 do
604 root 1.1 {
605 root 1.28 char buf [SHORT_STRING_LEN + UTF8_MAXBYTES];
606 root 1.12 char *cur = buf;
607 root 1.1
608 root 1.12 do
609 root 1.1 {
610 root 1.12 unsigned char ch = *(unsigned char *)dec->cur++;
611    
612     if (ch == '"')
613     {
614     --dec->cur;
615     break;
616     }
617     else if (ch == '\\')
618 root 1.1 {
619 root 1.12 switch (*dec->cur)
620 root 1.1 {
621 root 1.12 case '\\':
622     case '/':
623     case '"': *cur++ = *dec->cur++; break;
624    
625     case 'b': ++dec->cur; *cur++ = '\010'; break;
626     case 't': ++dec->cur; *cur++ = '\011'; break;
627     case 'n': ++dec->cur; *cur++ = '\012'; break;
628     case 'f': ++dec->cur; *cur++ = '\014'; break;
629     case 'r': ++dec->cur; *cur++ = '\015'; break;
630 root 1.1
631 root 1.12 case 'u':
632 root 1.1 {
633 root 1.12 UV lo, hi;
634     ++dec->cur;
635 root 1.1
636 root 1.12 hi = decode_4hex (dec);
637     if (hi == (UV)-1)
638     goto fail;
639 root 1.1
640 root 1.12 // possibly a surrogate pair
641     if (hi >= 0xd800)
642     if (hi < 0xdc00)
643     {
644     if (dec->cur [0] != '\\' || dec->cur [1] != 'u')
645     ERR ("missing low surrogate character in surrogate pair");
646    
647     dec->cur += 2;
648    
649     lo = decode_4hex (dec);
650     if (lo == (UV)-1)
651     goto fail;
652    
653     if (lo < 0xdc00 || lo >= 0xe000)
654     ERR ("surrogate pair expected");
655    
656     hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000;
657     }
658     else if (hi < 0xe000)
659     ERR ("missing high surrogate character in surrogate pair");
660 root 1.1
661 root 1.12 if (hi >= 0x80)
662     {
663     utf8 = 1;
664 root 1.1
665 root 1.12 cur = (char *)uvuni_to_utf8_flags (cur, hi, 0);
666     }
667     else
668     *cur++ = hi;
669 root 1.1 }
670 root 1.12 break;
671    
672     default:
673     --dec->cur;
674     ERR ("illegal backslash escape sequence in string");
675     }
676     }
677     else if (ch >= 0x20 && ch <= 0x7f)
678     *cur++ = ch;
679     else if (ch >= 0x80)
680     {
681 root 1.25 STRLEN clen;
682     UV uch;
683    
684 root 1.12 --dec->cur;
685 root 1.1
686 root 1.25 uch = decode_utf8 (dec->cur, dec->end - dec->cur, &clen);
687 root 1.12 if (clen == (STRLEN)-1)
688     ERR ("malformed UTF-8 character in JSON string");
689 root 1.1
690 root 1.12 do
691 root 1.23 *cur++ = *dec->cur++;
692 root 1.12 while (--clen);
693 root 1.5
694 root 1.12 utf8 = 1;
695 root 1.1 }
696 root 1.12 else
697 root 1.23 {
698     --dec->cur;
699 root 1.12
700 root 1.23 if (!ch)
701 root 1.24 ERR ("unexpected end of string while parsing JSON string");
702 root 1.23 else
703 root 1.24 ERR ("invalid character encountered while parsing JSON string");
704 root 1.23 }
705 root 1.1 }
706 root 1.12 while (cur < buf + SHORT_STRING_LEN);
707 root 1.1
708 root 1.25 {
709     STRLEN len = cur - buf;
710 root 1.5
711 root 1.25 if (sv)
712     {
713     SvGROW (sv, SvCUR (sv) + len + 1);
714     memcpy (SvPVX (sv) + SvCUR (sv), buf, len);
715     SvCUR_set (sv, SvCUR (sv) + len);
716     }
717     else
718     sv = newSVpvn (buf, len);
719     }
720 root 1.1 }
721 root 1.12 while (*dec->cur != '"');
722 root 1.1
723     ++dec->cur;
724    
725 root 1.12 if (sv)
726     {
727     SvPOK_only (sv);
728     *SvEND (sv) = 0;
729 root 1.4
730 root 1.12 if (utf8)
731     SvUTF8_on (sv);
732     }
733     else
734     sv = newSVpvn ("", 0);
735 root 1.6
736 root 1.1 return sv;
737    
738     fail:
739     return 0;
740     }
741    
742     static SV *
743     decode_num (dec_t *dec)
744     {
745     int is_nv = 0;
746     char *start = dec->cur;
747    
748     // [minus]
749     if (*dec->cur == '-')
750     ++dec->cur;
751    
752     if (*dec->cur == '0')
753     {
754     ++dec->cur;
755     if (*dec->cur >= '0' && *dec->cur <= '9')
756     ERR ("malformed number (leading zero must not be followed by another digit)");
757     }
758 root 1.5 else if (*dec->cur < '0' || *dec->cur > '9')
759     ERR ("malformed number (no digits after initial minus)");
760     else
761     do
762     {
763     ++dec->cur;
764     }
765     while (*dec->cur >= '0' && *dec->cur <= '9');
766 root 1.1
767     // [frac]
768     if (*dec->cur == '.')
769     {
770 root 1.5 ++dec->cur;
771    
772     if (*dec->cur < '0' || *dec->cur > '9')
773     ERR ("malformed number (no digits after decimal point)");
774 root 1.1
775     do
776     {
777     ++dec->cur;
778     }
779     while (*dec->cur >= '0' && *dec->cur <= '9');
780 root 1.5
781     is_nv = 1;
782 root 1.1 }
783    
784     // [exp]
785     if (*dec->cur == 'e' || *dec->cur == 'E')
786     {
787 root 1.5 ++dec->cur;
788 root 1.1
789     if (*dec->cur == '-' || *dec->cur == '+')
790     ++dec->cur;
791    
792 root 1.5 if (*dec->cur < '0' || *dec->cur > '9')
793     ERR ("malformed number (no digits after exp sign)");
794    
795     do
796     {
797     ++dec->cur;
798     }
799     while (*dec->cur >= '0' && *dec->cur <= '9');
800    
801     is_nv = 1;
802 root 1.1 }
803    
804     if (!is_nv)
805     {
806     UV uv;
807     int numtype = grok_number (start, dec->cur - start, &uv);
808     if (numtype & IS_NUMBER_IN_UV)
809     if (numtype & IS_NUMBER_NEG)
810     {
811     if (uv < (UV)IV_MIN)
812     return newSViv (-(IV)uv);
813     }
814     else
815     return newSVuv (uv);
816     }
817    
818     return newSVnv (Atof (start));
819    
820     fail:
821     return 0;
822     }
823    
824     static SV *
825     decode_av (dec_t *dec)
826     {
827     AV *av = newAV ();
828    
829 root 1.18 DEC_INC_DEPTH;
830 root 1.12 decode_ws (dec);
831 root 1.18
832 root 1.5 if (*dec->cur == ']')
833     ++dec->cur;
834     else
835     for (;;)
836     {
837     SV *value;
838 root 1.1
839 root 1.5 value = decode_sv (dec);
840     if (!value)
841     goto fail;
842 root 1.1
843 root 1.5 av_push (av, value);
844 root 1.1
845 root 1.12 decode_ws (dec);
846 root 1.1
847 root 1.5 if (*dec->cur == ']')
848     {
849     ++dec->cur;
850     break;
851     }
852    
853     if (*dec->cur != ',')
854     ERR (", or ] expected while parsing array");
855 root 1.1
856 root 1.5 ++dec->cur;
857     }
858 root 1.1
859 root 1.18 DEC_DEC_DEPTH;
860 root 1.1 return newRV_noinc ((SV *)av);
861    
862     fail:
863     SvREFCNT_dec (av);
864 root 1.18 DEC_DEC_DEPTH;
865 root 1.1 return 0;
866     }
867    
868     static SV *
869     decode_hv (dec_t *dec)
870     {
871     HV *hv = newHV ();
872    
873 root 1.18 DEC_INC_DEPTH;
874 root 1.12 decode_ws (dec);
875 root 1.18
876 root 1.5 if (*dec->cur == '}')
877     ++dec->cur;
878     else
879     for (;;)
880     {
881     SV *key, *value;
882 root 1.1
883 root 1.12 decode_ws (dec); EXPECT_CH ('"');
884 root 1.1
885 root 1.5 key = decode_str (dec);
886     if (!key)
887     goto fail;
888 root 1.1
889 root 1.12 decode_ws (dec); EXPECT_CH (':');
890 root 1.1
891 root 1.5 value = decode_sv (dec);
892     if (!value)
893     {
894     SvREFCNT_dec (key);
895     goto fail;
896     }
897 root 1.1
898 root 1.5 hv_store_ent (hv, key, value, 0);
899 root 1.18 SvREFCNT_dec (key);
900 root 1.1
901 root 1.12 decode_ws (dec);
902 root 1.1
903 root 1.5 if (*dec->cur == '}')
904     {
905     ++dec->cur;
906     break;
907     }
908 root 1.1
909 root 1.5 if (*dec->cur != ',')
910     ERR (", or } expected while parsing object/hash");
911 root 1.1
912 root 1.5 ++dec->cur;
913     }
914 root 1.1
915 root 1.18 DEC_DEC_DEPTH;
916 root 1.1 return newRV_noinc ((SV *)hv);
917    
918     fail:
919     SvREFCNT_dec (hv);
920 root 1.18 DEC_DEC_DEPTH;
921 root 1.1 return 0;
922     }
923    
924     static SV *
925     decode_sv (dec_t *dec)
926     {
927 root 1.12 decode_ws (dec);
928 root 1.1 switch (*dec->cur)
929     {
930     case '"': ++dec->cur; return decode_str (dec);
931     case '[': ++dec->cur; return decode_av (dec);
932     case '{': ++dec->cur; return decode_hv (dec);
933    
934     case '-':
935     case '0': case '1': case '2': case '3': case '4':
936     case '5': case '6': case '7': case '8': case '9':
937     return decode_num (dec);
938    
939     case 't':
940     if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
941     {
942     dec->cur += 4;
943     return newSViv (1);
944     }
945     else
946     ERR ("'true' expected");
947    
948     break;
949    
950     case 'f':
951     if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
952     {
953     dec->cur += 5;
954     return newSViv (0);
955     }
956     else
957     ERR ("'false' expected");
958    
959     break;
960    
961     case 'n':
962     if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "null", 4))
963     {
964     dec->cur += 4;
965 root 1.5 return newSVsv (&PL_sv_undef);
966 root 1.1 }
967     else
968     ERR ("'null' expected");
969    
970     break;
971    
972     default:
973 root 1.24 ERR ("malformed JSON string, neither array, object, number, string or atom");
974 root 1.1 break;
975     }
976    
977     fail:
978     return 0;
979     }
980    
981     static SV *
982 root 1.18 decode_json (SV *string, U32 flags)
983 root 1.1 {
984 root 1.25 dec_t dec;
985 root 1.1 SV *sv;
986    
987 root 1.22 SvUPGRADE (string, SVt_PV);
988    
989 root 1.5 if (flags & F_UTF8)
990     sv_utf8_downgrade (string, 0);
991     else
992 root 1.1 sv_utf8_upgrade (string);
993    
994     SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
995    
996 root 1.18 dec.flags = flags;
997     dec.cur = SvPVX (string);
998     dec.end = SvEND (string);
999     dec.err = 0;
1000     dec.depth = 0;
1001     dec.maxdepth = DEC_DEPTH (dec.flags);
1002 root 1.1
1003 root 1.20 *dec.end = 0; // this should basically be a nop, too, but make sure its there
1004 root 1.1 sv = decode_sv (&dec);
1005    
1006     if (!sv)
1007     {
1008 root 1.7 IV offset = dec.flags & F_UTF8
1009     ? dec.cur - SvPVX (string)
1010     : utf8_distance (dec.cur, SvPVX (string));
1011 root 1.1 SV *uni = sv_newmortal ();
1012 root 1.8
1013 root 1.5 // horrible hack to silence warning inside pv_uni_display
1014 root 1.8 COP cop = *PL_curcop;
1015 root 1.5 cop.cop_warnings = pWARN_NONE;
1016 root 1.8 ENTER;
1017 root 1.5 SAVEVPTR (PL_curcop);
1018     PL_curcop = &cop;
1019 root 1.8 pv_uni_display (uni, dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ);
1020     LEAVE;
1021 root 1.1
1022 root 1.23 croak ("%s, at character offset %d [\"%s\"]",
1023 root 1.1 dec.err,
1024     (int)offset,
1025     dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1026     }
1027    
1028 root 1.3 sv = sv_2mortal (sv);
1029    
1030     if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv))
1031 root 1.9 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
1032 root 1.3
1033     return sv;
1034 root 1.1 }
1035    
1036 root 1.12 /////////////////////////////////////////////////////////////////////////////
1037     // XS interface functions
1038    
1039 root 1.1 MODULE = JSON::XS PACKAGE = JSON::XS
1040    
1041     BOOT:
1042     {
1043     int i;
1044    
1045     memset (decode_hexdigit, 0xff, 256);
1046    
1047 root 1.18 for (i = 0; i < 256; ++i)
1048     decode_hexdigit [i] =
1049     i >= '0' && i <= '9' ? i - '0'
1050     : i >= 'a' && i <= 'f' ? i - 'a' + 10
1051     : i >= 'A' && i <= 'F' ? i - 'A' + 10
1052     : -1;
1053 root 1.1
1054     json_stash = gv_stashpv ("JSON::XS", 1);
1055     }
1056    
1057 root 1.4 PROTOTYPES: DISABLE
1058    
1059 root 1.1 SV *new (char *dummy)
1060     CODE:
1061     RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash);
1062     OUTPUT:
1063     RETVAL
1064    
1065 root 1.6 SV *ascii (SV *self, int enable = 1)
1066 root 1.1 ALIAS:
1067     ascii = F_ASCII
1068     utf8 = F_UTF8
1069     indent = F_INDENT
1070     canonical = F_CANONICAL
1071     space_before = F_SPACE_BEFORE
1072     space_after = F_SPACE_AFTER
1073 root 1.2 pretty = F_PRETTY
1074 root 1.3 allow_nonref = F_ALLOW_NONREF
1075 root 1.6 shrink = F_SHRINK
1076 root 1.1 CODE:
1077     {
1078     UV *uv = SvJSON (self);
1079     if (enable)
1080     *uv |= ix;
1081     else
1082     *uv &= ~ix;
1083    
1084     RETVAL = newSVsv (self);
1085     }
1086     OUTPUT:
1087     RETVAL
1088    
1089 root 1.25 SV *max_depth (SV *self, UV max_depth = 0x80000000UL)
1090 root 1.18 CODE:
1091     {
1092     UV *uv = SvJSON (self);
1093     UV log2 = 0;
1094    
1095     if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1096    
1097     while ((1UL << log2) < max_depth)
1098     ++log2;
1099    
1100     *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1101    
1102     RETVAL = newSVsv (self);
1103     }
1104     OUTPUT:
1105     RETVAL
1106    
1107 root 1.1 void encode (SV *self, SV *scalar)
1108     PPCODE:
1109     XPUSHs (encode_json (scalar, *SvJSON (self)));
1110    
1111 root 1.2 void decode (SV *self, SV *jsonstr)
1112 root 1.1 PPCODE:
1113 root 1.2 XPUSHs (decode_json (jsonstr, *SvJSON (self)));
1114    
1115 root 1.4 PROTOTYPES: ENABLE
1116    
1117 root 1.2 void to_json (SV *scalar)
1118 root 1.15 ALIAS:
1119     objToJson = 0
1120 root 1.2 PPCODE:
1121 root 1.18 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8));
1122 root 1.2
1123     void from_json (SV *jsonstr)
1124 root 1.15 ALIAS:
1125     jsonToObj = 0
1126 root 1.2 PPCODE:
1127 root 1.18 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8));
1128 root 1.1