ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.xs
(Generate patch)

Comparing JSON-XS/XS.xs (file contents):
Revision 1.38 by root, Mon Jun 11 03:18:07 2007 UTC vs.
Revision 1.67 by root, Wed Nov 28 14:01:01 2007 UTC

1#include "EXTERN.h" 1#include "EXTERN.h"
2#include "perl.h" 2#include "perl.h"
3#include "XSUB.h" 3#include "XSUB.h"
4 4
5#include "assert.h" 5#include <assert.h>
6#include "string.h" 6#include <string.h>
7#include "stdlib.h" 7#include <stdlib.h>
8#include "stdio.h" 8#include <stdio.h>
9#include <float.h>
9 10
10#if defined(__BORLANDC__) || defined(_MSC_VER) 11#if defined(__BORLANDC__) || defined(_MSC_VER)
11# define snprintf _snprintf // C compilers have this in stdio.h 12# define snprintf _snprintf // C compilers have this in stdio.h
12#endif 13#endif
13 14
15// some old perls do not have this, try to make it work, no
16// guarentees, though. if it breaks, you get to keep the pieces.
17#ifndef UTF8_MAXBYTES
18# define UTF8_MAXBYTES 13
19#endif
20
14#define F_ASCII 0x00000001UL 21#define F_ASCII 0x00000001UL
15#define F_LATIN1 0x00000002UL 22#define F_LATIN1 0x00000002UL
16#define F_UTF8 0x00000004UL 23#define F_UTF8 0x00000004UL
17#define F_INDENT 0x00000008UL 24#define F_INDENT 0x00000008UL
18#define F_CANONICAL 0x00000010UL 25#define F_CANONICAL 0x00000010UL
19#define F_SPACE_BEFORE 0x00000020UL 26#define F_SPACE_BEFORE 0x00000020UL
20#define F_SPACE_AFTER 0x00000040UL 27#define F_SPACE_AFTER 0x00000040UL
21#define F_ALLOW_NONREF 0x00000100UL 28#define F_ALLOW_NONREF 0x00000100UL
22#define F_SHRINK 0x00000200UL 29#define F_SHRINK 0x00000200UL
30#define F_ALLOW_BLESSED 0x00000400UL
31#define F_CONV_BLESSED 0x00000800UL
32#define F_RELAXED 0x00001000UL
33
23#define F_MAXDEPTH 0xf8000000UL 34#define F_MAXDEPTH 0xf8000000UL
24#define S_MAXDEPTH 27 35#define S_MAXDEPTH 27
36#define F_MAXSIZE 0x01f00000UL
37#define S_MAXSIZE 20
38#define F_HOOK 0x00080000UL // some hooks exist, so slow-path processing
25 39
26#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH)) 40#define DEC_DEPTH(flags) (1UL << ((flags & F_MAXDEPTH) >> S_MAXDEPTH))
27 41#define DEC_SIZE(flags) (1UL << ((flags & F_MAXSIZE ) >> S_MAXSIZE ))
28// F_SELFCONVERT? <=> to_json/toJson
29// F_BLESSED? <=> { $__class__$ => }
30 42
31#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER 43#define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER
32#define F_DEFAULT (9UL << S_MAXDEPTH) 44#define F_DEFAULT (9UL << S_MAXDEPTH)
33 45
34#define INIT_SIZE 32 // initial scalar size to be allocated 46#define INIT_SIZE 32 // initial scalar size to be allocated
48#endif 60#endif
49 61
50#define expect_false(expr) expect ((expr) != 0, 0) 62#define expect_false(expr) expect ((expr) != 0, 0)
51#define expect_true(expr) expect ((expr) != 0, 1) 63#define expect_true(expr) expect ((expr) != 0, 1)
52 64
65#ifdef USE_ITHREADS
66# define JSON_SLOW 1
67# define JSON_STASH (json_stash ? json_stash : gv_stashpv ("JSON::XS", 1))
68#else
69# define JSON_SLOW 0
70# define JSON_STASH json_stash
71#endif
72
53static HV *json_stash; // JSON::XS:: 73static HV *json_stash, *json_boolean_stash; // JSON::XS::
74static SV *json_true, *json_false;
75
76typedef struct {
77 U32 flags;
78 SV *cb_object;
79 HV *cb_sk_object;
80} JSON;
54 81
55///////////////////////////////////////////////////////////////////////////// 82/////////////////////////////////////////////////////////////////////////////
56// utility functions 83// utility functions
57 84
58static UV * 85inline void
59SvJSON (SV *sv)
60{
61 if (!(SvROK (sv) && SvOBJECT (SvRV (sv)) && SvSTASH (SvRV (sv)) == json_stash))
62 croak ("object is not of type JSON::XS");
63
64 return &SvUVX (SvRV (sv));
65}
66
67static void
68shrink (SV *sv) 86shrink (SV *sv)
69{ 87{
70 sv_utf8_downgrade (sv, 1); 88 sv_utf8_downgrade (sv, 1);
71 if (SvLEN (sv) > SvCUR (sv) + 1) 89 if (SvLEN (sv) > SvCUR (sv) + 1)
72 { 90 {
107typedef struct 125typedef struct
108{ 126{
109 char *cur; // SvPVX (sv) + current output position 127 char *cur; // SvPVX (sv) + current output position
110 char *end; // SvEND (sv) 128 char *end; // SvEND (sv)
111 SV *sv; // result scalar 129 SV *sv; // result scalar
112 U32 flags; // F_* 130 JSON json;
113 U32 indent; // indentation level 131 U32 indent; // indentation level
114 U32 maxdepth; // max. indentation/recursion level 132 U32 maxdepth; // max. indentation/recursion level
115} enc_t; 133} enc_t;
116 134
117inline void 135inline void
178 STRLEN clen; 196 STRLEN clen;
179 UV uch; 197 UV uch;
180 198
181 if (is_utf8) 199 if (is_utf8)
182 { 200 {
183 //uch = utf8n_to_uvuni (str, end - str, &clen, UTF8_CHECK_ONLY);
184 uch = decode_utf8 (str, end - str, &clen); 201 uch = decode_utf8 (str, end - str, &clen);
185 if (clen == (STRLEN)-1) 202 if (clen == (STRLEN)-1)
186 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); 203 croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str);
187 } 204 }
188 else 205 else
192 } 209 }
193 210
194 if (uch > 0x10FFFFUL) 211 if (uch > 0x10FFFFUL)
195 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch); 212 croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch);
196 213
197 if (uch < 0x80 || enc->flags & F_ASCII || (enc->flags & F_LATIN1 && uch > 0xFF)) 214 if (uch < 0x80 || enc->json.flags & F_ASCII || (enc->json.flags & F_LATIN1 && uch > 0xFF))
198 { 215 {
199 if (uch > 0xFFFFUL) 216 if (uch > 0xFFFFUL)
200 { 217 {
201 need (enc, len += 11); 218 need (enc, len += 11);
202 sprintf (enc->cur, "\\u%04x\\u%04x", 219 sprintf (enc->cur, "\\u%04x\\u%04x",
216 *enc->cur++ = hexdigit [(uch >> 0) & 15]; 233 *enc->cur++ = hexdigit [(uch >> 0) & 15];
217 } 234 }
218 235
219 str += clen; 236 str += clen;
220 } 237 }
221 else if (enc->flags & F_LATIN1) 238 else if (enc->json.flags & F_LATIN1)
222 { 239 {
223 *enc->cur++ = uch; 240 *enc->cur++ = uch;
224 str += clen; 241 str += clen;
225 } 242 }
226 else if (is_utf8) 243 else if (is_utf8)
247} 264}
248 265
249inline void 266inline void
250encode_indent (enc_t *enc) 267encode_indent (enc_t *enc)
251{ 268{
252 if (enc->flags & F_INDENT) 269 if (enc->json.flags & F_INDENT)
253 { 270 {
254 int spaces = enc->indent * INDENT_STEP; 271 int spaces = enc->indent * INDENT_STEP;
255 272
256 need (enc, spaces); 273 need (enc, spaces);
257 memset (enc->cur, ' ', spaces); 274 memset (enc->cur, ' ', spaces);
267} 284}
268 285
269inline void 286inline void
270encode_nl (enc_t *enc) 287encode_nl (enc_t *enc)
271{ 288{
272 if (enc->flags & F_INDENT) 289 if (enc->json.flags & F_INDENT)
273 { 290 {
274 need (enc, 1); 291 need (enc, 1);
275 encode_ch (enc, '\n'); 292 encode_ch (enc, '\n');
276 } 293 }
277} 294}
279inline void 296inline void
280encode_comma (enc_t *enc) 297encode_comma (enc_t *enc)
281{ 298{
282 encode_ch (enc, ','); 299 encode_ch (enc, ',');
283 300
284 if (enc->flags & F_INDENT) 301 if (enc->json.flags & F_INDENT)
285 encode_nl (enc); 302 encode_nl (enc);
286 else if (enc->flags & F_SPACE_AFTER) 303 else if (enc->json.flags & F_SPACE_AFTER)
287 encode_space (enc); 304 encode_space (enc);
288} 305}
289 306
290static void encode_sv (enc_t *enc, SV *sv); 307static void encode_sv (enc_t *enc, SV *sv);
291 308
295 int i, len = av_len (av); 312 int i, len = av_len (av);
296 313
297 if (enc->indent >= enc->maxdepth) 314 if (enc->indent >= enc->maxdepth)
298 croak ("data structure too deep (hit recursion limit)"); 315 croak ("data structure too deep (hit recursion limit)");
299 316
300 encode_ch (enc, '['); encode_nl (enc); 317 encode_ch (enc, '[');
301 ++enc->indent; 318
319 if (len >= 0)
320 {
321 encode_nl (enc); ++enc->indent;
302 322
303 for (i = 0; i <= len; ++i) 323 for (i = 0; i <= len; ++i)
304 { 324 {
325 SV **svp = av_fetch (av, i, 0);
326
305 encode_indent (enc); 327 encode_indent (enc);
306 encode_sv (enc, *av_fetch (av, i, 0));
307 328
329 if (svp)
330 encode_sv (enc, *svp);
331 else
332 encode_str (enc, "null", 4, 0);
333
308 if (i < len) 334 if (i < len)
309 encode_comma (enc); 335 encode_comma (enc);
310 } 336 }
311 337
338 encode_nl (enc); --enc->indent; encode_indent (enc);
339 }
340
312 encode_nl (enc); 341 encode_ch (enc, ']');
313
314 --enc->indent;
315 encode_indent (enc); encode_ch (enc, ']');
316} 342}
317 343
318static void 344static void
319encode_he (enc_t *enc, HE *he) 345encode_hk (enc_t *enc, HE *he)
320{ 346{
321 encode_ch (enc, '"'); 347 encode_ch (enc, '"');
322 348
323 if (HeKLEN (he) == HEf_SVKEY) 349 if (HeKLEN (he) == HEf_SVKEY)
324 { 350 {
334 else 360 else
335 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); 361 encode_str (enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he));
336 362
337 encode_ch (enc, '"'); 363 encode_ch (enc, '"');
338 364
339 if (enc->flags & F_SPACE_BEFORE) encode_space (enc); 365 if (enc->json.flags & F_SPACE_BEFORE) encode_space (enc);
340 encode_ch (enc, ':'); 366 encode_ch (enc, ':');
341 if (enc->flags & F_SPACE_AFTER ) encode_space (enc); 367 if (enc->json.flags & F_SPACE_AFTER ) encode_space (enc);
342 encode_sv (enc, HeVAL (he));
343} 368}
344 369
345// compare hash entries, used when all keys are bytestrings 370// compare hash entries, used when all keys are bytestrings
346static int 371static int
347he_cmp_fast (const void *a_, const void *b_) 372he_cmp_fast (const void *a_, const void *b_)
352 HE *b = *(HE **)b_; 377 HE *b = *(HE **)b_;
353 378
354 STRLEN la = HeKLEN (a); 379 STRLEN la = HeKLEN (a);
355 STRLEN lb = HeKLEN (b); 380 STRLEN lb = HeKLEN (b);
356 381
357 if (!(cmp = memcmp (HeKEY (a), HeKEY (b), la < lb ? la : lb))) 382 if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la)))
358 cmp = la - lb; 383 cmp = lb - la;
359 384
360 return cmp; 385 return cmp;
361} 386}
362 387
363// compare hash entries, used when some keys are sv's or utf-x 388// compare hash entries, used when some keys are sv's or utf-x
364static int 389static int
365he_cmp_slow (const void *a, const void *b) 390he_cmp_slow (const void *a, const void *b)
366{ 391{
367 return sv_cmp (HeSVKEY_force (*(HE **)a), HeSVKEY_force (*(HE **)b)); 392 return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a));
368} 393}
369 394
370static void 395static void
371encode_hv (enc_t *enc, HV *hv) 396encode_hv (enc_t *enc, HV *hv)
372{ 397{
398 HE *he;
373 int count, i; 399 int count;
374 400
375 if (enc->indent >= enc->maxdepth) 401 if (enc->indent >= enc->maxdepth)
376 croak ("data structure too deep (hit recursion limit)"); 402 croak ("data structure too deep (hit recursion limit)");
377 403
378 encode_ch (enc, '{'); encode_nl (enc); ++enc->indent; 404 encode_ch (enc, '{');
379 405
380 if ((count = hv_iterinit (hv)))
381 {
382 // for canonical output we have to sort by keys first 406 // for canonical output we have to sort by keys first
383 // actually, this is mostly due to the stupid so-called 407 // actually, this is mostly due to the stupid so-called
384 // security workaround added somewhere in 5.8.x. 408 // security workaround added somewhere in 5.8.x.
385 // that randomises hash orderings 409 // that randomises hash orderings
386 if (enc->flags & F_CANONICAL) 410 if (enc->json.flags & F_CANONICAL)
411 {
412 int count = hv_iterinit (hv);
413
414 if (SvMAGICAL (hv))
387 { 415 {
416 // need to count by iterating. could improve by dynamically building the vector below
417 // but I don't care for the speed of this special case.
418 // note also that we will run into undefined behaviour when the two iterations
419 // do not result in the same count, something I might care for in some later release.
420
421 count = 0;
422 while (hv_iternext (hv))
423 ++count;
424
425 hv_iterinit (hv);
426 }
427
428 if (count)
429 {
388 int fast = 1; 430 int i, fast = 1;
389 HE *he;
390#if defined(__BORLANDC__) || defined(_MSC_VER) 431#if defined(__BORLANDC__) || defined(_MSC_VER)
391 HE **hes = _alloca (count * sizeof (HE)); 432 HE **hes = _alloca (count * sizeof (HE));
392#else 433#else
393 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode 434 HE *hes [count]; // if your compiler dies here, you need to enable C99 mode
394#endif 435#endif
421 462
422 FREETMPS; 463 FREETMPS;
423 LEAVE; 464 LEAVE;
424 } 465 }
425 466
426 for (i = 0; i < count; ++i) 467 encode_nl (enc); ++enc->indent;
468
469 while (count--)
427 { 470 {
428 encode_indent (enc); 471 encode_indent (enc);
472 he = hes [count];
429 encode_he (enc, hes [i]); 473 encode_hk (enc, he);
474 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
430 475
431 if (i < count - 1) 476 if (count)
432 encode_comma (enc); 477 encode_comma (enc);
433 } 478 }
434 479
480 encode_nl (enc); --enc->indent; encode_indent (enc);
481 }
482 }
483 else
484 {
485 if (hv_iterinit (hv) || SvMAGICAL (hv))
486 if ((he = hv_iternext (hv)))
487 {
488 encode_nl (enc); ++enc->indent;
489
490 for (;;)
491 {
435 encode_nl (enc); 492 encode_indent (enc);
493 encode_hk (enc, he);
494 encode_sv (enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he));
495
496 if (!(he = hv_iternext (hv)))
497 break;
498
499 encode_comma (enc);
500 }
501
502 encode_nl (enc); --enc->indent; encode_indent (enc);
503 }
504 }
505
506 encode_ch (enc, '}');
507}
508
509// encode objects, arrays and special \0=false and \1=true values.
510static void
511encode_rv (enc_t *enc, SV *sv)
512{
513 svtype svt;
514
515 SvGETMAGIC (sv);
516 svt = SvTYPE (sv);
517
518 if (expect_false (SvOBJECT (sv)))
519 {
520 HV *stash = !JSON_SLOW || json_boolean_stash
521 ? json_boolean_stash
522 : gv_stashpv ("JSON::XS::Boolean", 1);
523
524 if (SvSTASH (sv) == stash)
525 {
526 if (SvIV (sv))
527 encode_str (enc, "true", 4, 0);
528 else
529 encode_str (enc, "false", 5, 0);
436 } 530 }
437 else 531 else
438 { 532 {
439 HE *he = hv_iternext (hv); 533#if 0
440 534 if (0 && sv_derived_from (rv, "JSON::Literal"))
441 for (;;)
442 { 535 {
443 encode_indent (enc); 536 // not yet
444 encode_he (enc, he);
445
446 if (!(he = hv_iternext (hv)))
447 break;
448
449 encode_comma (enc);
450 } 537 }
538#endif
539 if (enc->json.flags & F_CONV_BLESSED)
540 {
541 // we re-bless the reference to get overload and other niceties right
542 GV *to_json = gv_fetchmethod_autoload (SvSTASH (sv), "TO_JSON", 0);
451 543
544 if (to_json)
545 {
546 dSP;
547
548 ENTER; SAVETMPS; PUSHMARK (SP);
549 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), SvSTASH (sv)));
550
551 // calling with G_SCALAR ensures that we always get a 1 return value
552 PUTBACK;
553 call_sv ((SV *)GvCV (to_json), G_SCALAR);
554 SPAGAIN;
555
556 // catch this surprisingly common error
557 if (SvROK (TOPs) && SvRV (TOPs) == sv)
558 croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv)));
559
560 sv = POPs;
561 PUTBACK;
562
452 encode_nl (enc); 563 encode_sv (enc, sv);
564
565 FREETMPS; LEAVE;
566 }
567 else if (enc->json.flags & F_ALLOW_BLESSED)
568 encode_str (enc, "null", 4, 0);
569 else
570 croak ("encountered object '%s', but neither allow_blessed enabled nor TO_JSON method available on it",
571 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
572 }
573 else if (enc->json.flags & F_ALLOW_BLESSED)
574 encode_str (enc, "null", 4, 0);
575 else
576 croak ("encountered object '%s', but neither allow_blessed nor convert_blessed settings are enabled",
577 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
453 } 578 }
454 } 579 }
455
456 --enc->indent; encode_indent (enc); encode_ch (enc, '}');
457}
458
459// encode objects, arrays and special \0=false and \1=true values.
460static void
461encode_rv (enc_t *enc, SV *sv)
462{
463 svtype svt;
464
465 SvGETMAGIC (sv);
466 svt = SvTYPE (sv);
467
468 if (svt == SVt_PVHV) 580 else if (svt == SVt_PVHV)
469 encode_hv (enc, (HV *)sv); 581 encode_hv (enc, (HV *)sv);
470 else if (svt == SVt_PVAV) 582 else if (svt == SVt_PVAV)
471 encode_av (enc, (AV *)sv); 583 encode_av (enc, (AV *)sv);
472 else if (svt < SVt_PVAV) 584 else if (svt < SVt_PVAV)
473 { 585 {
474 if (SvNIOK (sv) && SvIV (sv) == 0) 586 STRLEN len = 0;
587 char *pv = svt ? SvPV (sv, len) : 0;
588
589 if (len == 1 && *pv == '1')
590 encode_str (enc, "true", 4, 0);
591 else if (len == 1 && *pv == '0')
475 encode_str (enc, "false", 5, 0); 592 encode_str (enc, "false", 5, 0);
476 else if (SvNIOK (sv) && SvIV (sv) == 1)
477 encode_str (enc, "true", 4, 0);
478 else 593 else
479 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1", 594 croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1",
480 SvPV_nolen (sv_2mortal (newRV_inc (sv)))); 595 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
481 } 596 }
482 else 597 else
497 encode_str (enc, str, len, SvUTF8 (sv)); 612 encode_str (enc, str, len, SvUTF8 (sv));
498 encode_ch (enc, '"'); 613 encode_ch (enc, '"');
499 } 614 }
500 else if (SvNOKp (sv)) 615 else if (SvNOKp (sv))
501 { 616 {
617 // trust that perl will do the right thing w.r.t. JSON syntax.
502 need (enc, NV_DIG + 32); 618 need (enc, NV_DIG + 32);
503 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); 619 Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur);
504 enc->cur += strlen (enc->cur); 620 enc->cur += strlen (enc->cur);
505 } 621 }
506 else if (SvIOKp (sv)) 622 else if (SvIOKp (sv))
507 { 623 {
508 // we assume we can always read an IV as a UV 624 // we assume we can always read an IV as a UV
509 if (SvUV (sv) & ~(UV)0x7fff) 625 if (SvUV (sv) & ~(UV)0x7fff)
510 { 626 {
627 // large integer, use the (rather slow) snprintf way.
511 need (enc, sizeof (UV) * 3); 628 need (enc, sizeof (UV) * 3);
512 enc->cur += 629 enc->cur +=
513 SvIsUV(sv) 630 SvIsUV(sv)
514 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv)) 631 ? snprintf (enc->cur, sizeof (UV) * 3, "%"UVuf, (UV)SvUVX (sv))
515 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv)); 632 : snprintf (enc->cur, sizeof (UV) * 3, "%"IVdf, (IV)SvIVX (sv));
518 { 635 {
519 // optimise the "small number case" 636 // optimise the "small number case"
520 // code will likely be branchless and use only a single multiplication 637 // code will likely be branchless and use only a single multiplication
521 I32 i = SvIV (sv); 638 I32 i = SvIV (sv);
522 U32 u; 639 U32 u;
640 char digit, nz = 0;
523 641
524 need (enc, 6); 642 need (enc, 6);
525 643
526 *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0; 644 *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0;
527 u = i < 0 ? -i : i; 645 u = i < 0 ? -i : i;
528 646
529 // convert to 4.28 fixed-point representation 647 // convert to 4.28 fixed-point representation
530 u = u * ((0xfffffff + 10000) / 10000); // 10**5, 5 fractional digits 648 u = u * ((0xfffffff + 10000) / 10000); // 10**5, 5 fractional digits
531 649
532 char digit, nz = 0; 650 // now output digit by digit, each time masking out the integer part
533 651 // and multiplying by 5 while moving the decimal point one to the right,
652 // resulting in a net multiplication by 10.
653 // we always write the digit to memory but conditionally increment
654 // the pointer, to ease the usage of conditional move instructions.
534 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffff) * 5; 655 digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffff) * 5;
535 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffff) * 5; 656 digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffff) * 5;
536 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffff) * 5; 657 digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffff) * 5;
537 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffff) * 5; 658 digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffff) * 5;
538 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; 659 digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; // correctly generate '0'
539 } 660 }
540 } 661 }
541 else if (SvROK (sv)) 662 else if (SvROK (sv))
542 encode_rv (enc, SvRV (sv)); 663 encode_rv (enc, SvRV (sv));
543 else if (!SvOK (sv)) 664 else if (!SvOK (sv))
546 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this", 667 croak ("encountered perl type (%s,0x%x) that JSON cannot handle, you might want to report this",
547 SvPV_nolen (sv), SvFLAGS (sv)); 668 SvPV_nolen (sv), SvFLAGS (sv));
548} 669}
549 670
550static SV * 671static SV *
551encode_json (SV *scalar, U32 flags) 672encode_json (SV *scalar, JSON *json)
552{ 673{
553 enc_t enc; 674 enc_t enc;
554 675
555 if (!(flags & F_ALLOW_NONREF) && !SvROK (scalar)) 676 if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar))
556 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); 677 croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)");
557 678
558 enc.flags = flags; 679 enc.json = *json;
559 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); 680 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
560 enc.cur = SvPVX (enc.sv); 681 enc.cur = SvPVX (enc.sv);
561 enc.end = SvEND (enc.sv); 682 enc.end = SvEND (enc.sv);
562 enc.indent = 0; 683 enc.indent = 0;
563 enc.maxdepth = DEC_DEPTH (flags); 684 enc.maxdepth = DEC_DEPTH (enc.json.flags);
564 685
565 SvPOK_only (enc.sv); 686 SvPOK_only (enc.sv);
566 encode_sv (&enc, scalar); 687 encode_sv (&enc, scalar);
567 688
568 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); 689 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
569 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings 690 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
570 691
571 if (!(flags & (F_ASCII | F_LATIN1 | F_UTF8))) 692 if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_UTF8)))
572 SvUTF8_on (enc.sv); 693 SvUTF8_on (enc.sv);
573 694
574 if (enc.flags & F_SHRINK) 695 if (enc.json.flags & F_SHRINK)
575 shrink (enc.sv); 696 shrink (enc.sv);
576 697
577 return enc.sv; 698 return enc.sv;
578} 699}
579 700
584typedef struct 705typedef struct
585{ 706{
586 char *cur; // current parser pointer 707 char *cur; // current parser pointer
587 char *end; // end of input string 708 char *end; // end of input string
588 const char *err; // parse error, if != 0 709 const char *err; // parse error, if != 0
589 U32 flags; // F_* 710 JSON json;
590 U32 depth; // recursion depth 711 U32 depth; // recursion depth
591 U32 maxdepth; // recursion depth limit 712 U32 maxdepth; // recursion depth limit
592} dec_t; 713} dec_t;
593 714
594inline void 715inline void
716decode_comment (dec_t *dec)
717{
718 // only '#'-style comments allowed a.t.m.
719
720 while (*dec->cur && *dec->cur != 0x0a && *dec->cur != 0x0d)
721 ++dec->cur;
722}
723
724inline void
595decode_ws (dec_t *dec) 725decode_ws (dec_t *dec)
596{ 726{
597 for (;;) 727 for (;;)
598 { 728 {
599 char ch = *dec->cur; 729 char ch = *dec->cur;
600 730
601 if (ch > 0x20 731 if (ch > 0x20)
732 {
733 if (expect_false (ch == '#'))
734 {
735 if (dec->json.flags & F_RELAXED)
736 decode_comment (dec);
737 else
738 break;
739 }
740 else
741 break;
742 }
602 || (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)) 743 else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09)
603 break; 744 break; // parse error, but let higher level handle it, gives better error messages
604 745
605 ++dec->cur; 746 ++dec->cur;
606 } 747 }
607} 748}
608 749
625decode_4hex (dec_t *dec) 766decode_4hex (dec_t *dec)
626{ 767{
627 signed char d1, d2, d3, d4; 768 signed char d1, d2, d3, d4;
628 unsigned char *cur = (unsigned char *)dec->cur; 769 unsigned char *cur = (unsigned char *)dec->cur;
629 770
630 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("four hexadecimal digits expected"); 771 d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected");
631 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("four hexadecimal digits expected"); 772 d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected");
632 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("four hexadecimal digits expected"); 773 d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected");
633 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("four hexadecimal digits expected"); 774 d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected");
634 775
635 dec->cur += 4; 776 dec->cur += 4;
636 777
637 return ((UV)d1) << 12 778 return ((UV)d1) << 12
638 | ((UV)d2) << 8 779 | ((UV)d2) << 8
857 is_nv = 1; 998 is_nv = 1;
858 } 999 }
859 1000
860 if (!is_nv) 1001 if (!is_nv)
861 { 1002 {
1003 int len = dec->cur - start;
1004
862 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so 1005 // special case the rather common 1..4-digit-int case, assumes 32 bit ints or so
863 if (*start == '-') 1006 if (*start == '-')
864 switch (dec->cur - start) 1007 switch (len)
865 { 1008 {
866 case 2: return newSViv (-( start [1] - '0' )); 1009 case 2: return newSViv (-( start [1] - '0' * 1));
867 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11)); 1010 case 3: return newSViv (-( start [1] * 10 + start [2] - '0' * 11));
868 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111)); 1011 case 4: return newSViv (-( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111));
869 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111)); 1012 case 5: return newSViv (-(start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111));
870 } 1013 }
871 else 1014 else
872 switch (dec->cur - start) 1015 switch (len)
873 { 1016 {
874 case 1: return newSViv ( start [0] - '0' ); 1017 case 1: return newSViv ( start [0] - '0' * 1);
875 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); 1018 case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11);
876 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111); 1019 case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111);
877 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111); 1020 case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111);
878 } 1021 }
879 1022
880 { 1023 {
881 UV uv; 1024 UV uv;
882 int numtype = grok_number (start, dec->cur - start, &uv); 1025 int numtype = grok_number (start, len, &uv);
883 if (numtype & IS_NUMBER_IN_UV) 1026 if (numtype & IS_NUMBER_IN_UV)
884 if (numtype & IS_NUMBER_NEG) 1027 if (numtype & IS_NUMBER_NEG)
885 { 1028 {
886 if (uv < (UV)IV_MIN) 1029 if (uv < (UV)IV_MIN)
887 return newSViv (-(IV)uv); 1030 return newSViv (-(IV)uv);
888 } 1031 }
889 else 1032 else
890 return newSVuv (uv); 1033 return newSVuv (uv);
891 } 1034 }
892 }
893 1035
1036 len -= *start == '-' ? 1 : 0;
1037
1038 // does not fit into IV or UV, try NV
1039 if ((sizeof (NV) == sizeof (double) && DBL_DIG >= len)
1040 #if defined (LDBL_DIG)
1041 || (sizeof (NV) == sizeof (long double) && LDBL_DIG >= len)
1042 #endif
1043 )
1044 // fits into NV without loss of precision
1045 return newSVnv (Atof (start));
1046
1047 // everything else fails, convert it to a string
1048 return newSVpvn (start, dec->cur - start);
1049 }
1050
1051 // loss of precision here
894 return newSVnv (Atof (start)); 1052 return newSVnv (Atof (start));
895 1053
896fail: 1054fail:
897 return 0; 1055 return 0;
898} 1056}
928 1086
929 if (*dec->cur != ',') 1087 if (*dec->cur != ',')
930 ERR (", or ] expected while parsing array"); 1088 ERR (", or ] expected while parsing array");
931 1089
932 ++dec->cur; 1090 ++dec->cur;
1091
1092 decode_ws (dec);
1093
1094 if (*dec->cur == ']' && dec->json.flags & F_RELAXED)
1095 {
1096 ++dec->cur;
1097 break;
1098 }
933 } 1099 }
934 1100
935 DEC_DEC_DEPTH; 1101 DEC_DEC_DEPTH;
936 return newRV_noinc ((SV *)av); 1102 return newRV_noinc ((SV *)av);
937 1103
942} 1108}
943 1109
944static SV * 1110static SV *
945decode_hv (dec_t *dec) 1111decode_hv (dec_t *dec)
946{ 1112{
1113 SV *sv;
947 HV *hv = newHV (); 1114 HV *hv = newHV ();
948 1115
949 DEC_INC_DEPTH; 1116 DEC_INC_DEPTH;
950 decode_ws (dec); 1117 decode_ws (dec);
951 1118
952 if (*dec->cur == '}') 1119 if (*dec->cur == '}')
953 ++dec->cur; 1120 ++dec->cur;
954 else 1121 else
955 for (;;) 1122 for (;;)
956 { 1123 {
1124 EXPECT_CH ('"');
1125
1126 // heuristic: assume that
1127 // a) decode_str + hv_store_ent are abysmally slow.
1128 // b) most hash keys are short, simple ascii text.
1129 // => try to "fast-match" such strings to avoid
1130 // the overhead of decode_str + hv_store_ent.
1131 {
957 SV *key, *value; 1132 SV *value;
1133 char *p = dec->cur;
1134 char *e = p + 24; // only try up to 24 bytes
958 1135
959 decode_ws (dec); EXPECT_CH ('"'); 1136 for (;;)
960
961 key = decode_str (dec);
962 if (!key)
963 goto fail;
964
965 decode_ws (dec); EXPECT_CH (':');
966
967 value = decode_sv (dec);
968 if (!value)
969 { 1137 {
1138 // the >= 0x80 is true on most architectures
1139 if (p == e || *p < 0x20 || *p >= 0x80 || *p == '\\')
1140 {
1141 // slow path, back up and use decode_str
1142 SV *key = decode_str (dec);
1143 if (!key)
1144 goto fail;
1145
1146 decode_ws (dec); EXPECT_CH (':');
1147
1148 decode_ws (dec);
1149 value = decode_sv (dec);
1150 if (!value)
1151 {
1152 SvREFCNT_dec (key);
1153 goto fail;
1154 }
1155
1156 hv_store_ent (hv, key, value, 0);
970 SvREFCNT_dec (key); 1157 SvREFCNT_dec (key);
1158
1159 break;
1160 }
1161 else if (*p == '"')
1162 {
1163 // fast path, got a simple key
1164 char *key = dec->cur;
1165 int len = p - key;
1166 dec->cur = p + 1;
1167
1168 decode_ws (dec); EXPECT_CH (':');
1169
1170 decode_ws (dec);
1171 value = decode_sv (dec);
1172 if (!value)
971 goto fail; 1173 goto fail;
1174
1175 hv_store (hv, key, len, value, 0);
1176
1177 break;
1178 }
1179
1180 ++p;
972 } 1181 }
973 1182 }
974 hv_store_ent (hv, key, value, 0);
975 SvREFCNT_dec (key);
976 1183
977 decode_ws (dec); 1184 decode_ws (dec);
978 1185
979 if (*dec->cur == '}') 1186 if (*dec->cur == '}')
980 { 1187 {
984 1191
985 if (*dec->cur != ',') 1192 if (*dec->cur != ',')
986 ERR (", or } expected while parsing object/hash"); 1193 ERR (", or } expected while parsing object/hash");
987 1194
988 ++dec->cur; 1195 ++dec->cur;
1196
1197 decode_ws (dec);
1198
1199 if (*dec->cur == '}' && dec->json.flags & F_RELAXED)
1200 {
1201 ++dec->cur;
1202 break;
1203 }
989 } 1204 }
990 1205
991 DEC_DEC_DEPTH; 1206 DEC_DEC_DEPTH;
992 return newRV_noinc ((SV *)hv); 1207 sv = newRV_noinc ((SV *)hv);
1208
1209 // check filter callbacks
1210 if (dec->json.flags & F_HOOK)
1211 {
1212 if (dec->json.cb_sk_object && HvKEYS (hv) == 1)
1213 {
1214 HE *cb, *he;
1215
1216 hv_iterinit (hv);
1217 he = hv_iternext (hv);
1218 hv_iterinit (hv);
1219
1220 // the next line creates a mortal sv each time its called.
1221 // might want to optimise this for common cases.
1222 cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0);
1223
1224 if (cb)
1225 {
1226 dSP;
1227 int count;
1228
1229 ENTER; SAVETMPS; PUSHMARK (SP);
1230 XPUSHs (HeVAL (he));
1231
1232 PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN;
1233
1234 if (count == 1)
1235 {
1236 sv = newSVsv (POPs);
1237 FREETMPS; LEAVE;
1238 return sv;
1239 }
1240
1241 FREETMPS; LEAVE;
1242 }
1243 }
1244
1245 if (dec->json.cb_object)
1246 {
1247 dSP;
1248 int count;
1249
1250 ENTER; SAVETMPS; PUSHMARK (SP);
1251 XPUSHs (sv_2mortal (sv));
1252
1253 PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN;
1254
1255 if (count == 1)
1256 {
1257 sv = newSVsv (POPs);
1258 FREETMPS; LEAVE;
1259 return sv;
1260 }
1261
1262 SvREFCNT_inc (sv);
1263 FREETMPS; LEAVE;
1264 }
1265 }
1266
1267 return sv;
993 1268
994fail: 1269fail:
995 SvREFCNT_dec (hv); 1270 SvREFCNT_dec (hv);
996 DEC_DEC_DEPTH; 1271 DEC_DEC_DEPTH;
997 return 0; 1272 return 0;
998} 1273}
999 1274
1000static SV * 1275static SV *
1001decode_sv (dec_t *dec) 1276decode_sv (dec_t *dec)
1002{ 1277{
1003 decode_ws (dec); 1278 // the beauty of JSON: you need exactly one character lookahead
1279 // to parse anything.
1004 switch (*dec->cur) 1280 switch (*dec->cur)
1005 { 1281 {
1006 case '"': ++dec->cur; return decode_str (dec); 1282 case '"': ++dec->cur; return decode_str (dec);
1007 case '[': ++dec->cur; return decode_av (dec); 1283 case '[': ++dec->cur; return decode_av (dec);
1008 case '{': ++dec->cur; return decode_hv (dec); 1284 case '{': ++dec->cur; return decode_hv (dec);
1014 1290
1015 case 't': 1291 case 't':
1016 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) 1292 if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4))
1017 { 1293 {
1018 dec->cur += 4; 1294 dec->cur += 4;
1019 return newSViv (1); 1295#if JSON_SLOW
1296 json_true = get_sv ("JSON::XS::true", 1); SvREADONLY_on (json_true);
1297#endif
1298 return SvREFCNT_inc (json_true);
1020 } 1299 }
1021 else 1300 else
1022 ERR ("'true' expected"); 1301 ERR ("'true' expected");
1023 1302
1024 break; 1303 break;
1025 1304
1026 case 'f': 1305 case 'f':
1027 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) 1306 if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5))
1028 { 1307 {
1029 dec->cur += 5; 1308 dec->cur += 5;
1030 return newSViv (0); 1309#if JSON_SLOW
1310 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1311#endif
1312 return SvREFCNT_inc (json_false);
1031 } 1313 }
1032 else 1314 else
1033 ERR ("'false' expected"); 1315 ERR ("'false' expected");
1034 1316
1035 break; 1317 break;
1053fail: 1335fail:
1054 return 0; 1336 return 0;
1055} 1337}
1056 1338
1057static SV * 1339static SV *
1058decode_json (SV *string, U32 flags, UV *offset_return) 1340decode_json (SV *string, JSON *json, UV *offset_return)
1059{ 1341{
1060 dec_t dec; 1342 dec_t dec;
1061 UV offset; 1343 UV offset;
1062 SV *sv; 1344 SV *sv;
1063 1345
1064 SvGETMAGIC (string); 1346 SvGETMAGIC (string);
1065 SvUPGRADE (string, SVt_PV); 1347 SvUPGRADE (string, SVt_PV);
1066 1348
1349 if (json->flags & F_MAXSIZE && SvCUR (string) > DEC_SIZE (json->flags))
1350 croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu",
1351 (unsigned long)SvCUR (string), (unsigned long)DEC_SIZE (json->flags));
1352
1067 if (flags & F_UTF8) 1353 if (json->flags & F_UTF8)
1068 sv_utf8_downgrade (string, 0); 1354 sv_utf8_downgrade (string, 0);
1069 else 1355 else
1070 sv_utf8_upgrade (string); 1356 sv_utf8_upgrade (string);
1071 1357
1072 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP 1358 SvGROW (string, SvCUR (string) + 1); // should basically be a NOP
1073 1359
1074 dec.flags = flags; 1360 dec.json = *json;
1075 dec.cur = SvPVX (string); 1361 dec.cur = SvPVX (string);
1076 dec.end = SvEND (string); 1362 dec.end = SvEND (string);
1077 dec.err = 0; 1363 dec.err = 0;
1078 dec.depth = 0; 1364 dec.depth = 0;
1079 dec.maxdepth = DEC_DEPTH (dec.flags); 1365 dec.maxdepth = DEC_DEPTH (dec.json.flags);
1366
1367 if (dec.json.cb_object || dec.json.cb_sk_object)
1368 dec.json.flags |= F_HOOK;
1080 1369
1081 *dec.end = 0; // this should basically be a nop, too, but make sure it's there 1370 *dec.end = 0; // this should basically be a nop, too, but make sure it's there
1371
1372 decode_ws (&dec);
1082 sv = decode_sv (&dec); 1373 sv = decode_sv (&dec);
1083 1374
1084 if (!(offset_return || !sv)) 1375 if (!(offset_return || !sv))
1085 { 1376 {
1086 // check for trailing garbage 1377 // check for trailing garbage
1094 } 1385 }
1095 } 1386 }
1096 1387
1097 if (offset_return || !sv) 1388 if (offset_return || !sv)
1098 { 1389 {
1099 offset = dec.flags & F_UTF8 1390 offset = dec.json.flags & F_UTF8
1100 ? dec.cur - SvPVX (string) 1391 ? dec.cur - SvPVX (string)
1101 : utf8_distance (dec.cur, SvPVX (string)); 1392 : utf8_distance (dec.cur, SvPVX (string));
1102 1393
1103 if (offset_return) 1394 if (offset_return)
1104 *offset_return = offset; 1395 *offset_return = offset;
1123 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); 1414 dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)");
1124 } 1415 }
1125 1416
1126 sv = sv_2mortal (sv); 1417 sv = sv_2mortal (sv);
1127 1418
1128 if (!(dec.flags & F_ALLOW_NONREF) && !SvROK (sv)) 1419 if (!(dec.json.flags & F_ALLOW_NONREF) && !SvROK (sv))
1129 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)"); 1420 croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)");
1130 1421
1131 return sv; 1422 return sv;
1132} 1423}
1133 1424
1137MODULE = JSON::XS PACKAGE = JSON::XS 1428MODULE = JSON::XS PACKAGE = JSON::XS
1138 1429
1139BOOT: 1430BOOT:
1140{ 1431{
1141 int i; 1432 int i;
1142
1143 memset (decode_hexdigit, 0xff, 256);
1144 1433
1145 for (i = 0; i < 256; ++i) 1434 for (i = 0; i < 256; ++i)
1146 decode_hexdigit [i] = 1435 decode_hexdigit [i] =
1147 i >= '0' && i <= '9' ? i - '0' 1436 i >= '0' && i <= '9' ? i - '0'
1148 : i >= 'a' && i <= 'f' ? i - 'a' + 10 1437 : i >= 'a' && i <= 'f' ? i - 'a' + 10
1149 : i >= 'A' && i <= 'F' ? i - 'A' + 10 1438 : i >= 'A' && i <= 'F' ? i - 'A' + 10
1150 : -1; 1439 : -1;
1151 1440
1152 json_stash = gv_stashpv ("JSON::XS", 1); 1441 json_stash = gv_stashpv ("JSON::XS" , 1);
1442 json_boolean_stash = gv_stashpv ("JSON::XS::Boolean", 1);
1443
1444 json_true = get_sv ("JSON::XS::true" , 1); SvREADONLY_on (json_true );
1445 json_false = get_sv ("JSON::XS::false", 1); SvREADONLY_on (json_false);
1153} 1446}
1154 1447
1155PROTOTYPES: DISABLE 1448PROTOTYPES: DISABLE
1156 1449
1157SV *new (char *dummy) 1450void CLONE (...)
1158 CODE: 1451 CODE:
1159 RETVAL = sv_bless (newRV_noinc (newSVuv (F_DEFAULT)), json_stash); 1452 json_stash = 0;
1453 json_boolean_stash = 0;
1454
1455void new (char *klass)
1456 PPCODE:
1457{
1458 SV *pv = NEWSV (0, sizeof (JSON));
1459 SvPOK_only (pv);
1460 Zero (SvPVX (pv), 1, JSON);
1461 ((JSON *)SvPVX (pv))->flags = F_DEFAULT;
1462 XPUSHs (sv_2mortal (sv_bless (newRV_noinc (pv), JSON_STASH)));
1463}
1464
1465void ascii (JSON *self, int enable = 1)
1466 ALIAS:
1467 ascii = F_ASCII
1468 latin1 = F_LATIN1
1469 utf8 = F_UTF8
1470 indent = F_INDENT
1471 canonical = F_CANONICAL
1472 space_before = F_SPACE_BEFORE
1473 space_after = F_SPACE_AFTER
1474 pretty = F_PRETTY
1475 allow_nonref = F_ALLOW_NONREF
1476 shrink = F_SHRINK
1477 allow_blessed = F_ALLOW_BLESSED
1478 convert_blessed = F_CONV_BLESSED
1479 relaxed = F_RELAXED
1480 PPCODE:
1481{
1482 if (enable)
1483 self->flags |= ix;
1484 else
1485 self->flags &= ~ix;
1486
1487 XPUSHs (ST (0));
1488}
1489
1490void get_ascii (JSON *self)
1491 ALIAS:
1492 get_ascii = F_ASCII
1493 get_latin1 = F_LATIN1
1494 get_utf8 = F_UTF8
1495 get_indent = F_INDENT
1496 get_canonical = F_CANONICAL
1497 get_space_before = F_SPACE_BEFORE
1498 get_space_after = F_SPACE_AFTER
1499 get_pretty = F_PRETTY
1500 get_allow_nonref = F_ALLOW_NONREF
1501 get_shrink = F_SHRINK
1502 get_allow_blessed = F_ALLOW_BLESSED
1503 get_convert_blessed = F_CONV_BLESSED
1504 get_relaxed = F_RELAXED
1505 PPCODE:
1506 XPUSHs (boolSV (self->flags & ix));
1507
1508void max_depth (JSON *self, UV max_depth = 0x80000000UL)
1509 PPCODE:
1510{
1511 UV log2 = 0;
1512
1513 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1514
1515 while ((1UL << log2) < max_depth)
1516 ++log2;
1517
1518 self->flags = self->flags & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1519
1520 XPUSHs (ST (0));
1521}
1522
1523U32 get_max_depth (JSON *self)
1524 CODE:
1525 RETVAL = DEC_DEPTH (self->flags);
1160 OUTPUT: 1526 OUTPUT:
1161 RETVAL 1527 RETVAL
1162 1528
1163SV *ascii (SV *self, int enable = 1) 1529void max_size (JSON *self, UV max_size = 0)
1164 ALIAS: 1530 PPCODE:
1165 ascii = F_ASCII 1531{
1166 latin1 = F_LATIN1 1532 UV log2 = 0;
1167 utf8 = F_UTF8 1533
1168 indent = F_INDENT 1534 if (max_size > 0x80000000UL) max_size = 0x80000000UL;
1169 canonical = F_CANONICAL 1535 if (max_size == 1) max_size = 2;
1170 space_before = F_SPACE_BEFORE 1536
1171 space_after = F_SPACE_AFTER 1537 while ((1UL << log2) < max_size)
1172 pretty = F_PRETTY 1538 ++log2;
1173 allow_nonref = F_ALLOW_NONREF 1539
1174 shrink = F_SHRINK 1540 self->flags = self->flags & ~F_MAXSIZE | (log2 << S_MAXSIZE);
1541
1542 XPUSHs (ST (0));
1543}
1544
1545int get_max_size (JSON *self)
1175 CODE: 1546 CODE:
1176{ 1547 RETVAL = DEC_SIZE (self->flags);
1177 UV *uv = SvJSON (self);
1178 if (enable)
1179 *uv |= ix;
1180 else
1181 *uv &= ~ix;
1182
1183 RETVAL = newSVsv (self);
1184}
1185 OUTPUT: 1548 OUTPUT:
1186 RETVAL 1549 RETVAL
1187 1550
1188SV *max_depth (SV *self, UV max_depth = 0x80000000UL) 1551void filter_json_object (JSON *self, SV *cb = &PL_sv_undef)
1189 CODE:
1190{
1191 UV *uv = SvJSON (self);
1192 UV log2 = 0;
1193
1194 if (max_depth > 0x80000000UL) max_depth = 0x80000000UL;
1195
1196 while ((1UL << log2) < max_depth)
1197 ++log2;
1198
1199 *uv = *uv & ~F_MAXDEPTH | (log2 << S_MAXDEPTH);
1200
1201 RETVAL = newSVsv (self);
1202}
1203 OUTPUT:
1204 RETVAL
1205
1206void encode (SV *self, SV *scalar)
1207 PPCODE: 1552 PPCODE:
1208 XPUSHs (encode_json (scalar, *SvJSON (self))); 1553{
1554 SvREFCNT_dec (self->cb_object);
1555 self->cb_object = SvOK (cb) ? newSVsv (cb) : 0;
1209 1556
1210void decode (SV *self, SV *jsonstr) 1557 XPUSHs (ST (0));
1558}
1559
1560void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef)
1211 PPCODE: 1561 PPCODE:
1562{
1563 if (!self->cb_sk_object)
1564 self->cb_sk_object = newHV ();
1565
1566 if (SvOK (cb))
1567 hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0);
1568 else
1569 {
1570 hv_delete_ent (self->cb_sk_object, key, G_DISCARD, 0);
1571
1572 if (!HvKEYS (self->cb_sk_object))
1573 {
1574 SvREFCNT_dec (self->cb_sk_object);
1575 self->cb_sk_object = 0;
1576 }
1577 }
1578
1579 XPUSHs (ST (0));
1580}
1581
1582void encode (JSON *self, SV *scalar)
1583 PPCODE:
1584 XPUSHs (encode_json (scalar, self));
1585
1586void decode (JSON *self, SV *jsonstr)
1587 PPCODE:
1212 XPUSHs (decode_json (jsonstr, *SvJSON (self), 0)); 1588 XPUSHs (decode_json (jsonstr, self, 0));
1213 1589
1214void decode_prefix (SV *self, SV *jsonstr) 1590void decode_prefix (JSON *self, SV *jsonstr)
1215 PPCODE: 1591 PPCODE:
1216{ 1592{
1217 UV offset; 1593 UV offset;
1218 EXTEND (SP, 2); 1594 EXTEND (SP, 2);
1219 PUSHs (decode_json (jsonstr, *SvJSON (self), &offset)); 1595 PUSHs (decode_json (jsonstr, self, &offset));
1220 PUSHs (sv_2mortal (newSVuv (offset))); 1596 PUSHs (sv_2mortal (newSVuv (offset)));
1221} 1597}
1222 1598
1599void DESTROY (JSON *self)
1600 CODE:
1601 SvREFCNT_dec (self->cb_sk_object);
1602 SvREFCNT_dec (self->cb_object);
1603
1223PROTOTYPES: ENABLE 1604PROTOTYPES: ENABLE
1224 1605
1225void to_json (SV *scalar) 1606void to_json (SV *scalar)
1226 ALIAS:
1227 objToJson = 0
1228 PPCODE: 1607 PPCODE:
1608{
1609 JSON json = { F_DEFAULT | F_UTF8 };
1229 XPUSHs (encode_json (scalar, F_DEFAULT | F_UTF8)); 1610 XPUSHs (encode_json (scalar, &json));
1611}
1230 1612
1231void from_json (SV *jsonstr) 1613void from_json (SV *jsonstr)
1232 ALIAS:
1233 jsonToObj = 0
1234 PPCODE: 1614 PPCODE:
1615{
1616 JSON json = { F_DEFAULT | F_UTF8 };
1235 XPUSHs (decode_json (jsonstr, F_DEFAULT | F_UTF8, 0)); 1617 XPUSHs (decode_json (jsonstr, &json, 0));
1618}
1236 1619

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines