Cpanel-JSON-XS-3.0210/0000755000076500001200000000000012630027164013237 5ustar rurbanadminCpanel-JSON-XS-3.0210/.travis.yml0000644000076500001200000000233212625565726015367 0ustar rurbanadminlanguage: "perl" sudo: false perl: # - "5.6.2" - "5.8" - "5.10" - "5.12" - "5.14" - "5.16" - "5.18" - "5.20" - "5.22" - "5.22-thr" - "5.22-dbg" - "5.22-thr-dbg" - "5.22-mb" - "dev" - "blead" #addons: # apt: # packages: # - gperf # blead and 5.6 stumble over YAML and more missing dependencies # for Devel::Cover::Report::Coveralls # cpanm does not do 5.6 before_install: - mkdir /home/travis/bin || true - ln -s `which true` /home/travis/bin/cpansign - eval $(curl https://travis-perl.github.io/init) --auto install: - export AUTOMATED_TESTING=1 HARNESS_TIMER=1 AUTHOR_TESTING=0 RELEASE_TESTING=0 - cpan-install --deps # installs prereqs, including recommends - cpan-install JSON JSON::PP JSON::XS Mojo::JSON Test::LeakTrace Time::Piece - cpan-install --coverage # installs converage prereqs, if enabled before_script: - coverage-setup notifications: email: on_success: change on_failure: always matrix: fast_finish: true include: - perl: "5.18" env: COVERAGE=1 AUTHOR_TESTING=1 # enables coverage+coveralls reporting allow_failures: - env: COVERAGE=1 AUTHOR_TESTING=1 # Hack to not run on tag pushes: branches: except: - /^v?[0-9]+\.[0-9]+/ Cpanel-JSON-XS-3.0210/bin/0000755000076500001200000000000012630027156014010 5ustar rurbanadminCpanel-JSON-XS-3.0210/bin/cpanel_json_xs0000755000076500001200000001713612630026757016761 0ustar rurbanadmin#!/usr/bin/perl =head1 NAME cpanel_json_xs - Cpanel::JSON::XS commandline utility =head1 SYNOPSIS cpanel_json_xs [-v] [-f inputformat] [-t outputformat] =head1 DESCRIPTION F converts between some input and output formats (one of them is JSON). The default input format is C and the default output format is C. =head1 OPTIONS =over 4 =item -v Be slightly more verbose. =item -f fromformat Read a file in the given format from STDIN. C can be one of: =over 4 =item json - a json text encoded, either utf-8, utf16-be/le, utf32-be/le =item json-nonref - json according to RFC 7159 =item json-relaxed - json with all relaxed options =item json-unknown - json with allow_unknown =item storable - a Storable frozen value =item storable-file - a Storable file (Storable has two incompatible formats) =item bencode - use Convert::Bencode, if available (used by torrent files, among others) =item clzf - Compress::LZF format (requires that module to be installed) =item eval - evaluate the given code as (non-utf-8) Perl, basically the reverse of "-t dump" =item yaml - YAML (avoid at all costs, requires the YAML module :) =item string - do not attempt to decode the file data =item none - nothing is read, creates an C scalar - mainly useful with C<-e> =back =item -t toformat Write the file in the given format to STDOUT. C can be one of: =over 4 =item json, json-utf-8 - json, utf-8 encoded =item json-pretty - as above, but pretty-printed with sorted object keys =item json-stringify - as json-pretty with allow_stringify =item json-relaxed - as json-pretty, but with the additional options ->allow_stringify->allow_blessed->convert_blessed->allow_unknown ->allow_tags->stringify_infnan(1) =item json-utf-16le, json-utf-16be - little endian/big endian utf-16 =item json-utf-32le, json-utf-32be - little endian/big endian utf-32 =item storable - a Storable frozen value in network format =item storable-file - a Storable file in network format (Storable has two incompatible formats) =item bencode - use Convert::Bencode, if available (used by torrent files, among others) =item clzf - Compress::LZF format =item yaml - YAML =item dump - Data::Dump =item dumper - Data::Dumper =item string - writes the data out as if it were a string =item none - nothing gets written, mainly useful together with C<-e> Note that Data::Dumper doesn't handle self-referential data structures correctly - use "dump" instead. =back =item -e code Evaluate perl code after reading the data and before writing it out again - can be used to filter, create or extract data. The data that has been written is in C<$_>, and whatever is in there is written out afterwards. =back =head1 EXAMPLES cpanel_json_xs -t none as JSON - if it is valid JSON, the command outputs nothing, otherwise it will print an error message and exit with non-zero exit status. pretty.json Prettify the JSON file F to F. cpanel_json_xs -f storable-file and print a human-readable JSON version of it to STDOUT. cpanel_json_xs -f storable-file -t yaml {"announce-list"}}' -t string Print the tracker list inside a torrent file. lwp-request http://cpantesters.perl.org/show/Cpanel-JSON-XS.json | cpanel_json_xs Fetch the cpan-testers result summary C and pretty-print it. =head1 AUTHOR Copyright (C) 2008 Marc Lehmann =cut use strict; use Getopt::Long; use Storable (); use Encode; use Cpanel::JSON::XS; my $opt_verbose; my $opt_from = "json"; my $opt_to = "json-pretty"; my $opt_eval; Getopt::Long::Configure ("bundling", "no_ignore_case", "require_order"); GetOptions( "v" => \$opt_verbose, "f=s" => \$opt_from, "t=s" => \$opt_to, "e=s" => \$opt_eval, ) or die "Usage: $0 [-v] -f fromformat [-e code] [-t toformat]\n"; sub enc { $_ = shift; my $enc = /^\x00\x00\x00/s ? "utf-32be" : /^\x00.\x00/s ? "utf-16be" : /^.\x00\x00\x00/s ? "utf-32le" : /^.\x00.\x00/s ? "utf-16le" : "utf-8"; warn "input text encoding is $enc\n" if $opt_verbose; $enc; } my %F = ( "none" => sub { undef }, "string" => sub { $_ }, "json" => sub { Cpanel::JSON::XS->new->decode (decode enc($_), $_) }, "json-nonref" => sub { Cpanel::JSON::XS->new->allow_nonref->decode (decode enc($_), $_) }, "json-relaxed" => sub { Cpanel::JSON::XS->new->relaxed->decode (decode enc($_), $_) }, "json-unknown" => sub { Cpanel::JSON::XS->new->allow_unknown->decode (decode enc($_), $_) }, "storable" => sub { Storable::thaw $_ }, "storable-file" => sub { open my $fh, "<", \$_; Storable::fd_retrieve $fh }, "bencode" => sub { require Convert::Bencode; Convert::Bencode::bdecode ($_) }, "clzf" => sub { require Compress::LZF; Compress::LZF::sthaw ($_) }, "yaml" => sub { require YAML; YAML::Load ($_) }, "eval" => sub { my $v = eval "no strict; no warnings; no utf8;\n#line 1 \"input\"\n$_"; die "$@" if $@; $v }, ); my %T = ( "none" => sub { "" }, "string" => sub { $_ }, "json" => sub { encode_json $_ }, "json-utf-8" => sub { encode_json $_ }, "json-pretty" => sub { Cpanel::JSON::XS->new->utf8->pretty->canonical->encode ($_) }, "json-stringify"=> sub { Cpanel::JSON::XS->new->utf8->pretty->canonical->allow_stringify->encode ($_) }, "json-relaxed" => sub { Cpanel::JSON::XS->new->utf8->pretty->canonical ->allow_stringify->allow_blessed->convert_blessed ->allow_unknown->allow_tags->stringify_infnan(1) ->encode ($_) }, "json-utf-16le" => sub { encode "utf-16le", Cpanel::JSON::XS->new->encode ($_) }, "json-utf-16be" => sub { encode "utf-16be", Cpanel::JSON::XS->new->encode ($_) }, "json-utf-32le" => sub { encode "utf-32le", Cpanel::JSON::XS->new->encode ($_) }, "json-utf-32be" => sub { encode "utf-32be", Cpanel::JSON::XS->new->encode ($_) }, "storable" => sub { Storable::nfreeze $_ }, "storable-file" => sub { open my $fh, ">", \my $buf; Storable::nstore_fd $_, $fh; $buf }, "bencode" => sub { require Convert::Bencode; Convert::Bencode::bencode ($_) }, "clzf" => sub { require Compress::LZF; Compress::LZF::sfreeze_cr ($_) }, "yaml" => sub { require YAML; YAML::Dump ($_) }, "dumper" => sub { require Data::Dumper; #local $Data::Dumper::Purity = 1; # hopeless case local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 1; local $Data::Dumper::Useqq = 1; local $Data::Dumper::Quotekeys = 0; local $Data::Dumper::Sortkeys = 1; Data::Dumper::Dumper($_) }, "dump" => sub { require Data::Dump; local $Data::Dump::TRY_BASE64 = 0; Data::Dump::dump ($_) . "\n" }, ); $F{$opt_from} or die "$opt_from: not a valid fromformat\n"; $T{$opt_to} or die "$opt_from: not a valid toformat\n"; if ($opt_from ne "none") { local $/; binmode STDIN; # stupid perl sometimes thinks its funny $_ = ; } $_ = $F{$opt_from}->(); eval $opt_eval; die $@ if $@; $_ = $T{$opt_to}->(); binmode STDOUT; syswrite STDOUT, $_; Cpanel-JSON-XS-3.0210/Changes0000644000076500001200000006772012630026757014555 0ustar rurbanadminRevision history for Perl extension Cpanel::JSON::XS TODO: http://stevehanov.ca/blog/index.php?id=104 compression 3.0210 2015-12-03 (rurban) - improve cpanel_json_xs: more input and output formats - improved various spellings and add test - much faster t/99_binary.t test 3.0209 2015-12-03 (rurban) - Fix nasty regression bug with allow_singlequote or relaxed, hanging with single quotes in normal strings. #54 (reported by Quim Rovira) 3.0208 2015-12-02 (rurban) - Fix regression for is_bool([]), with unblessed references. #53 (reported by Gregory Oschwald) 3.0207 2015-12-02 (rurban) - Fix regression decoding big strings (>16384). #50 (reported by Dan Book) - Ignore allow_barekey if we detect quotes. #51 (Fixed by Quim Rovira) - Skip some unicode tests with 5.6 3.0206 2015-11-30 (rurban) - Add support for escape_slash from JSON::PP. #47 - Map sort_by to canonical from JSON::PP. #47 reverse sort or sort by custom keys not yet possible/silently ignored. - Add support for allow_singlequote from JSON::PP. #47 - Add support for allow_barekey from JSON::PP. #47 - Add support for allow_bignum from JSON::PP. #47 - relaxed uses now also allow_singlequote and allow_barekey. - Fixed t/20_unknown.t: SKIP when JSON is not available. #45 - Fixed t/55_modifiable.t: Broaden the is check of true <5.12 #45 (both reported by Paul Howarth) - Add t/zero-mojibake.t from JSON::PP testing all supported decoding options: none, utf8, ascii, latin1, binary. 3.0205 2015-11-29 (rurban) - Add t/20_unknown.t tests from JSON::PP, extended. - Fix convert_blessed, disallow invalid JSON. #46 (reported by Dan Book) convert_blessed returns now always a string, even for numbers. - Fix encountered GLOB error message (still in JSON::XS, and JSON::PP took over the wrong message also). - Fixed regression of immediate raw values for null/true/false to be modifiable again. #45. Broken with 3.0201 - 3.0204. (reported by Thomas Sibley and Karen Etheridge) This caused failues in Test::JSON and App::RecordStream. 3.0204 2015-11-26 (rurban) - Fix is_bool with JSON::XS >3.0 interop. #44 (Graham Knop) 3.0203 2015-11-26 (rurban) - New optional decode_json() argument to set allow_nonref as in RFC 7159 and PHP. Before 3.02 JSON::XS and Cpanel::JSON::XS always allowed nonref values for decode_json due to an interal bug. 3.0202 2015-11-26 (rurban) - New feature: convert_blessed for encode. Stringify overloaded perl objects and with allow_blessed even without string overload (#37) 3.0201 2015-11-26 (rurban) - Simplify handling of references, removing all the complicated work-around for reblessing. Breaks overloaded values, but fixes serialising refs to readonly values. #21 (Gianni Ceccarelli) new test t/53_readonly.t schmorp thinks that overloading is broken with this patch, but reblessing and breaking readonly is worse. - Stabilize Test::Kwalitee with missing XS dependencies - suggests common::sense, not recommend. #36 (mst) - Boolean interop: use only JSON::PP::Boolean. #40 Remove our own JSON::XS::Boolean, and solely use JSON::PP::Boolean and accept Mojo::JSON::_Bool and Types::Serialiser::Boolean, which is aliased to JSON::PP::Boolean. JSON::YAJL::Parser just produces an unbless IV (0|1). fix overload of our bools. stringify true to "true", false to "0" - accept Mojo::JSON::_Bool (#37) Mojo does not store their booleans as JSON::PP::Boolean as everybody else does. - accept is_bool as method call also. - implement native encode_sv of the internal sv_yes/sv_no values (#39) and map them to json true/false. YAML::XS compatible. - pod: add SECURITY CONSIDERATIONS added a table of safe and unsafe serializers for comparison. Written by JD Lightsey. Only JSON and Data::MessagePack are safe by default. - With canonical only skip hash keys sorting for actually tied hashes. #42 (Sergey Aleynikov) 3.0115 2015-01-31 (rurban) - Fix stack corruption when encoding nested objects with FREEZE method, #35 (Sergey Aleynikov) 3.0114 2015-01-04 (rurban) - Fix bad powl with Freebsd 10 -Duselongdouble. Rather use strtold. #34 + RT #101265 3.0113 2014-12-15 (rurban) - t/117_number relax the tests for negative nan, as BSDs also cannot deal with it. #33 3.0112 2014-12-14 (rurban) - Add {get_,}stringify_infnan methods and use it in the test, now run-time. #32 mode 0: null, 1: stringify, 2: inf/nan (invalid JSON) as before. - Fix t/117_number tests for Solaris and MSWin32 - Remove build-time "Do you want to handle inf/nan as strings? Default: null." prompt. - Improve docs. 3.0111 2014-12-13 (rurban) - Fixed detecting 1.#INF/1.#IND on windows. #28 - Also detect now -inf and -nan. #28 - Fixed STRINGIFY_INFNAN return string, length off by one. #28 - Fixed a non-C99 declaration error on XS.xs:863. Was broken with older MSVC. 3.0110 2014-12-12 (rurban) - Fixed one more memory bug with encode of dual-vars to strings, esp. with older perl <5.10, leading to eventual panic: realloc. 3.0109 2014-12-12 (rurban) - Fixed serious bug with encode of dual-vars to strings, missing the ending \0. #31 (Grinnz) 3.0108 2014-12-11 (rurban) - Change encode of numbers with dual-strings (int and float), integers and numbers are now not mishandled anymore by dual-vars, temp. string representations. Add t/117_numbers.t from JSON::PP, PR#10 by kraih. - Add prompt for nan/inf encode policy: null or stringify. - Change stringification of false and true to 0 and 1, matching upstream JSON and JSON::XS, #29. This didn't affect string comparisons, just e.g. print decode_json("false"). - Tolerate literal ASCII TABs in strings in relaxed mode #22 (from JSON::XS) - Revise pod, merge updates from JSON::XS. - Fix pod typo #30 (Colin Kuskie) 3.0107 2014-11-28 (rurban) - fix fatal stack corruption with perl callbacks in list context #27 (dur-randir) 3.0106 2014-11-11 (rurban) - more minor doc improvements #26 (schwern) 3.0105 2014-11-05 (rurban) - minor doc improvements #25 (ether) - fix d_Gconvert test in t/11_pc_expo.t for 5.6 3.0104 2014-04-26 (rurban) - add t/z_leaktrace.t - restore build on C89 (bulk88) - fix small cxt->sv_json leak on interp exit (bulk88) 3.0103 2014-04-21 (rurban) - Change booleans interop logic (again) for JSON-XS-3.01 Check now for Types::Serialiser::Boolean ie JSON::PP::Boolean refs (#18 clintongormley) to avoid allow_blessed for JSON-XS-3.01 booleans. - fix boolean representation for JSON-XS-3.01/Types::Serialiser::Boolean interop (arrayref, not hashref) - add t/52_object.t from JSON::XS - backport encode_hv HE sort on stack < 64 or heap to avoid stack overflows from JSON-XS-3.01. do not use alloca. - backport allow_tags, decode_tag, FREEZE/THAW callbacks from JSON-XS-3.01 - added pod for OBJECT SERIALISATION (allow_tags, FREEZE/THAW) 3.0102 2014-04-17 (rurban + bulk88) - Added PERL_NO_GET_CONTEXT for better performance on threaded Perls (bulk88) - MANIFEST: added t/96_interop.t - Document deprecated functions - Change booleans interop logic for JSON-XS-3.01 3.0101 2014-04-15 (rurban + bulk88) - Added ithreads support (bulk88) Cpanel::JSON::XS is now thread-safe. - const'ed a translation table for memory savings (bulk88) - Fixed booleans for JSON 2.9 and JSON-XS-3.01 interop. JSON does not support JSON::XS booleans anymore, so I cannot think of any reason to still use JSON::XS. 2.3404 2014-01-30 (rurban) - fix interop with JSON::XS booleans the internal boolean objects are now blessed into JSON::XS::Boolean #13 and [cpan #92548] (samuel.c.kaufman) - t/96_interop.t: added - LICENSE section to pod added for t/z_kwalitee.t - README: fixed some pod spelling errors in (David Steinbrunner) 2.3403 2013-11-02 (cpanel) - fix json_atof on AIX without HAS_LONG_DOUBLE (powl in libm) [cpan #88061] (Ulisse Monari, Reini Urban) 2.3402 2013-11-02 (cpanel) - t/97_unshare_hek.t: fix issue #10, unshare hek assertion resp. valgrind error - Rename internal 5.6 methods {from|to}_json_ to _{from|to}_json - Fixed get_binary pod - Added t/z_*.t maintainer tests 2.3401 2013-10-02 (cpanel) - add more binary tests, including 5.6 - improve POD for binary and cPanel fork - Fix homepage META 2.3314 2013-09-09 (cpanel) - t/01_utf8.t: workaround for stricter Encode versions (syohex) - autogenerate META files 2.3313 2013-06-26 (cpanel) - Fix re-blessing of READONLY data (chip) [GH issue #7]. - Depend on Pod::Usage 1.36. 1.51 was added with 2.3306 - t/01_utf8.t: workaround for stricter Encode versions [RT #84244] - avoid <5.10 const warnings with sv_chop 2.3312 2013-05-22 (cpanel) - Made common::sense optional to get smaller FatPacker packages. 2.3311 2013-04-04 18:41:23 (cpanel) - Changed maintainer to cpan@cpanel.net - Changed tracker to RT - Worked on JSON integration (matching prototypes) - Fixed Boolean stringify and eq overload methods to match JSON (Fixes JSON tests) 2.3310 2013-03-28 12:20:11 (rurban) - add testcases for JSON::XS RT #84244, double-encoding with utf8 t/01_utf8.t (use utf8), t/14_latin1.t (no utf8) - t/01_utf8.t: enable and fix more 5.6 testcases 2.3309 2013-03-28 09:37:29 (rurban) - fix 19_incr.t broken with 5.17.10 hash randomization [JSON::XS RT #84151] by wyant @ cpan.org 2.3308 2013-03-28 09:10:45 (rurban) - fix 5.6 binary utf8 encoding, harmonized with newer perls 5.6. encodes strings to utf8 internally when seeing a codepoint >= 0x80. with binary decode it to the original bytes before encoding it to escaped JSON. 2.3307 2013-03-27 17:27:18 (rurban) - fix lots of -Wincompatible-pointer-types and -Wpointer-sign warnings - add binary method - write and accept \xNN JSON encoding with binary only, also accept octal \0NNN JSON with binary 2.3306 2013-03-27 12:15:20 (rurban) - fix decode_utf8 for 5.6 (bdraco) - use common::sense for tests - fix README dependency: update earlier, not just at make dist - added pod2text prereqs 2.3305 2013-03-27 11:47:36 (rurban) - nondev version to be indexed in CPAN - t/99_binary.t: non-numeric test names, use is instead of ok - added META data to Makefile.PL 2.33_04 2013-03-01 15:42:39 (rurban) - fix for 5.6 compiler: $json->incr_text may not be called as lvalue, missing attributes::reftype 2.33_03 2013-02-28 17:22:52 (bdraco) - revert fix crash with invalid JSON, empty sv 2.33_02 2012-08-17 16:29:52 (rurban) - fix crash with invalid JSON, empty sv 2.33_01 2012-08-08 16:29:52 (rurban) - merge with JSON-XS-2.33 2.33 Wed Aug 1 21:03:52 CEST 2012 - internal encode/decode XS wrappers did not expect stack moves caused by callbacks (analyzed and testcase by Jesse Luehrs). - add bencode as to/from option in bin/json_xs. - add -e option to json_xs, and none and string in/out formats. 2.32_02 Wed Jun 27 19:59:18 2012 (rurban) - forked from JSON-XS-2.32 - Cpanel perl-5.6.2 support - prefix with Cpanel 2.32 Thu Aug 11 19:06:38 CEST 2011 - fix a bug in the initial whitespace accumulation. 2.31 Wed Jul 27 17:53:05 CEST 2011 - don't accumulate initial whitespace in the incremental buffer (this can be useful to allow whitespace-keepalive on a tcp connection without triggering the max_size limit). - properly croak on some invalid inputs that are not strings (e.g. undef) when trying to decode a json text (reported and analyzed by Goro Fuji). 2.3 Wed Aug 18 01:26:47 CEST 2010 - make sure decoder doesn't change the decoding in the incremental parser (testcase provided by Hendrik Schumacher). - applied patch by DaTa for Data::Dumper support in json_xs. - added -t dump support to json_xs, using Data::Dump. - added -f eval support to json_xs. 2.29 Wed Mar 17 02:39:12 CET 2010 - fix a memory leak when callbacks set using filter_json_object or filter_json_single_key_object were called (great testcase by Eric Wilhelm). 2.28 Thu Mar 11 20:30:46 CET 2010 - implement our own atof function - perl's can be orders of magnitudes slower than even the system one. on the positive side, ours seems to be more exact in general than perl's. (testcase provided by Tim Meadowcroft). - clarify floating point conversion issues a bit. - update jpsykes csrf article url. - updated benchmark section - JSON::PP became much faster! 2.27 Thu Jan 7 07:35:08 CET 2010 - support relaxed option inside the incremental parser (testcase provided by IKEGAMI via Makamaka). 2.26 Sat Oct 10 03:26:19 CEST 2009 - big integers could become truncated (based on patch by Strobl Anton). - output format change: indent now adds a final newline, which is more expected and more true to the documentation. 2.25 Sat Aug 8 12:04:41 CEST 2009 - the perl debugger completely breaks lvalue subs - try to work around the issue. - ignore RMAGICAL hashes w.r.t. CANONICAL. - try to work around a possible char signedness issue on aix. - require common sense. 2.24 Sat May 30 08:25:45 CEST 2009 - the incremental parser did not update its parse offset pointer correctly when parsing utf8-strings (nicely debugged by Martin Evans). - appending a non-utf8-string to the incremental parser in utf8 mode failed to upgrade the string. - wording of parse error messages has been improved. 2.232 Sun Feb 22 11:12:25 CET 2009 - use an exponential algorithm to extend strings, to help platforms with bad or abysmal==windows memory allocater performance, at the expense of some memory wastage (use shrink to recover this extra memory). (nicely analysed by Dmitry Karasik). 2.2311 Thu Feb 19 02:12:54 CET 2009 - add a section "JSON and ECMAscript" to explain some incompatibilities between the two (problem was noted by various people). - add t/20_faihu.t. 2.231 Thu Nov 20 04:59:08 CET 2008 - work around 5.10.0 magic bugs where manipulating magic values (such as $1) would permanently damage them as perl would ignore the magicalness, by making a full copy of the string, reported by Dmitry Karasik. - work around spurious warnings under older perl 5.8's. 2.23 Mon Sep 29 05:08:29 CEST 2008 - fix a compilation problem when perl is not using char * as, well, char *. - use PL_hexdigit in favour of rolling our own. 2.2222 Sun Jul 20 18:49:00 CEST 2008 - same game again, broken 5.10 finds yet another assertion failure, and the workaround causes additional runtime warnings. Work around the next assertion AND the warning. 5.10 seriously needs to adjust it's attitude against working code. 2.222 Sat Jul 19 06:15:34 CEST 2008 - you work around one -DDEBUGGING assertion bug in perl 5.10 just to hit the next one. work around this one, too. 2.22 Tue Jul 15 13:26:51 CEST 2008 - allow higher nesting levels in incremental parser. - error out earlier in some cases in the incremental parser (as suggested by Yuval Kogman). - improve incr-parser test (Yuval Kogman). 2.21 Tue Jun 3 08:43:23 CEST 2008 - (hopefully) work around a perl 5.10 bug with -DDEBUGGING. - remove the experimental status of the incremental parser interface. - move =encoding around again, to avoid bugs with search.cpan.org. when can we finally have utf-8 in pod??? - add ->incr_reset method. 2.2 Wed Apr 16 20:37:25 CEST 2008 - lifted the log2 rounding restriction of max_depth and max_size. - make booleans mutable by creating a copy instead of handing out the same scalar (reported by pasha sadri). - added support for incremental json parsing (still EXPERIMENTAL). - implemented and added a json_xs command line utility that can convert from/to a number of serialisation formats - tell me if you need more. - implement allow_unknown/get_allow_unknown methods. - fixed documentation of max_depth w.r.t. higher and equal. - moved down =encoding directive a bit, too much breaks if it's the first pod directive :/. - removed documentation section on other modules, it became somewhat outdated and is nowadays mostly of historical interest. 2.1 Wed Mar 19 23:23:18 CET 2008 - update documentation here and there: add a large section about utf8/latin1/ascii flags, add a security consideration and extend and clarify the JSON and YAML section. - medium speed enhancements when encoding/decoding non-ascii chars. - minor speedup in number encoding case. - extend and clarify the section on incompatibilities between YAML and JSON. - switch to static inline from just inline when using gcc. - add =encoding utf-8 to the manpage, now that perl 5.10 supports it. - fix some issues with UV to JSON conversion of unknown impact. - published the yahoo locals search result used in benchmarks as the original url changes so comparison is impossible. 2.01 Wed Dec 5 11:40:28 CET 2007 - INCOMPATIBLE API CHANGE: to_json and from_json have been renamed to encode_json/decode_json for JSON.pm compatibility. The old functions croak and might be replaced by JSON.pm comaptible versions in some later release. 2.0 Tue Dec 4 11:30:46 CET 2007 - this is supposed to be the first version of JSON::XS compatible with version 2.0+ of the JSON module. Using the JSON module as frontend to JSON::XS should be as fast as using JSON::XS directly, so consider using it instead. - added get_* methods for all "simple" options. - make JSON::XS subclassable. 1.53 Tue Nov 13 23:58:33 CET 2007 - minor doc clarifications. - fixed many doc typos (patch by Thomas L. Shinnick). 1.52 Mon Oct 15 03:22:06 CEST 2007 - remove =encoding pod directive again, it confuses too many pod parsers :/. 1.51 Sat Oct 13 03:55:56 CEST 2007 - encode empty arrays/hashes in a compact way when pretty is enabled. - apparently JSON::XS was used to find some bugs in the JSON_checker testsuite, so add (the corrected) JSON_checker tests to the testsuite. - quite a bit of doc updates/extension. - require 5.8.2, as this seems to be the first unicode-stable version. 1.5 Tue Aug 28 04:05:38 CEST 2007 - add support for tied hashes, based on ideas and testcase by Marcus Holland-Moritz. - implemented relaxed parsing mode where some extensions are being accepted. generation is still JSON-only. 1.44 Wed Aug 22 01:02:44 CEST 2007 - very experimental process-emulation support, slowing everything down. the horribly broken perl threads are still not supported - YMMV. 1.43 Thu Jul 26 13:26:37 CEST 2007 - convert big json numbers exclusively consisting of digits to NV only when there is no loss of precision, otherwise to string. 1.42 Tue Jul 24 00:51:18 CEST 2007 - fix a crash caused by not handling missing array elements (report and testcase by Jay Kuri). 1.41 Tue Jul 10 18:21:44 CEST 2007 - fix compilation with NDEBUG (assert side-effect), affects convert_blessed only. - fix a bug in decode filters calling ENTER; SAVETMPS; one time too often. - catch a typical error in TO_JSON methods. - antique-ised XS.xs again to work with outdated C compilers (windows...). 1.4 Mon Jul 2 10:06:30 CEST 2007 - add convert_blessed setting. - encode did not catch all blessed objects, encoding their contents in most cases. This has been fixed by introducing the allow_blessed setting. - added filter_json_object and filter_json_single_key_object settings that specify a callback to be called when all/specific json objects are encountered. - assume that most object keys are simple ascii words and optimise this case, penalising the general case. This can speed up decoding by 30% in typical cases and gives a smaller and faster perl hash. - implemented simpleminded, optional resource size checking in decode_json. - remove objToJson/jsonToObj aliases, as the next version of JSON will not have them either. - bit the bullet and converted the very simple json object into a more complex one. - work around a bug where perl wrongly claims an integer is not an integer. - unbundle JSON::XS::Boolean into own pm file so Storable and similar modules can resolve the overloading when thawing. 1.3 Sun Jun 24 01:55:02 CEST 2007 - make JSON::XS::true and false special overloaded objects and return those instead of 1 and 0 for those json atoms (JSON::PP compatibility is NOT achieved yet). - add JSON::XS::is_bool predicate to test for those special values. - add a reference to http://jpsykes.com/47/practical-csrf-and-json-security. - removed require 5.8.8 again, it is just not very expert-friendly. Also try to be more compatible with slightly older versions, which are not recommended (because they are buggy). 1.24 Mon Jun 11 05:40:49 CEST 2007 - added informative section on JSON-as-YAML. - get rid of some c99-isms again. - localise dec->cur in decode_str, speeding up string decoding considerably (>15% on my amd64 + gcc). - increased SHORT_STRING_LEN to 16kb: stack space is usually plenty, and this actually saves memory when !shrinking as short strings will fit perfectly. 1.23 Wed Jun 6 20:13:06 CEST 2007 - greatly improved small integer encoding and decoding speed. - implement a number of µ-optimisations. - updated benchmarks. 1.22 Thu May 24 00:07:25 CEST 2007 - require 5.8.8 explicitly as older perls do not seem to offer the required macros. - possibly made it compile on so-called C compilers by microsoft. 1.21 Wed May 9 18:40:32 CEST 2007 - character offset reported for trailing garbage was random. 1.2 Wed May 9 18:35:01 CEST 2007 - decode did not work with magical scalars (doh!). - added latin1 flag to produce JSON texts in the latin1 subset of unicode. - flag trailing garbage as error. - new decode_prefix method that returns the number of characters consumed by a decode. - max octets/char in perls UTF-X is actually 13, not 11, as pointed out by Glenn Linderman. - fixed typoe reported by YAMASHINA Hio. 1.11 Mon Apr 9 07:05:49 CEST 2007 - properly 0-terminate sv's returned by encode to help C libraries that expect that 0 to be there. - partially "port" JSON from C to microsofts fucking broken pseudo-C. They should be burned to the ground for pissing on standards. And I should be stoned for even trying to support this filthy excuse for a c compiler. 1.1 Wed Apr 4 01:45:00 CEST 2007 - clarify documentation (pointed out by Quinn Weaver). - decode_utf8 sometimes did not correctly flag errors, leading to segfaults. - further reduced default nesting depth to 512 due to the test failure by that anonymous "chris" whose e-mail address seems to be impossible to get. Tests on other freebsd systems indicate that this is likely a problem in his/her configuration and not this module. - renamed json => JSON in error messages. - corrected the character offset in some error messages. 1.01 Sat Mar 31 16:15:40 CEST 2007 - do not segfault when from_json/decode gets passed a non-string object (reported by Florian Ragwitz). This has no effect on normal operation. 1.0 Thu Mar 29 04:43:34 CEST 2007 - the long awaited (by me) 1.0 version. - add \0 (JSON::XS::false) and \1 (JSON::XS::true) mappings to JSON true and false. - add some more notes to shrink, as suggested by Alex Efros. - improve testsuite. - halve the default nesting depth limit, to hopefully make it work on Freebsd (unfortunately, the cpan tester did not send me his report, so I cannot ask about the stack limit on fbsd). 0.8 Mon Mar 26 00:10:48 CEST 2007 - fix a memleak when decoding hashes. - export jsonToBj and objToJson as aliases to to_json and from_json, to reduce incompatibilities between JSON/JSON::PC and JSON::XS. (experimental). - implement a maximum nesting depth for both en- and de-coding. - added a security considerations sections. 0.7 Sun Mar 25 01:46:30 CET 2007 - code cleanup. - fix a memory overflow bug when indenting. - pretty-printing now up to 15% faster. - improve decoding speed of strings by up to 50% by specialcasing short strings. - further decoding speedups for strings using lots of \u escapes. - improve utf8 decoding speed for U+80 .. U+7FF. 0.5 Sat Mar 24 20:41:51 CET 2007 - added the UTF-16 encoding example hinted at in previous versions. - minor documentation fixes. - fix a bug in and optimise canonicalising fastpath (reported by Craig Manley). - remove a subtest that breaks with bleadperl (reported by Andreas König). 0.31 Sat Mar 24 02:14:34 CET 2007 - documentation updates. - do some casting to hopefully fix Andreas' problem. - nuke bogus json rpc stuff. 0.3 Fri Mar 23 19:33:21 CET 2007 - remove spurious PApp::Util reference (John McNamara). - adapted lots of tests from other json modules (idea by Chris Carline). - documented mapping from json to perl and vice versa. - improved the documentation by adding more examples. - added short escaping forms, reducing the created json texts a bit. - added shrink flag. - when flag methods are called without enable argument they will by default enable their flag. - considerably improved string encoding speed (at least with gcc 4). - added a test that covers lots of different characters. - clarified some error messages. - error messages now use correct character offset with F_UTF8. - improve the "no bytes" and "no warnings" hacks in case the called functions do... stuff. - croak when encoding to ascii and an out-of-range (non-unicode) codepoint is encountered. 0.2 Fri Mar 23 00:23:34 CET 2007 - the "could not sleep without debugging release". it should basically work now, with many bugs as no production tests have been run yet. - added more testcases. - the expected shitload of bugfixes. - handle utf8 flag correctly in decode. - fix segfault in decoder. - utf8n_to_uvuni sets retlen to -1, but retlen is an unsigned types (argh). - fix decoding of utf-8 strings. - improved error diagnostics. - fix decoding of 'null'. - fix parsing of empty array/hashes - silence warnings when we prepare the croak message. 0.1 Thu Mar 22 22:13:43 CET 2007 - first release, very untested, basically just to claim the namespace. 0.01 Thu Mar 22 06:08:12 CET 2007 - original version; cloned from Convert-Scalar Cpanel-JSON-XS-3.0210/COPYING0000644000076500001200000000007612463231643014300 0ustar rurbanadminThis module is licensed under the same terms as perl itself. Cpanel-JSON-XS-3.0210/eg/0000755000076500001200000000000012630027156013633 5ustar rurbanadminCpanel-JSON-XS-3.0210/eg/bench0000755000076500001200000000526012463231643014645 0ustar rurbanadmin#!/opt/bin/perl # Usage: bench json-file # which modules to test (JSON::PP usually excluded because its so slow) my %tst = ( # "JSON" => ['JSON::encode_json $perl' , 'JSON::decode_json $json'], "JSON::PP" => ['$pp->encode ($perl)' , '$pp->decode ($json)'], "JSON::DWIW/FJ" => ['$dwiw->to_json ($perl)' , '$dwiw->from_json ($json)'], "JSON::DWIW/DS" => ['$dwiw->to_json ($perl)' , 'JSON::DWIW::deserialize $json'], # "JSON::PC" => ['$pc->convert ($perl)' , '$pc->parse ($json)'], "JSON::Syck" => ['JSON::Syck::Dump $perl' , 'JSON::Syck::Load $json'], "Cpanel::JSON::XS" => ['encode_json $perl' , 'decode_json $json'], "Cpanel::JSON::XS/2" => ['$xs2->encode ($perl)' , '$xs2->decode ($json)'], "Cpanel::JSON::XS/3" => ['$xs3->encode ($perl)' , '$xs3->decode ($json)'], "Storable" => ['Storable::nfreeze $perl' , 'Storable::thaw $pst'], ); use JSON (); use JSON::DWIW; use JSON::PC; use JSON::PP (); use Cpanel::JSON::XS qw(encode_json decode_json); use JSON::Syck; use Storable (); use Time::HiRes; use List::Util; use utf8; my $dwiw = new JSON::DWIW; my $pc = new JSON::PC; my $pp = JSON::PP->new->max_depth (512); my $xs2 = Cpanel::JSON::XS->new->utf8->pretty->canonical; my $xs3 = Cpanel::JSON::XS->new->utf8->shrink; my $json; # the test string local $/; $json = <>; # fix syck-brokenised stuff #$json = Cpanel::JSON::XS->new->ascii(1)->encode (JSON::Syck::Load $json); #srand 0; $json = Cpanel::JSON::XS->new->utf8(1)->ascii(0)->encode ([join "", map +(chr rand 255), 0..2047]); #if (1) { # use Storable; # open my $fh, "<:unix", "/opt/crossfire/share/cfserver/faces" or die "$!"; # my $faces = Storable::thaw do { <$fh> }; # $json = objToJson $faces; # open my $fh2, ">:unix", "faces.json" or die "$!"; # print $fh2 $json; # warn length $json; #} sub bench($) { my ($code) = @_; my $pst = Storable::nfreeze Cpanel::JSON::XS::decode_json $json; # seperately decode as storable stringifies :/ my $perl = Cpanel::JSON::XS::decode_json $json; my $count = 5; my $times = 200; my $cent = eval "sub { my \$t = Time::HiRes::time; " . (join ";", ($code) x $count) . "; Time::HiRes::time - \$t }"; $cent->(); my $min = 1e99; for (1..$times) { my $t = $cent->(); $min = $t if $t < $min; } return $count / $min; } printf "%-13s | %10s | %10s |\n", "module", "encode", "decode"; printf "--------------|------------|------------|\n"; for my $module (sort keys %tst) { my $enc = bench $tst{$module}[0]; my $dec = bench $tst{$module}[1]; printf "%-13s | %10.3f | %10.3f |\n", $module, $enc, $dec; } printf "--------------+------------+------------+\n"; Cpanel-JSON-XS-3.0210/Makefile.PL0000644000076500001200000000442712625703626015230 0ustar rurbanadminuse 5.006002; use ExtUtils::MakeMaker; use Config (); WriteMakefile( dist => { PREOP => 'pod2text XS.pm | tee README >$(DISTVNAME)/README; chmod -R u=rwX,go=rX . ;', COMPRESS => 'gzip -9v', SUFFIX => '.gz', }, EXE_FILES => [ "bin/cpanel_json_xs" ], VERSION_FROM => "XS.pm", NAME => "Cpanel::JSON::XS", PREREQ_PM => { 'Pod::Text' => '2.08', 'Pod::Usage' => '1.33', }, LICENSE => 'perl', ($] >= 5.005 ? (ABSTRACT_FROM => 'XS.pm', AUTHOR => 'Reini Urban ', # ORIGINAL_AUTHOR => 'Marc Lehmann ' ) : ()), ($ExtUtils::MakeMaker::VERSION gt '6.46' ? ('META_MERGE' => { prereqs => { runtime => { requires => { # just the script, not the module 'Encode' => '1.9801', } }, test => { requires => { 'Encode' => '1.9801', 'Time::Piece' => 0, }, suggests => { 'common::sense' => '3.5', 'Mojo::JSON' => '6.11', 'JSON' => 0, 'JSON::XS' => 0, 'JSON::PP' => 0, 'Test::LeakTrace' => 0, 'Test::MinimumVersion' => '0.008', 'Perl::MinimumVersion' => '1.20', 'Test::CPAN::Meta' => '0.12', 'Test::Pod' => '1.00', 'Test::Pod::Coverage' => '1.04', } } }, resources => { license => 'http://dev.perl.org/licenses/', bugtracker => 'https://github.com/rurban/Cpanel-JSON-XS/issues', # Note: https://rt.cpan.org/Public/Dist/Display.html?Queue=Cpanel-JSON-XS is also observed repository => 'https://github.com/rurban/Cpanel-JSON-XS', homepage => 'http://software.schmorp.de/pkg/JSON-XS.html', }, } ) : ()), SIGN => 1, ); package MY; sub test { local $_ = shift->SUPER::test(@_); eval { require common::sense; }; unless ($@) { s/TEST_FILES = /TEST_FILES = -Mcommon::sense /; } $_ } sub top_targets { local $_ = shift->SUPER::top_targets(@_); s/\$\(FIRST_MAKEFILE\) blibdirs/\$(FIRST_MAKEFILE\) blibdirs README/; $_ } sub depend { " README : \$(VERSION_FROM) pod2text \$(VERSION_FROM) > README " } Cpanel-JSON-XS-3.0210/MANIFEST0000644000076500001200000000255412630027157014400 0ustar rurbanadmin.travis.yml README Changes MANIFEST COPYING ppport.h Makefile.PL XS.pm XS.xs XS/Boolean.pm bin/cpanel_json_xs eg/bench t/00_load.t t/01_utf8.t t/02_error.t t/03_types.t t/04_dwiw_encode.t t/05_dwiw_decode.t t/06_pc_pretty.t t/07_pc_esc.t t/08_pc_base.t t/08_pc_base_nv.t t/09_pc_extra_number.t t/10_pc_keysort.t t/11_pc_expo.t t/12_blessed.t t/13_limit.t t/14_latin1.t t/15_prefix.t t/16_tied.t t/17_relaxed.t t/18_json_checker.t t/19_incr.t t/20_faihu.t t/20_unknown.t t/21_evans.t t/22_comment_at_eof.t t/23_array_ctx.t t/24_freeze_recursion.t t/25_boolean.t t/52_object.t t/53_readonly.t t/54_stringify.t t/55_modifiable.t t/96_interop.t t/96_mojo.t t/97_unshare_hek.t t/98_56only.t t/99_binary.t t/104_sortby.t t/105_esc_slash.t t/106_allow_barekey.t t/107_allow_singlequote.t t/108_decode.t t/109_encode.t t/110_bignum.t t/112_upgrade.t t/113_overloaded_eq.t t/114_decode_prefix.t t/115_tie_ixhash.t t/116_incr_parse_fixed.t t/117_numbers.t t/_unicode_handling.pm t/zero-mojibake.t t/z_kwalitee.t t/z_leaktrace.t t/z_meta.t t/z_perl_minimum_version.t t/z_pod-coverage.t t/z_pod-spelling.t t/z_pod-spell-mistakes.t t/z_pod.t typemap META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) SIGNATURE Public-key signature (added by MakeMaker) Cpanel-JSON-XS-3.0210/META.json0000644000076500001200000000250612630027157014665 0ustar rurbanadmin{ "abstract" : "cPanel fork of JSON::XS, fast and correct serializing", "author" : [ "Reini Urban " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.1, CPAN::Meta::Converter version 2.150005", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Cpanel-JSON-XS", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Pod::Text" : "2.08", "Pod::Usage" : "1.33" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/rurban/Cpanel-JSON-XS/issues" }, "homepage" : "http://software.schmorp.de/pkg/JSON-XS.html", "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "url" : "https://github.com/rurban/Cpanel-JSON-XS" } }, "version" : "3.0210", "x_serialization_backend" : "JSON::PP version 2.27300" } Cpanel-JSON-XS-3.0210/META.yml0000644000076500001200000000147712630027157014523 0ustar rurbanadmin--- abstract: 'cPanel fork of JSON::XS, fast and correct serializing' author: - 'Reini Urban ' build_requires: ExtUtils::MakeMaker: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.1, CPAN::Meta::Converter version 2.150005' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Cpanel-JSON-XS no_index: directory: - t - inc requires: Pod::Text: '2.08' Pod::Usage: '1.33' resources: bugtracker: https://github.com/rurban/Cpanel-JSON-XS/issues homepage: http://software.schmorp.de/pkg/JSON-XS.html license: http://dev.perl.org/licenses/ repository: https://github.com/rurban/Cpanel-JSON-XS version: '3.0210' x_serialization_backend: 'CPAN::Meta::YAML version 0.016' Cpanel-JSON-XS-3.0210/ppport.h0000644000076500001200000054004412463231643014746 0ustar rurbanadmin#if 0 <<'SKIP'; #endif /* ---------------------------------------------------------------------- ppport.h -- Perl/Pollution/Portability Version 3.20 Automatically created by Devel::PPPort running under perl 5.014002. Do NOT edit this file directly! -- Edit PPPort_pm.PL and the includes in parts/inc/ instead. Use 'perldoc ppport.h' to view the documentation below. ---------------------------------------------------------------------- SKIP =pod =head1 NAME ppport.h - Perl/Pollution/Portability version 3.20 =head1 SYNOPSIS perl ppport.h [options] [source files] Searches current directory for files if no [source files] are given --help show short help --version show version --patch=file write one patch file with changes --copy=suffix write changed copies with suffix --diff=program use diff program and options --compat-version=version provide compatibility with Perl version --cplusplus accept C++ comments --quiet don't output anything except fatal errors --nodiag don't show diagnostics --nohints don't show hints --nochanges don't suggest changes --nofilter don't filter input files --strip strip all script and doc functionality from ppport.h --list-provided list provided API --list-unsupported list unsupported API --api-info=name show Perl API portability information =head1 COMPATIBILITY This version of F is designed to support operation with Perl installations back to 5.003, and has been tested up to 5.11.5. =head1 OPTIONS =head2 --help Display a brief usage summary. =head2 --version Display the version of F. =head2 --patch=I If this option is given, a single patch file will be created if any changes are suggested. This requires a working diff program to be installed on your system. =head2 --copy=I If this option is given, a copy of each file will be saved with the given suffix that contains the suggested changes. This does not require any external programs. Note that this does not automagially add a dot between the original filename and the suffix. If you want the dot, you have to include it in the option argument. If neither C<--patch> or C<--copy> are given, the default is to simply print the diffs for each file. This requires either C or a C program to be installed. =head2 --diff=I Manually set the diff program and options to use. The default is to use C, when installed, and output unified context diffs. =head2 --compat-version=I Tell F to check for compatibility with the given Perl version. The default is to check for compatibility with Perl version 5.003. You can use this option to reduce the output of F if you intend to be backward compatible only down to a certain Perl version. =head2 --cplusplus Usually, F will detect C++ style comments and replace them with C style comments for portability reasons. Using this option instructs F to leave C++ comments untouched. =head2 --quiet Be quiet. Don't print anything except fatal errors. =head2 --nodiag Don't output any diagnostic messages. Only portability alerts will be printed. =head2 --nohints Don't output any hints. Hints often contain useful portability notes. Warnings will still be displayed. =head2 --nochanges Don't suggest any changes. Only give diagnostic output and hints unless these are also deactivated. =head2 --nofilter Don't filter the list of input files. By default, files not looking like source code (i.e. not *.xs, *.c, *.cc, *.cpp or *.h) are skipped. =head2 --strip Strip all script and documentation functionality from F. This reduces the size of F dramatically and may be useful if you want to include F in smaller modules without increasing their distribution size too much. The stripped F will have a C<--unstrip> option that allows you to undo the stripping, but only if an appropriate C module is installed. =head2 --list-provided Lists the API elements for which compatibility is provided by F. Also lists if it must be explicitly requested, if it has dependencies, and if there are hints or warnings for it. =head2 --list-unsupported Lists the API elements that are known not to be supported by F and below which version of Perl they probably won't be available or work. =head2 --api-info=I Show portability information for API elements matching I. If I is surrounded by slashes, it is interpreted as a regular expression. =head1 DESCRIPTION In order for a Perl extension (XS) module to be as portable as possible across differing versions of Perl itself, certain steps need to be taken. =over 4 =item * Including this header is the first major one. This alone will give you access to a large part of the Perl API that hasn't been available in earlier Perl releases. Use perl ppport.h --list-provided to see which API elements are provided by ppport.h. =item * You should avoid using deprecated parts of the API. For example, using global Perl variables without the C prefix is deprecated. Also, some API functions used to have a C prefix. Using this form is also deprecated. You can safely use the supported API, as F will provide wrappers for older Perl versions. =item * If you use one of a few functions or variables that were not present in earlier versions of Perl, and that can't be provided using a macro, you have to explicitly request support for these functions by adding one or more C<#define>s in your source code before the inclusion of F. These functions or variables will be marked C in the list shown by C<--list-provided>. Depending on whether you module has a single or multiple files that use such functions or variables, you want either C or global variants. For a C function or variable (used only in a single source file), use: #define NEED_function #define NEED_variable For a global function or variable (used in multiple source files), use: #define NEED_function_GLOBAL #define NEED_variable_GLOBAL Note that you mustn't have more than one global request for the same function or variable in your project. Function / Variable Static Request Global Request ----------------------------------------------------------------------------------------- PL_parser NEED_PL_parser NEED_PL_parser_GLOBAL PL_signals NEED_PL_signals NEED_PL_signals_GLOBAL eval_pv() NEED_eval_pv NEED_eval_pv_GLOBAL grok_bin() NEED_grok_bin NEED_grok_bin_GLOBAL grok_hex() NEED_grok_hex NEED_grok_hex_GLOBAL grok_number() NEED_grok_number NEED_grok_number_GLOBAL grok_numeric_radix() NEED_grok_numeric_radix NEED_grok_numeric_radix_GLOBAL grok_oct() NEED_grok_oct NEED_grok_oct_GLOBAL load_module() NEED_load_module NEED_load_module_GLOBAL my_snprintf() NEED_my_snprintf NEED_my_snprintf_GLOBAL my_sprintf() NEED_my_sprintf NEED_my_sprintf_GLOBAL my_strlcat() NEED_my_strlcat NEED_my_strlcat_GLOBAL my_strlcpy() NEED_my_strlcpy NEED_my_strlcpy_GLOBAL newCONSTSUB() NEED_newCONSTSUB NEED_newCONSTSUB_GLOBAL newRV_noinc() NEED_newRV_noinc NEED_newRV_noinc_GLOBAL newSV_type() NEED_newSV_type NEED_newSV_type_GLOBAL newSVpvn_flags() NEED_newSVpvn_flags NEED_newSVpvn_flags_GLOBAL newSVpvn_share() NEED_newSVpvn_share NEED_newSVpvn_share_GLOBAL pv_display() NEED_pv_display NEED_pv_display_GLOBAL pv_escape() NEED_pv_escape NEED_pv_escape_GLOBAL pv_pretty() NEED_pv_pretty NEED_pv_pretty_GLOBAL sv_2pv_flags() NEED_sv_2pv_flags NEED_sv_2pv_flags_GLOBAL sv_2pvbyte() NEED_sv_2pvbyte NEED_sv_2pvbyte_GLOBAL sv_catpvf_mg() NEED_sv_catpvf_mg NEED_sv_catpvf_mg_GLOBAL sv_catpvf_mg_nocontext() NEED_sv_catpvf_mg_nocontext NEED_sv_catpvf_mg_nocontext_GLOBAL sv_pvn_force_flags() NEED_sv_pvn_force_flags NEED_sv_pvn_force_flags_GLOBAL sv_setpvf_mg() NEED_sv_setpvf_mg NEED_sv_setpvf_mg_GLOBAL sv_setpvf_mg_nocontext() NEED_sv_setpvf_mg_nocontext NEED_sv_setpvf_mg_nocontext_GLOBAL vload_module() NEED_vload_module NEED_vload_module_GLOBAL vnewSVpvf() NEED_vnewSVpvf NEED_vnewSVpvf_GLOBAL warner() NEED_warner NEED_warner_GLOBAL To avoid namespace conflicts, you can change the namespace of the explicitly exported functions / variables using the C macro. Just C<#define> the macro before including C: #define DPPP_NAMESPACE MyOwnNamespace_ #include "ppport.h" The default namespace is C. =back The good thing is that most of the above can be checked by running F on your source code. See the next section for details. =head1 EXAMPLES To verify whether F is needed for your module, whether you should make any changes to your code, and whether any special defines should be used, F can be run as a Perl script to check your source code. Simply say: perl ppport.h The result will usually be a list of patches suggesting changes that should at least be acceptable, if not necessarily the most efficient solution, or a fix for all possible problems. If you know that your XS module uses features only available in newer Perl releases, if you're aware that it uses C++ comments, and if you want all suggestions as a single patch file, you could use something like this: perl ppport.h --compat-version=5.6.0 --cplusplus --patch=test.diff If you only want your code to be scanned without any suggestions for changes, use: perl ppport.h --nochanges You can specify a different C program or options, using the C<--diff> option: perl ppport.h --diff='diff -C 10' This would output context diffs with 10 lines of context. If you want to create patched copies of your files instead, use: perl ppport.h --copy=.new To display portability information for the C function, use: perl ppport.h --api-info=newSVpvn Since the argument to C<--api-info> can be a regular expression, you can use perl ppport.h --api-info=/_nomg$/ to display portability information for all C<_nomg> functions or perl ppport.h --api-info=/./ to display information for all known API elements. =head1 BUGS If this version of F is causing failure during the compilation of this module, please check if newer versions of either this module or C are available on CPAN before sending a bug report. If F was generated using the latest version of C and is causing failure of this module, please file a bug report using the CPAN Request Tracker at L. Please include the following information: =over 4 =item 1. The complete output from running "perl -V" =item 2. This file. =item 3. The name and version of the module you were trying to build. =item 4. A full log of the build that failed. =item 5. Any other information that you think could be relevant. =back For the latest version of this code, please get the C module from CPAN. =head1 COPYRIGHT Version 3.x, Copyright (c) 2004-2010, Marcus Holland-Moritz. Version 2.x, Copyright (C) 2001, Paul Marquess. Version 1.x, Copyright (C) 1999, Kenneth Albanowski. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO See L. =cut use strict; # Disable broken TRIE-optimization BEGIN { eval '${^RE_TRIE_MAXBUF} = -1' if $] >= 5.009004 && $] <= 5.009005 } my $VERSION = 3.20; my %opt = ( quiet => 0, diag => 1, hints => 1, changes => 1, cplusplus => 0, filter => 1, strip => 0, version => 0, ); my($ppport) = $0 =~ /([\w.]+)$/; my $LF = '(?:\r\n|[\r\n])'; # line feed my $HS = "[ \t]"; # horizontal whitespace # Never use C comments in this file! my $ccs = '/'.'*'; my $cce = '*'.'/'; my $rccs = quotemeta $ccs; my $rcce = quotemeta $cce; eval { require Getopt::Long; Getopt::Long::GetOptions(\%opt, qw( help quiet diag! filter! hints! changes! cplusplus strip version patch=s copy=s diff=s compat-version=s list-provided list-unsupported api-info=s )) or usage(); }; if ($@ and grep /^-/, @ARGV) { usage() if "@ARGV" =~ /^--?h(?:elp)?$/; die "Getopt::Long not found. Please don't use any options.\n"; } if ($opt{version}) { print "This is $0 $VERSION.\n"; exit 0; } usage() if $opt{help}; strip() if $opt{strip}; if (exists $opt{'compat-version'}) { my($r,$v,$s) = eval { parse_version($opt{'compat-version'}) }; if ($@) { die "Invalid version number format: '$opt{'compat-version'}'\n"; } die "Only Perl 5 is supported\n" if $r != 5; die "Invalid version number: $opt{'compat-version'}\n" if $v >= 1000 || $s >= 1000; $opt{'compat-version'} = sprintf "%d.%03d%03d", $r, $v, $s; } else { $opt{'compat-version'} = 5; } my %API = map { /^(\w+)\|([^|]*)\|([^|]*)\|(\w*)$/ ? ( $1 => { ($2 ? ( base => $2 ) : ()), ($3 ? ( todo => $3 ) : ()), (index($4, 'v') >= 0 ? ( varargs => 1 ) : ()), (index($4, 'p') >= 0 ? ( provided => 1 ) : ()), (index($4, 'n') >= 0 ? ( nothxarg => 1 ) : ()), } ) : die "invalid spec: $_" } qw( AvFILLp|5.004050||p AvFILL||| BhkDISABLE||5.014000| BhkENABLE||5.014000| BhkENTRY_set||5.014000| BhkENTRY||| BhkFLAGS||| CALL_BLOCK_HOOKS||| CLASS|||n CPERLscope|5.005000||p CX_CURPAD_SAVE||| CX_CURPAD_SV||| CopFILEAV|5.006000||p CopFILEGV_set|5.006000||p CopFILEGV|5.006000||p CopFILESV|5.006000||p CopFILE_set|5.006000||p CopFILE|5.006000||p CopSTASHPV_set|5.006000||p CopSTASHPV|5.006000||p CopSTASH_eq|5.006000||p CopSTASH_set|5.006000||p CopSTASH|5.006000||p CopyD|5.009002||p Copy||| CvPADLIST||| CvSTASH||| CvWEAKOUTSIDE||| DEFSV_set|5.010001||p DEFSV|5.004050||p END_EXTERN_C|5.005000||p ENTER||| ERRSV|5.004050||p EXTEND||| EXTERN_C|5.005000||p F0convert|||n FREETMPS||| GIMME_V||5.004000|n GIMME|||n GROK_NUMERIC_RADIX|5.007002||p G_ARRAY||| G_DISCARD||| G_EVAL||| G_METHOD|5.006001||p G_NOARGS||| G_SCALAR||| G_VOID||5.004000| GetVars||| GvSVn|5.009003||p GvSV||| Gv_AMupdate||5.011000| HEf_SVKEY||5.004000| HeHASH||5.004000| HeKEY||5.004000| HeKLEN||5.004000| HePV||5.004000| HeSVKEY_force||5.004000| HeSVKEY_set||5.004000| HeSVKEY||5.004000| HeUTF8||5.010001| HeVAL||5.004000| HvENAME||5.013007| HvNAMELEN_get|5.009003||p HvNAME_get|5.009003||p HvNAME||| INT2PTR|5.006000||p IN_LOCALE_COMPILETIME|5.007002||p IN_LOCALE_RUNTIME|5.007002||p IN_LOCALE|5.007002||p IN_PERL_COMPILETIME|5.008001||p IS_NUMBER_GREATER_THAN_UV_MAX|5.007002||p IS_NUMBER_INFINITY|5.007002||p IS_NUMBER_IN_UV|5.007002||p IS_NUMBER_NAN|5.007003||p IS_NUMBER_NEG|5.007002||p IS_NUMBER_NOT_INT|5.007002||p IVSIZE|5.006000||p IVTYPE|5.006000||p IVdf|5.006000||p LEAVE||| LINKLIST||5.013006| LVRET||| MARK||| MULTICALL||5.014000| MY_CXT_CLONE|5.009002||p MY_CXT_INIT|5.007003||p MY_CXT|5.007003||p MoveD|5.009002||p Move||| NOOP|5.005000||p NUM2PTR|5.006000||p NVTYPE|5.006000||p NVef|5.006001||p NVff|5.006001||p NVgf|5.006001||p Newxc|5.009003||p Newxz|5.009003||p Newx|5.009003||p Nullav||| Nullch||| Nullcv||| Nullhv||| Nullsv||| OP_CLASS||5.013007| OP_DESC||5.007003| OP_NAME||5.007003| ORIGMARK||| PAD_BASE_SV||| PAD_CLONE_VARS||| PAD_COMPNAME_FLAGS||| PAD_COMPNAME_GEN_set||| PAD_COMPNAME_GEN||| PAD_COMPNAME_OURSTASH||| PAD_COMPNAME_PV||| PAD_COMPNAME_TYPE||| PAD_DUP||| PAD_RESTORE_LOCAL||| PAD_SAVE_LOCAL||| PAD_SAVE_SETNULLPAD||| PAD_SETSV||| PAD_SET_CUR_NOSAVE||| PAD_SET_CUR||| PAD_SVl||| PAD_SV||| PERLIO_FUNCS_CAST|5.009003||p PERLIO_FUNCS_DECL|5.009003||p PERL_ABS|5.008001||p PERL_BCDVERSION|5.014000||p PERL_GCC_BRACE_GROUPS_FORBIDDEN|5.008001||p PERL_HASH|5.004000||p PERL_INT_MAX|5.004000||p PERL_INT_MIN|5.004000||p PERL_LONG_MAX|5.004000||p PERL_LONG_MIN|5.004000||p PERL_MAGIC_arylen|5.007002||p PERL_MAGIC_backref|5.007002||p PERL_MAGIC_bm|5.007002||p PERL_MAGIC_collxfrm|5.007002||p PERL_MAGIC_dbfile|5.007002||p PERL_MAGIC_dbline|5.007002||p PERL_MAGIC_defelem|5.007002||p PERL_MAGIC_envelem|5.007002||p PERL_MAGIC_env|5.007002||p PERL_MAGIC_ext|5.007002||p PERL_MAGIC_fm|5.007002||p PERL_MAGIC_glob|5.014000||p PERL_MAGIC_isaelem|5.007002||p PERL_MAGIC_isa|5.007002||p PERL_MAGIC_mutex|5.014000||p PERL_MAGIC_nkeys|5.007002||p PERL_MAGIC_overload_elem|5.007002||p PERL_MAGIC_overload_table|5.007002||p PERL_MAGIC_overload|5.007002||p PERL_MAGIC_pos|5.007002||p PERL_MAGIC_qr|5.007002||p PERL_MAGIC_regdata|5.007002||p PERL_MAGIC_regdatum|5.007002||p PERL_MAGIC_regex_global|5.007002||p PERL_MAGIC_shared_scalar|5.007003||p PERL_MAGIC_shared|5.007003||p PERL_MAGIC_sigelem|5.007002||p PERL_MAGIC_sig|5.007002||p PERL_MAGIC_substr|5.007002||p PERL_MAGIC_sv|5.007002||p PERL_MAGIC_taint|5.007002||p PERL_MAGIC_tiedelem|5.007002||p PERL_MAGIC_tiedscalar|5.007002||p PERL_MAGIC_tied|5.007002||p PERL_MAGIC_utf8|5.008001||p PERL_MAGIC_uvar_elem|5.007003||p PERL_MAGIC_uvar|5.007002||p PERL_MAGIC_vec|5.007002||p PERL_MAGIC_vstring|5.008001||p PERL_PV_ESCAPE_ALL|5.009004||p PERL_PV_ESCAPE_FIRSTCHAR|5.009004||p PERL_PV_ESCAPE_NOBACKSLASH|5.009004||p PERL_PV_ESCAPE_NOCLEAR|5.009004||p PERL_PV_ESCAPE_QUOTE|5.009004||p PERL_PV_ESCAPE_RE|5.009005||p PERL_PV_ESCAPE_UNI_DETECT|5.009004||p PERL_PV_ESCAPE_UNI|5.009004||p PERL_PV_PRETTY_DUMP|5.009004||p PERL_PV_PRETTY_ELLIPSES|5.010000||p PERL_PV_PRETTY_LTGT|5.009004||p PERL_PV_PRETTY_NOCLEAR|5.010000||p PERL_PV_PRETTY_QUOTE|5.009004||p PERL_PV_PRETTY_REGPROP|5.009004||p PERL_QUAD_MAX|5.004000||p PERL_QUAD_MIN|5.004000||p PERL_REVISION|5.006000||p PERL_SCAN_ALLOW_UNDERSCORES|5.007003||p PERL_SCAN_DISALLOW_PREFIX|5.007003||p PERL_SCAN_GREATER_THAN_UV_MAX|5.007003||p PERL_SCAN_SILENT_ILLDIGIT|5.008001||p PERL_SHORT_MAX|5.004000||p PERL_SHORT_MIN|5.004000||p PERL_SIGNALS_UNSAFE_FLAG|5.008001||p PERL_SUBVERSION|5.006000||p PERL_SYS_INIT3||5.006000| PERL_SYS_INIT||| PERL_SYS_TERM||5.014000| PERL_UCHAR_MAX|5.004000||p PERL_UCHAR_MIN|5.004000||p PERL_UINT_MAX|5.004000||p PERL_UINT_MIN|5.004000||p PERL_ULONG_MAX|5.004000||p PERL_ULONG_MIN|5.004000||p PERL_UNUSED_ARG|5.009003||p PERL_UNUSED_CONTEXT|5.009004||p PERL_UNUSED_DECL|5.007002||p PERL_UNUSED_VAR|5.007002||p PERL_UQUAD_MAX|5.004000||p PERL_UQUAD_MIN|5.004000||p PERL_USE_GCC_BRACE_GROUPS|5.009004||p PERL_USHORT_MAX|5.004000||p PERL_USHORT_MIN|5.004000||p PERL_VERSION|5.006000||p PL_DBsignal|5.005000||p PL_DBsingle|||pn PL_DBsub|||pn PL_DBtrace|||pn PL_Sv|5.005000||p PL_bufend|5.014000||p PL_bufptr|5.014000||p PL_compiling|5.004050||p PL_copline|5.014000||p PL_curcop|5.004050||p PL_curstash|5.004050||p PL_debstash|5.004050||p PL_defgv|5.004050||p PL_diehook|5.004050||p PL_dirty|5.004050||p PL_dowarn|||pn PL_errgv|5.004050||p PL_error_count|5.014000||p PL_expect|5.014000||p PL_hexdigit|5.005000||p PL_hints|5.005000||p PL_in_my_stash|5.014000||p PL_in_my|5.014000||p PL_keyword_plugin||5.011002| PL_last_in_gv|||n PL_laststatval|5.005000||p PL_lex_state|5.014000||p PL_lex_stuff|5.014000||p PL_linestr|5.014000||p PL_modglobal||5.005000|n PL_na|5.004050||pn PL_no_modify|5.006000||p PL_ofsgv|||n PL_opfreehook||5.011000|n PL_parser|5.009005|5.009005|p PL_peepp||5.007003|n PL_perl_destruct_level|5.004050||p PL_perldb|5.004050||p PL_ppaddr|5.006000||p PL_rpeepp||5.013005|n PL_rsfp_filters|5.014000||p PL_rsfp|5.014000||p PL_rs|||n PL_signals|5.008001||p PL_stack_base|5.004050||p PL_stack_sp|5.004050||p PL_statcache|5.005000||p PL_stdingv|5.004050||p PL_sv_arenaroot|5.004050||p PL_sv_no|5.004050||pn PL_sv_undef|5.004050||pn PL_sv_yes|5.004050||pn PL_tainted|5.004050||p PL_tainting|5.004050||p PL_tokenbuf|5.014000||p POP_MULTICALL||5.014000| POPi|||n POPl|||n POPn|||n POPpbytex||5.007001|n POPpx||5.005030|n POPp|||n POPs|||n PTR2IV|5.006000||p PTR2NV|5.006000||p PTR2UV|5.006000||p PTR2nat|5.009003||p PTR2ul|5.007001||p PTRV|5.006000||p PUSHMARK||| PUSH_MULTICALL||5.014000| PUSHi||| PUSHmortal|5.009002||p PUSHn||| PUSHp||| PUSHs||| PUSHu|5.004000||p PUTBACK||| PerlIO_clearerr||5.007003| PerlIO_close||5.007003| PerlIO_context_layers||5.009004| PerlIO_eof||5.007003| PerlIO_error||5.007003| PerlIO_fileno||5.007003| PerlIO_fill||5.007003| PerlIO_flush||5.007003| PerlIO_get_base||5.007003| PerlIO_get_bufsiz||5.007003| PerlIO_get_cnt||5.007003| PerlIO_get_ptr||5.007003| PerlIO_read||5.007003| PerlIO_seek||5.007003| PerlIO_set_cnt||5.007003| PerlIO_set_ptrcnt||5.007003| PerlIO_setlinebuf||5.007003| PerlIO_stderr||5.007003| PerlIO_stdin||5.007003| PerlIO_stdout||5.007003| PerlIO_tell||5.007003| PerlIO_unread||5.007003| PerlIO_write||5.007003| Perl_signbit||5.009005|n PoisonFree|5.009004||p PoisonNew|5.009004||p PoisonWith|5.009004||p Poison|5.008000||p RETVAL|||n Renewc||| Renew||| SAVECLEARSV||| SAVECOMPPAD||| SAVEPADSV||| SAVETMPS||| SAVE_DEFSV|5.004050||p SPAGAIN||| SP||| START_EXTERN_C|5.005000||p START_MY_CXT|5.007003||p STMT_END|||p STMT_START|||p STR_WITH_LEN|5.009003||p ST||| SV_CONST_RETURN|5.009003||p SV_COW_DROP_PV|5.008001||p SV_COW_SHARED_HASH_KEYS|5.009005||p SV_GMAGIC|5.007002||p SV_HAS_TRAILING_NUL|5.009004||p SV_IMMEDIATE_UNREF|5.007001||p SV_MUTABLE_RETURN|5.009003||p SV_NOSTEAL|5.009002||p SV_SMAGIC|5.009003||p SV_UTF8_NO_ENCODING|5.008001||p SVfARG|5.009005||p SVf_UTF8|5.006000||p SVf|5.006000||p SVt_IV||| SVt_NV||| SVt_PVAV||| SVt_PVCV||| SVt_PVHV||| SVt_PVMG||| SVt_PV||| Safefree||| Slab_Alloc||| Slab_Free||| Slab_to_rw||| StructCopy||| SvCUR_set||| SvCUR||| SvEND||| SvGAMAGIC||5.006001| SvGETMAGIC|5.004050||p SvGROW||| SvIOK_UV||5.006000| SvIOK_notUV||5.006000| SvIOK_off||| SvIOK_only_UV||5.006000| SvIOK_only||| SvIOK_on||| SvIOKp||| SvIOK||| SvIVX||| SvIV_nomg|5.009001||p SvIV_set||| SvIVx||| SvIV||| SvIsCOW_shared_hash||5.008003| SvIsCOW||5.008003| SvLEN_set||| SvLEN||| SvLOCK||5.007003| SvMAGIC_set|5.009003||p SvNIOK_off||| SvNIOKp||| SvNIOK||| SvNOK_off||| SvNOK_only||| SvNOK_on||| SvNOKp||| SvNOK||| SvNVX||| SvNV_nomg||5.013002| SvNV_set||| SvNVx||| SvNV||| SvOK||| SvOOK_offset||5.011000| SvOOK||| SvPOK_off||| SvPOK_only_UTF8||5.006000| SvPOK_only||| SvPOK_on||| SvPOKp||| SvPOK||| SvPVX_const|5.009003||p SvPVX_mutable|5.009003||p SvPVX||| SvPV_const|5.009003||p SvPV_flags_const_nolen|5.009003||p SvPV_flags_const|5.009003||p SvPV_flags_mutable|5.009003||p SvPV_flags|5.007002||p SvPV_force_flags_mutable|5.009003||p SvPV_force_flags_nolen|5.009003||p SvPV_force_flags|5.007002||p SvPV_force_mutable|5.009003||p SvPV_force_nolen|5.009003||p SvPV_force_nomg_nolen|5.009003||p SvPV_force_nomg|5.007002||p SvPV_force|||p SvPV_mutable|5.009003||p SvPV_nolen_const|5.009003||p SvPV_nolen|5.006000||p SvPV_nomg_const_nolen|5.009003||p SvPV_nomg_const|5.009003||p SvPV_nomg_nolen||5.013007| SvPV_nomg|5.007002||p SvPV_renew|5.009003||p SvPV_set||| SvPVbyte_force||5.009002| SvPVbyte_nolen||5.006000| SvPVbytex_force||5.006000| SvPVbytex||5.006000| SvPVbyte|5.006000||p SvPVutf8_force||5.006000| SvPVutf8_nolen||5.006000| SvPVutf8x_force||5.006000| SvPVutf8x||5.006000| SvPVutf8||5.006000| SvPVx||| SvPV||| SvREFCNT_dec||| SvREFCNT_inc_NN|5.009004||p SvREFCNT_inc_simple_NN|5.009004||p SvREFCNT_inc_simple_void_NN|5.009004||p SvREFCNT_inc_simple_void|5.009004||p SvREFCNT_inc_simple|5.009004||p SvREFCNT_inc_void_NN|5.009004||p SvREFCNT_inc_void|5.009004||p SvREFCNT_inc|||p SvREFCNT||| SvROK_off||| SvROK_on||| SvROK||| SvRV_set|5.009003||p SvRV||| SvRXOK||5.009005| SvRX||5.009005| SvSETMAGIC||| SvSHARED_HASH|5.009003||p SvSHARE||5.007003| SvSTASH_set|5.009003||p SvSTASH||| SvSetMagicSV_nosteal||5.004000| SvSetMagicSV||5.004000| SvSetSV_nosteal||5.004000| SvSetSV||| SvTAINTED_off||5.004000| SvTAINTED_on||5.004000| SvTAINTED||5.004000| SvTAINT||| SvTRUE_nomg||5.013006| SvTRUE||| SvTYPE||| SvUNLOCK||5.007003| SvUOK|5.007001|5.006000|p SvUPGRADE||| SvUTF8_off||5.006000| SvUTF8_on||5.006000| SvUTF8||5.006000| SvUVXx|5.004000||p SvUVX|5.004000||p SvUV_nomg|5.009001||p SvUV_set|5.009003||p SvUVx|5.004000||p SvUV|5.004000||p SvVOK||5.008001| SvVSTRING_mg|5.009004||p THIS|||n UNDERBAR|5.009002||p UTF8_MAXBYTES|5.009002||p UVSIZE|5.006000||p UVTYPE|5.006000||p UVXf|5.007001||p UVof|5.006000||p UVuf|5.006000||p UVxf|5.006000||p WARN_ALL|5.006000||p WARN_AMBIGUOUS|5.006000||p WARN_ASSERTIONS|5.014000||p WARN_BAREWORD|5.006000||p WARN_CLOSED|5.006000||p WARN_CLOSURE|5.006000||p WARN_DEBUGGING|5.006000||p WARN_DEPRECATED|5.006000||p WARN_DIGIT|5.006000||p WARN_EXEC|5.006000||p WARN_EXITING|5.006000||p WARN_GLOB|5.006000||p WARN_INPLACE|5.006000||p WARN_INTERNAL|5.006000||p WARN_IO|5.006000||p WARN_LAYER|5.008000||p WARN_MALLOC|5.006000||p WARN_MISC|5.006000||p WARN_NEWLINE|5.006000||p WARN_NUMERIC|5.006000||p WARN_ONCE|5.006000||p WARN_OVERFLOW|5.006000||p WARN_PACK|5.006000||p WARN_PARENTHESIS|5.006000||p WARN_PIPE|5.006000||p WARN_PORTABLE|5.006000||p WARN_PRECEDENCE|5.006000||p WARN_PRINTF|5.006000||p WARN_PROTOTYPE|5.006000||p WARN_QW|5.006000||p WARN_RECURSION|5.006000||p WARN_REDEFINE|5.006000||p WARN_REGEXP|5.006000||p WARN_RESERVED|5.006000||p WARN_SEMICOLON|5.006000||p WARN_SEVERE|5.006000||p WARN_SIGNAL|5.006000||p WARN_SUBSTR|5.006000||p WARN_SYNTAX|5.006000||p WARN_TAINT|5.006000||p WARN_THREADS|5.008000||p WARN_UNINITIALIZED|5.006000||p WARN_UNOPENED|5.006000||p WARN_UNPACK|5.006000||p WARN_UNTIE|5.006000||p WARN_UTF8|5.006000||p WARN_VOID|5.006000||p XCPT_CATCH|5.009002||p XCPT_RETHROW|5.009002||p XCPT_TRY_END|5.009002||p XCPT_TRY_START|5.009002||p XPUSHi||| XPUSHmortal|5.009002||p XPUSHn||| XPUSHp||| XPUSHs||| XPUSHu|5.004000||p XSPROTO|5.010000||p XSRETURN_EMPTY||| XSRETURN_IV||| XSRETURN_NO||| XSRETURN_NV||| XSRETURN_PV||| XSRETURN_UNDEF||| XSRETURN_UV|5.008001||p XSRETURN_YES||| XSRETURN|||p XST_mIV||| XST_mNO||| XST_mNV||| XST_mPV||| XST_mUNDEF||| XST_mUV|5.008001||p XST_mYES||| XS_APIVERSION_BOOTCHECK||5.013004| XS_VERSION_BOOTCHECK||| XS_VERSION||| XSprePUSH|5.006000||p XS||| XopDISABLE||5.014000| XopENABLE||5.014000| XopENTRY_set||5.014000| XopENTRY||5.014000| XopFLAGS||5.013007| ZeroD|5.009002||p Zero||| _aMY_CXT|5.007003||p _append_range_to_invlist||| _new_invlist||| _pMY_CXT|5.007003||p _swash_inversion_hash||| _swash_to_invlist||| aMY_CXT_|5.007003||p aMY_CXT|5.007003||p aTHXR_|5.014000||p aTHXR|5.014000||p aTHX_|5.006000||p aTHX|5.006000||p add_alternate||| add_cp_to_invlist||| add_data|||n add_range_to_invlist||| add_utf16_textfilter||| addmad||| allocmy||| amagic_call||| amagic_cmp_locale||| amagic_cmp||| amagic_deref_call||5.013007| amagic_i_ncmp||| amagic_ncmp||| anonymise_cv_maybe||| any_dup||| ao||| append_madprops||| apply_attrs_my||| apply_attrs_string||5.006001| apply_attrs||| apply||| assert_uft8_cache_coherent||| atfork_lock||5.007003|n atfork_unlock||5.007003|n av_arylen_p||5.009003| av_clear||| av_create_and_push||5.009005| av_create_and_unshift_one||5.009005| av_delete||5.006000| av_exists||5.006000| av_extend||| av_fetch||| av_fill||| av_iter_p||5.011000| av_len||| av_make||| av_pop||| av_push||| av_reify||| av_shift||| av_store||| av_undef||| av_unshift||| ax|||n bad_type||| bind_match||| block_end||| block_gimme||5.004000| block_start||| blockhook_register||5.013003| boolSV|5.004000||p boot_core_PerlIO||| boot_core_UNIVERSAL||| boot_core_mro||| bytes_cmp_utf8||5.013007| bytes_from_utf8||5.007001| bytes_to_uni|||n bytes_to_utf8||5.006001| call_argv|5.006000||p call_atexit||5.006000| call_list||5.004000| call_method|5.006000||p call_pv|5.006000||p call_sv|5.006000||p caller_cx||5.013005| calloc||5.007002|n cando||| cast_i32||5.006000| cast_iv||5.006000| cast_ulong||5.006000| cast_uv||5.006000| check_type_and_open||| check_uni||| check_utf8_print||| checkcomma||| checkposixcc||| ckWARN|5.006000||p ck_entersub_args_list||5.013006| ck_entersub_args_proto_or_list||5.013006| ck_entersub_args_proto||5.013006| ck_warner_d||5.011001|v ck_warner||5.011001|v ckwarn_common||| ckwarn_d||5.009003| ckwarn||5.009003| cl_and|||n cl_anything|||n cl_init|||n cl_is_anything|||n cl_or|||n clear_placeholders||| clone_params_del|||n clone_params_new|||n closest_cop||| convert||| cop_free||| cop_hints_2hv||5.013007| cop_hints_fetch_pvn||5.013007| cop_hints_fetch_pvs||5.013007| cop_hints_fetch_pv||5.013007| cop_hints_fetch_sv||5.013007| cophh_2hv||5.013007| cophh_copy||5.013007| cophh_delete_pvn||5.013007| cophh_delete_pvs||5.013007| cophh_delete_pv||5.013007| cophh_delete_sv||5.013007| cophh_fetch_pvn||5.013007| cophh_fetch_pvs||5.013007| cophh_fetch_pv||5.013007| cophh_fetch_sv||5.013007| cophh_free||5.013007| cophh_new_empty||5.014000| cophh_store_pvn||5.013007| cophh_store_pvs||5.013007| cophh_store_pv||5.013007| cophh_store_sv||5.013007| cr_textfilter||| create_eval_scope||| croak_no_modify||5.013003| croak_nocontext|||vn croak_sv||5.013001| croak_xs_usage||5.010001| croak|||v csighandler||5.009003|n curmad||| curse||| custom_op_desc||5.007003| custom_op_name||5.007003| custom_op_register||5.013007| custom_op_xop||5.013007| cv_ckproto_len||| cv_clone||| cv_const_sv||5.004000| cv_dump||| cv_get_call_checker||5.013006| cv_set_call_checker||5.013006| cv_undef||| cvgv_set||| cvstash_set||| cx_dump||5.005000| cx_dup||| cxinc||| dAXMARK|5.009003||p dAX|5.007002||p dITEMS|5.007002||p dMARK||| dMULTICALL||5.009003| dMY_CXT_SV|5.007003||p dMY_CXT|5.007003||p dNOOP|5.006000||p dORIGMARK||| dSP||| dTHR|5.004050||p dTHXR|5.014000||p dTHXa|5.006000||p dTHXoa|5.006000||p dTHX|5.006000||p dUNDERBAR|5.009002||p dVAR|5.009003||p dXCPT|5.009002||p dXSARGS||| dXSI32||| dXSTARG|5.006000||p deb_curcv||| deb_nocontext|||vn deb_stack_all||| deb_stack_n||| debop||5.005000| debprofdump||5.005000| debprof||| debstackptrs||5.007003| debstack||5.007003| debug_start_match||| deb||5.007003|v del_sv||| delete_eval_scope||| delimcpy||5.004000|n deprecate_commaless_var_list||| despatch_signals||5.007001| destroy_matcher||| die_nocontext|||vn die_sv||5.013001| die_unwind||| die|||v dirp_dup||| div128||| djSP||| do_aexec5||| do_aexec||| do_aspawn||| do_binmode||5.004050| do_chomp||| do_close||| do_delete_local||| do_dump_pad||| do_eof||| do_exec3||| do_execfree||| do_exec||| do_gv_dump||5.006000| do_gvgv_dump||5.006000| do_hv_dump||5.006000| do_ipcctl||| do_ipcget||| do_join||| do_magic_dump||5.006000| do_msgrcv||| do_msgsnd||| do_oddball||| do_op_dump||5.006000| do_op_xmldump||| do_open9||5.006000| do_openn||5.007001| do_open||5.004000| do_pmop_dump||5.006000| do_pmop_xmldump||| do_print||| do_readline||| do_seek||| do_semop||| do_shmio||| do_smartmatch||| do_spawn_nowait||| do_spawn||| do_sprintf||| do_sv_dump||5.006000| do_sysseek||| do_tell||| do_trans_complex_utf8||| do_trans_complex||| do_trans_count_utf8||| do_trans_count||| do_trans_simple_utf8||| do_trans_simple||| do_trans||| do_vecget||| do_vecset||| do_vop||| docatch||| doeval||| dofile||| dofindlabel||| doform||| doing_taint||5.008001|n dooneliner||| doopen_pm||| doparseform||| dopoptoeval||| dopoptogiven||| dopoptolabel||| dopoptoloop||| dopoptosub_at||| dopoptowhen||| doref||5.009003| dounwind||| dowantarray||| dump_all_perl||| dump_all||5.006000| dump_eval||5.006000| dump_exec_pos||| dump_fds||| dump_form||5.006000| dump_indent||5.006000|v dump_mstats||| dump_packsubs_perl||| dump_packsubs||5.006000| dump_sub_perl||| dump_sub||5.006000| dump_sv_child||| dump_trie_interim_list||| dump_trie_interim_table||| dump_trie||| dump_vindent||5.006000| dumpuntil||| dup_attrlist||| emulate_cop_io||| eval_pv|5.006000||p eval_sv|5.006000||p exec_failed||| expect_number||| fbm_compile||5.005000| fbm_instr||5.005000| feature_is_enabled||| fetch_cop_label||5.011000| filter_add||| filter_del||| filter_gets||| filter_read||| find_and_forget_pmops||| find_array_subscript||| find_beginning||| find_byclass||| find_hash_subscript||| find_in_my_stash||| find_runcv||5.008001| find_rundefsvoffset||5.009002| find_rundefsv||5.013002| find_script||| find_uninit_var||| first_symbol|||n foldEQ_latin1||5.013008|n foldEQ_locale||5.013002|n foldEQ_utf8_flags||5.013010| foldEQ_utf8||5.013002| foldEQ||5.013002|n fold_constants||| forbid_setid||| force_ident||| force_list||| force_next||| force_strict_version||| force_version||| force_word||| forget_pmop||| form_nocontext|||vn form||5.004000|v fp_dup||| fprintf_nocontext|||vn free_global_struct||| free_tied_hv_pool||| free_tmps||| gen_constant_list||| get_aux_mg||| get_av|5.006000||p get_context||5.006000|n get_cvn_flags|5.009005||p get_cvs|5.011000||p get_cv|5.006000||p get_db_sub||| get_debug_opts||| get_hash_seed||| get_hv|5.006000||p get_mstats||| get_no_modify||| get_num||| get_op_descs||5.005000| get_op_names||5.005000| get_opargs||| get_ppaddr||5.006000| get_re_arg||| get_sv|5.006000||p get_vtbl||5.005030| getcwd_sv||5.007002| getenv_len||| glob_2number||| glob_assign_glob||| glob_assign_ref||| gp_dup||| gp_free||| gp_ref||| grok_bin|5.007003||p grok_bslash_c||| grok_bslash_o||| grok_hex|5.007003||p grok_number|5.007002||p grok_numeric_radix|5.007002||p grok_oct|5.007003||p group_end||| gv_AVadd||| gv_HVadd||| gv_IOadd||| gv_SVadd||| gv_add_by_type||5.011000| gv_autoload4||5.004000| gv_check||| gv_const_sv||5.009003| gv_dump||5.006000| gv_efullname3||5.004000| gv_efullname4||5.006001| gv_efullname||| gv_ename||| gv_fetchfile_flags||5.009005| gv_fetchfile||| gv_fetchmeth_autoload||5.007003| gv_fetchmethod_autoload||5.004000| gv_fetchmethod_flags||5.011000| gv_fetchmethod||| gv_fetchmeth||| gv_fetchpvn_flags|5.009002||p gv_fetchpvs|5.009004||p gv_fetchpv||| gv_fetchsv|5.009002||p gv_fullname3||5.004000| gv_fullname4||5.006001| gv_fullname||| gv_get_super_pkg||| gv_handler||5.007001| gv_init_sv||| gv_init||| gv_magicalize_isa||| gv_magicalize_overload||| gv_name_set||5.009004| gv_stashpvn|5.004000||p gv_stashpvs|5.009003||p gv_stashpv||| gv_stashsv||| gv_try_downgrade||| he_dup||| hek_dup||| hfreeentries||| hsplit||| hv_assert||| hv_auxinit|||n hv_backreferences_p||| hv_clear_placeholders||5.009001| hv_clear||| hv_common_key_len||5.010000| hv_common||5.010000| hv_copy_hints_hv||5.009004| hv_delayfree_ent||5.004000| hv_delete_common||| hv_delete_ent||5.004000| hv_delete||| hv_eiter_p||5.009003| hv_eiter_set||5.009003| hv_ename_add||| hv_ename_delete||| hv_exists_ent||5.004000| hv_exists||| hv_fetch_ent||5.004000| hv_fetchs|5.009003||p hv_fetch||| hv_fill||5.013002| hv_free_ent||5.004000| hv_iterinit||| hv_iterkeysv||5.004000| hv_iterkey||| hv_iternext_flags||5.008000| hv_iternextsv||| hv_iternext||| hv_iterval||| hv_kill_backrefs||| hv_ksplit||5.004000| hv_magic_check|||n hv_magic||| hv_name_set||5.009003| hv_notallowed||| hv_placeholders_get||5.009003| hv_placeholders_p||5.009003| hv_placeholders_set||5.009003| hv_riter_p||5.009003| hv_riter_set||5.009003| hv_scalar||5.009001| hv_store_ent||5.004000| hv_store_flags||5.008000| hv_stores|5.009004||p hv_store||| hv_undef_flags||| hv_undef||| ibcmp_locale||5.004000| ibcmp_utf8||5.007003| ibcmp||| incline||| incpush_if_exists||| incpush_use_sep||| incpush||| ingroup||| init_argv_symbols||| init_dbargs||| init_debugger||| init_global_struct||| init_i18nl10n||5.006000| init_i18nl14n||5.006000| init_ids||| init_interp||| init_main_stash||| init_perllib||| init_postdump_symbols||| init_predump_symbols||| init_stacks||5.005000| init_tm||5.007002| instr|||n intro_my||| intuit_method||| intuit_more||| invert||| invlist_array||| invlist_destroy||| invlist_extend||| invlist_intersection||| invlist_len||| invlist_max||| invlist_set_array||| invlist_set_len||| invlist_set_max||| invlist_trim||| invlist_union||| invoke_exception_hook||| io_close||| isALNUMC|5.006000||p isALPHA||| isASCII|5.006000||p isBLANK|5.006001||p isCNTRL|5.006000||p isDIGIT||| isGRAPH|5.006000||p isGV_with_GP|5.009004||p isLOWER||| isOCTAL||5.013005| isPRINT|5.004000||p isPSXSPC|5.006001||p isPUNCT|5.006000||p isSPACE||| isUPPER||| isWORDCHAR||5.013006| isXDIGIT|5.006000||p is_an_int||| is_ascii_string||5.011000|n is_gv_magical_sv||| is_handle_constructor|||n is_inplace_av||| is_list_assignment||| is_lvalue_sub||5.007001| is_uni_alnum_lc||5.006000| is_uni_alnum||5.006000| is_uni_alpha_lc||5.006000| is_uni_alpha||5.006000| is_uni_ascii_lc||5.006000| is_uni_ascii||5.006000| is_uni_cntrl_lc||5.006000| is_uni_cntrl||5.006000| is_uni_digit_lc||5.006000| is_uni_digit||5.006000| is_uni_graph_lc||5.006000| is_uni_graph||5.006000| is_uni_idfirst_lc||5.006000| is_uni_idfirst||5.006000| is_uni_lower_lc||5.006000| is_uni_lower||5.006000| is_uni_print_lc||5.006000| is_uni_print||5.006000| is_uni_punct_lc||5.006000| is_uni_punct||5.006000| is_uni_space_lc||5.006000| is_uni_space||5.006000| is_uni_upper_lc||5.006000| is_uni_upper||5.006000| is_uni_xdigit_lc||5.006000| is_uni_xdigit||5.006000| is_utf8_X_LVT||| is_utf8_X_LV_LVT_V||| is_utf8_X_LV||| is_utf8_X_L||| is_utf8_X_T||| is_utf8_X_V||| is_utf8_X_begin||| is_utf8_X_extend||| is_utf8_X_non_hangul||| is_utf8_X_prepend||| is_utf8_alnum||5.006000| is_utf8_alpha||5.006000| is_utf8_ascii||5.006000| is_utf8_char_slow|||n is_utf8_char||5.006000|n is_utf8_cntrl||5.006000| is_utf8_common||| is_utf8_digit||5.006000| is_utf8_graph||5.006000| is_utf8_idcont||5.008000| is_utf8_idfirst||5.006000| is_utf8_lower||5.006000| is_utf8_mark||5.006000| is_utf8_perl_space||5.011001| is_utf8_perl_word||5.011001| is_utf8_posix_digit||5.011001| is_utf8_print||5.006000| is_utf8_punct||5.006000| is_utf8_space||5.006000| is_utf8_string_loclen||5.009003|n is_utf8_string_loc||5.008001|n is_utf8_string||5.006001|n is_utf8_upper||5.006000| is_utf8_xdigit||5.006000| is_utf8_xidcont||5.013010| is_utf8_xidfirst||5.013010| isa_lookup||| items|||n ix|||n jmaybe||| join_exact||| keyword_plugin_standard||| keyword||| leave_scope||| lex_bufutf8||5.011002| lex_discard_to||5.011002| lex_grow_linestr||5.011002| lex_next_chunk||5.011002| lex_peek_unichar||5.011002| lex_read_space||5.011002| lex_read_to||5.011002| lex_read_unichar||5.011002| lex_start||5.009005| lex_stuff_pvn||5.011002| lex_stuff_pvs||5.013005| lex_stuff_pv||5.013006| lex_stuff_sv||5.011002| lex_unstuff||5.011002| listkids||| list||| load_module_nocontext|||vn load_module|5.006000||pv localize||| looks_like_bool||| looks_like_number||| lop||| mPUSHi|5.009002||p mPUSHn|5.009002||p mPUSHp|5.009002||p mPUSHs|5.010001||p mPUSHu|5.009002||p mXPUSHi|5.009002||p mXPUSHn|5.009002||p mXPUSHp|5.009002||p mXPUSHs|5.010001||p mXPUSHu|5.009002||p mad_free||| madlex||| madparse||| magic_clear_all_env||| magic_clearenv||| magic_clearhints||| magic_clearhint||| magic_clearisa||| magic_clearpack||| magic_clearsig||| magic_dump||5.006000| magic_existspack||| magic_freearylen_p||| magic_freeovrld||| magic_getarylen||| magic_getdefelem||| magic_getnkeys||| magic_getpack||| magic_getpos||| magic_getsig||| magic_getsubstr||| magic_gettaint||| magic_getuvar||| magic_getvec||| magic_get||| magic_killbackrefs||| magic_len||| magic_methcall1||| magic_methcall|||v magic_methpack||| magic_nextpack||| magic_regdata_cnt||| magic_regdatum_get||| magic_regdatum_set||| magic_scalarpack||| magic_set_all_env||| magic_setamagic||| magic_setarylen||| magic_setcollxfrm||| magic_setdbline||| magic_setdefelem||| magic_setenv||| magic_sethint||| magic_setisa||| magic_setmglob||| magic_setnkeys||| magic_setpack||| magic_setpos||| magic_setregexp||| magic_setsig||| magic_setsubstr||| magic_settaint||| magic_setutf8||| magic_setuvar||| magic_setvec||| magic_set||| magic_sizepack||| magic_wipepack||| make_matcher||| make_trie_failtable||| make_trie||| malloc_good_size|||n malloced_size|||n malloc||5.007002|n markstack_grow||| matcher_matches_sv||| measure_struct||| memEQs|5.009005||p memEQ|5.004000||p memNEs|5.009005||p memNE|5.004000||p mem_collxfrm||| mem_log_common|||n mess_alloc||| mess_nocontext|||vn mess_sv||5.013001| mess||5.006000|v method_common||| mfree||5.007002|n mg_clear||| mg_copy||| mg_dup||| mg_findext||5.013008| mg_find||| mg_free_type||5.013006| mg_free||| mg_get||| mg_length||5.005000| mg_localize||| mg_magical||| mg_set||| mg_size||5.005000| mini_mktime||5.007002| missingterm||| mode_from_discipline||| modkids||| mod||| more_bodies||| more_sv||| moreswitches||| mro_clean_isarev||| mro_gather_and_rename||| mro_get_from_name||5.010001| mro_get_linear_isa_dfs||| mro_get_linear_isa||5.009005| mro_get_private_data||5.010001| mro_isa_changed_in||| mro_meta_dup||| mro_meta_init||| mro_method_changed_in||5.009005| mro_package_moved||| mro_register||5.010001| mro_set_mro||5.010001| mro_set_private_data||5.010001| mul128||| mulexp10|||n munge_qwlist_to_paren_list||| my_atof2||5.007002| my_atof||5.006000| my_attrs||| my_bcopy|||n my_betoh16|||n my_betoh32|||n my_betoh64|||n my_betohi|||n my_betohl|||n my_betohs|||n my_bzero|||n my_chsize||| my_clearenv||| my_cxt_index||| my_cxt_init||| my_dirfd||5.009005| my_exit_jump||| my_exit||| my_failure_exit||5.004000| my_fflush_all||5.006000| my_fork||5.007003|n my_htobe16|||n my_htobe32|||n my_htobe64|||n my_htobei|||n my_htobel|||n my_htobes|||n my_htole16|||n my_htole32|||n my_htole64|||n my_htolei|||n my_htolel|||n my_htoles|||n my_htonl||| my_kid||| my_letoh16|||n my_letoh32|||n my_letoh64|||n my_letohi|||n my_letohl|||n my_letohs|||n my_lstat_flags||| my_lstat||5.014000| my_memcmp||5.004000|n my_memset|||n my_ntohl||| my_pclose||5.004000| my_popen_list||5.007001| my_popen||5.004000| my_setenv||| my_snprintf|5.009004||pvn my_socketpair||5.007003|n my_sprintf|5.009003||pvn my_stat_flags||| my_stat||5.014000| my_strftime||5.007002| my_strlcat|5.009004||pn my_strlcpy|5.009004||pn my_swabn|||n my_swap||| my_unexec||| my_vsnprintf||5.009004|n need_utf8|||n newANONATTRSUB||5.006000| newANONHASH||| newANONLIST||| newANONSUB||| newASSIGNOP||| newATTRSUB||5.006000| newAVREF||| newAV||| newBINOP||| newCONDOP||| newCONSTSUB|5.004050||p newCVREF||| newDEFSVOP||| newFORM||| newFOROP||5.013007| newGIVENOP||5.009003| newGIVWHENOP||| newGP||| newGVOP||| newGVREF||| newGVgen||| newHVREF||| newHVhv||5.005000| newHV||| newIO||| newLISTOP||| newLOGOP||| newLOOPEX||| newLOOPOP||| newMADPROP||| newMADsv||| newMYSUB||| newNULLLIST||| newOP||| newPADOP||| newPMOP||| newPROG||| newPVOP||| newRANGE||| newRV_inc|5.004000||p newRV_noinc|5.004000||p newRV||| newSLICEOP||| newSTATEOP||| newSUB||| newSVOP||| newSVREF||| newSV_type|5.009005||p newSVhek||5.009003| newSViv||| newSVnv||| newSVpv_share||5.013006| newSVpvf_nocontext|||vn newSVpvf||5.004000|v newSVpvn_flags|5.010001||p newSVpvn_share|5.007001||p newSVpvn_utf8|5.010001||p newSVpvn|5.004050||p newSVpvs_flags|5.010001||p newSVpvs_share|5.009003||p newSVpvs|5.009003||p newSVpv||| newSVrv||| newSVsv||| newSVuv|5.006000||p newSV||| newTOKEN||| newUNOP||| newWHENOP||5.009003| newWHILEOP||5.013007| newXS_flags||5.009004| newXSproto||5.006000| newXS||5.006000| new_collate||5.006000| new_constant||| new_ctype||5.006000| new_he||| new_logop||| new_numeric||5.006000| new_stackinfo||5.005000| new_version||5.009000| new_warnings_bitfield||| next_symbol||| nextargv||| nextchar||| ninstr|||n no_bareword_allowed||| no_fh_allowed||| no_op||| not_a_number||| nothreadhook||5.008000| nuke_stacks||| num_overflow|||n oopsAV||| oopsHV||| op_append_elem||5.013006| op_append_list||5.013006| op_clear||| op_const_sv||| op_contextualize||5.013006| op_dump||5.006000| op_free||| op_getmad_weak||| op_getmad||| op_linklist||5.013006| op_lvalue||5.013007| op_null||5.007002| op_prepend_elem||5.013006| op_refcnt_dec||| op_refcnt_inc||| op_refcnt_lock||5.009002| op_refcnt_unlock||5.009002| op_scope||5.013007| op_xmldump||| open_script||| opt_scalarhv||| pMY_CXT_|5.007003||p pMY_CXT|5.007003||p pTHX_|5.006000||p pTHX|5.006000||p packWARN|5.007003||p pack_cat||5.007003| pack_rec||| package_version||| package||| packlist||5.008001| pad_add_anon||| pad_add_name_sv||| pad_add_name||| pad_alloc||| pad_block_start||| pad_check_dup||| pad_compname_type||| pad_findlex||| pad_findmy||5.011002| pad_fixup_inner_anons||| pad_free||| pad_leavemy||| pad_new||| pad_peg|||n pad_push||| pad_reset||| pad_setsv||| pad_sv||| pad_swipe||| pad_tidy||| padlist_dup||| parse_arithexpr||5.013008| parse_barestmt||5.013007| parse_block||5.013007| parse_body||| parse_fullexpr||5.013008| parse_fullstmt||5.013005| parse_label||5.013007| parse_listexpr||5.013008| parse_stmtseq||5.013006| parse_termexpr||5.013008| parse_unicode_opts||| parser_dup||| parser_free||| path_is_absolute|||n peep||| pending_Slabs_to_ro||| perl_alloc_using|||n perl_alloc|||n perl_clone_using|||n perl_clone|||n perl_construct|||n perl_destruct||5.007003|n perl_free|||n perl_parse||5.006000|n perl_run|||n pidgone||| pm_description||| pmop_dump||5.006000| pmop_xmldump||| pmruntime||| pmtrans||| pop_scope||| populate_isa|||v pregcomp||5.009005| pregexec||| pregfree2||5.011000| pregfree||| prepend_madprops||| prescan_version||5.011004| printbuf||| printf_nocontext|||vn process_special_blocks||| ptr_table_clear||5.009005| ptr_table_fetch||5.009005| ptr_table_find|||n ptr_table_free||5.009005| ptr_table_new||5.009005| ptr_table_split||5.009005| ptr_table_store||5.009005| push_scope||| put_byte||| pv_display|5.006000||p pv_escape|5.009004||p pv_pretty|5.009004||p pv_uni_display||5.007003| qerror||| qsortsvu||| re_compile||5.009005| re_croak2||| re_dup_guts||| re_intuit_start||5.009005| re_intuit_string||5.006000| readpipe_override||| realloc||5.007002|n reentrant_free||| reentrant_init||| reentrant_retry|||vn reentrant_size||| ref_array_or_hash||| refcounted_he_chain_2hv||| refcounted_he_fetch_pvn||| refcounted_he_fetch_pvs||| refcounted_he_fetch_pv||| refcounted_he_fetch_sv||| refcounted_he_free||| refcounted_he_inc||| refcounted_he_new_pvn||| refcounted_he_new_pvs||| refcounted_he_new_pv||| refcounted_he_new_sv||| refcounted_he_value||| refkids||| refto||| ref||5.014000| reg_check_named_buff_matched||| reg_named_buff_all||5.009005| reg_named_buff_exists||5.009005| reg_named_buff_fetch||5.009005| reg_named_buff_firstkey||5.009005| reg_named_buff_iter||| reg_named_buff_nextkey||5.009005| reg_named_buff_scalar||5.009005| reg_named_buff||| reg_namedseq||| reg_node||| reg_numbered_buff_fetch||| reg_numbered_buff_length||| reg_numbered_buff_store||| reg_qr_package||| reg_recode||| reg_scan_name||| reg_skipcomment||| reg_temp_copy||| reganode||| regatom||| regbranch||| regclass_swash||5.009004| regclass||| regcppop||| regcppush||| regcurly||| regdump_extflags||| regdump||5.005000| regdupe_internal||| regexec_flags||5.005000| regfree_internal||5.009005| reghop3|||n reghop4|||n reghopmaybe3|||n reginclass||| reginitcolors||5.006000| reginsert||| regmatch||| regnext||5.005000| regpiece||| regpposixcc||| regprop||| regrepeat||| regtail_study||| regtail||| regtry||| reguni||| regwhite|||n reg||| repeatcpy|||n report_evil_fh||| report_uninit||| report_wrongway_fh||| require_pv||5.006000| require_tie_mod||| restore_magic||| rninstr|||n rpeep||| rsignal_restore||| rsignal_save||| rsignal_state||5.004000| rsignal||5.004000| run_body||| run_user_filter||| runops_debug||5.005000| runops_standard||5.005000| rv2cv_op_cv||5.013006| rvpv_dup||| rxres_free||| rxres_restore||| rxres_save||| safesyscalloc||5.006000|n safesysfree||5.006000|n safesysmalloc||5.006000|n safesysrealloc||5.006000|n same_dirent||| save_I16||5.004000| save_I32||| save_I8||5.006000| save_adelete||5.011000| save_aelem_flags||5.011000| save_aelem||5.004050| save_alloc||5.006000| save_aptr||| save_ary||| save_bool||5.008001| save_clearsv||| save_delete||| save_destructor_x||5.006000| save_destructor||5.006000| save_freeop||| save_freepv||| save_freesv||| save_generic_pvref||5.006001| save_generic_svref||5.005030| save_gp||5.004000| save_hash||| save_hdelete||5.011000| save_hek_flags|||n save_helem_flags||5.011000| save_helem||5.004050| save_hints||5.010001| save_hptr||| save_int||| save_item||| save_iv||5.005000| save_lines||| save_list||| save_long||| save_magic||| save_mortalizesv||5.007001| save_nogv||| save_op||5.005000| save_padsv_and_mortalize||5.010001| save_pptr||| save_pushi32ptr||5.010001| save_pushptri32ptr||| save_pushptrptr||5.010001| save_pushptr||5.010001| save_re_context||5.006000| save_scalar_at||| save_scalar||| save_set_svflags||5.009000| save_shared_pvref||5.007003| save_sptr||| save_svref||| save_vptr||5.006000| savepvn||| savepvs||5.009003| savepv||| savesharedpvn||5.009005| savesharedpvs||5.013006| savesharedpv||5.007003| savesharedsvpv||5.013006| savestack_grow_cnt||5.008001| savestack_grow||| savesvpv||5.009002| sawparens||| scalar_mod_type|||n scalarboolean||| scalarkids||| scalarseq||| scalarvoid||| scalar||| scan_bin||5.006000| scan_commit||| scan_const||| scan_formline||| scan_heredoc||| scan_hex||| scan_ident||| scan_inputsymbol||| scan_num||5.007001| scan_oct||| scan_pat||| scan_str||| scan_subst||| scan_trans||| scan_version||5.009001| scan_vstring||5.009005| scan_word||| screaminstr||5.005000| search_const||| seed||5.008001| sequence_num||| sequence_tail||| sequence||| set_context||5.006000|n set_numeric_local||5.006000| set_numeric_radix||5.006000| set_numeric_standard||5.006000| set_regclass_bit_fold||| set_regclass_bit||| setdefout||| share_hek_flags||| share_hek||5.004000| si_dup||| sighandler|||n simplify_sort||| skipspace0||| skipspace1||| skipspace2||| skipspace||| softref2xv||| sortcv_stacked||| sortcv_xsub||| sortcv||| sortsv_flags||5.009003| sortsv||5.007003| space_join_names_mortal||| ss_dup||| stack_grow||| start_force||| start_glob||| start_subparse||5.004000| stashpv_hvname_match||5.014000| stdize_locale||| store_cop_label||| strEQ||| strGE||| strGT||| strLE||| strLT||| strNE||| str_to_version||5.006000| strip_return||| strnEQ||| strnNE||| study_chunk||| sub_crush_depth||| sublex_done||| sublex_push||| sublex_start||| sv_2bool_flags||5.013006| sv_2bool||| sv_2cv||| sv_2io||| sv_2iuv_common||| sv_2iuv_non_preserve||| sv_2iv_flags||5.009001| sv_2iv||| sv_2mortal||| sv_2num||| sv_2nv_flags||5.013001| sv_2pv_flags|5.007002||p sv_2pv_nolen|5.006000||p sv_2pvbyte_nolen|5.006000||p sv_2pvbyte|5.006000||p sv_2pvutf8_nolen||5.006000| sv_2pvutf8||5.006000| sv_2pv||| sv_2uv_flags||5.009001| sv_2uv|5.004000||p sv_add_arena||| sv_add_backref||| sv_backoff||| sv_bless||| sv_cat_decode||5.008001| sv_catpv_flags||5.013006| sv_catpv_mg|5.004050||p sv_catpv_nomg||5.013006| sv_catpvf_mg_nocontext|||pvn sv_catpvf_mg|5.006000|5.004000|pv sv_catpvf_nocontext|||vn sv_catpvf||5.004000|v sv_catpvn_flags||5.007002| sv_catpvn_mg|5.004050||p sv_catpvn_nomg|5.007002||p sv_catpvn||| sv_catpvs_flags||5.013006| sv_catpvs_mg||5.013006| sv_catpvs_nomg||5.013006| sv_catpvs|5.009003||p sv_catpv||| sv_catsv_flags||5.007002| sv_catsv_mg|5.004050||p sv_catsv_nomg|5.007002||p sv_catsv||| sv_catxmlpvn||| sv_catxmlpv||| sv_catxmlsv||| sv_chop||| sv_clean_all||| sv_clean_objs||| sv_clear||| sv_cmp_flags||5.013006| sv_cmp_locale_flags||5.013006| sv_cmp_locale||5.004000| sv_cmp||| sv_collxfrm_flags||5.013006| sv_collxfrm||| sv_compile_2op_is_broken||| sv_compile_2op||5.008001| sv_copypv||5.007003| sv_dec_nomg||5.013002| sv_dec||| sv_del_backref||| sv_derived_from||5.004000| sv_destroyable||5.010000| sv_does||5.009004| sv_dump||| sv_dup_common||| sv_dup_inc_multiple||| sv_dup_inc||| sv_dup||| sv_eq_flags||5.013006| sv_eq||| sv_exp_grow||| sv_force_normal_flags||5.007001| sv_force_normal||5.006000| sv_free2||| sv_free_arenas||| sv_free||| sv_gets||5.004000| sv_grow||| sv_i_ncmp||| sv_inc_nomg||5.013002| sv_inc||| sv_insert_flags||5.010001| sv_insert||| sv_isa||| sv_isobject||| sv_iv||5.005000| sv_kill_backrefs||| sv_len_utf8||5.006000| sv_len||| sv_magic_portable|5.014000|5.004000|p sv_magicext||5.007003| sv_magic||| sv_mortalcopy||| sv_ncmp||| sv_newmortal||| sv_newref||| sv_nolocking||5.007003| sv_nosharing||5.007003| sv_nounlocking||| sv_nv||5.005000| sv_peek||5.005000| sv_pos_b2u_midway||| sv_pos_b2u||5.006000| sv_pos_u2b_cached||| sv_pos_u2b_flags||5.011005| sv_pos_u2b_forwards|||n sv_pos_u2b_midway|||n sv_pos_u2b||5.006000| sv_pvbyten_force||5.006000| sv_pvbyten||5.006000| sv_pvbyte||5.006000| sv_pvn_force_flags|5.007002||p sv_pvn_force||| sv_pvn_nomg|5.007003|5.005000|p sv_pvn||5.005000| sv_pvutf8n_force||5.006000| sv_pvutf8n||5.006000| sv_pvutf8||5.006000| sv_pv||5.006000| sv_recode_to_utf8||5.007003| sv_reftype||| sv_release_COW||| sv_replace||| sv_report_used||| sv_reset||| sv_rvweaken||5.006000| sv_setiv_mg|5.004050||p sv_setiv||| sv_setnv_mg|5.006000||p sv_setnv||| sv_setpv_mg|5.004050||p sv_setpvf_mg_nocontext|||pvn sv_setpvf_mg|5.006000|5.004000|pv sv_setpvf_nocontext|||vn sv_setpvf||5.004000|v sv_setpviv_mg||5.008001| sv_setpviv||5.008001| sv_setpvn_mg|5.004050||p sv_setpvn||| sv_setpvs_mg||5.013006| sv_setpvs|5.009004||p sv_setpv||| sv_setref_iv||| sv_setref_nv||| sv_setref_pvn||| sv_setref_pvs||5.013006| sv_setref_pv||| sv_setref_uv||5.007001| sv_setsv_cow||| sv_setsv_flags||5.007002| sv_setsv_mg|5.004050||p sv_setsv_nomg|5.007002||p sv_setsv||| sv_setuv_mg|5.004050||p sv_setuv|5.004000||p sv_tainted||5.004000| sv_taint||5.004000| sv_true||5.005000| sv_unglob||| sv_uni_display||5.007003| sv_unmagicext||5.013008| sv_unmagic||| sv_unref_flags||5.007001| sv_unref||| sv_untaint||5.004000| sv_upgrade||| sv_usepvn_flags||5.009004| sv_usepvn_mg|5.004050||p sv_usepvn||| sv_utf8_decode||5.006000| sv_utf8_downgrade||5.006000| sv_utf8_encode||5.006000| sv_utf8_upgrade_flags_grow||5.011000| sv_utf8_upgrade_flags||5.007002| sv_utf8_upgrade_nomg||5.007002| sv_utf8_upgrade||5.007001| sv_uv|5.005000||p sv_vcatpvf_mg|5.006000|5.004000|p sv_vcatpvfn||5.004000| sv_vcatpvf|5.006000|5.004000|p sv_vsetpvf_mg|5.006000|5.004000|p sv_vsetpvfn||5.004000| sv_vsetpvf|5.006000|5.004000|p sv_xmlpeek||| svtype||| swallow_bom||| swash_fetch||5.007002| swash_get||| swash_init||5.006000| sys_init3||5.010000|n sys_init||5.010000|n sys_intern_clear||| sys_intern_dup||| sys_intern_init||| sys_term||5.010000|n taint_env||| taint_proper||| tied_method|||v tmps_grow||5.006000| toLOWER||| toUPPER||| to_byte_substr||| to_uni_fold||5.007003| to_uni_lower_lc||5.006000| to_uni_lower||5.007003| to_uni_title_lc||5.006000| to_uni_title||5.007003| to_uni_upper_lc||5.006000| to_uni_upper||5.007003| to_utf8_case||5.007003| to_utf8_fold||5.007003| to_utf8_lower||5.007003| to_utf8_substr||| to_utf8_title||5.007003| to_utf8_upper||5.007003| token_free||| token_getmad||| tokenize_use||| tokeq||| tokereport||| too_few_arguments||| too_many_arguments||| try_amagic_bin||| try_amagic_un||| uiv_2buf|||n unlnk||| unpack_rec||| unpack_str||5.007003| unpackstring||5.008001| unreferenced_to_tmp_stack||| unshare_hek_or_pvn||| unshare_hek||| unsharepvn||5.004000| unwind_handler_stack||| update_debugger_info||| upg_version||5.009005| usage||| utf16_textfilter||| utf16_to_utf8_reversed||5.006001| utf16_to_utf8||5.006001| utf8_distance||5.006000| utf8_hop||5.006000| utf8_length||5.007001| utf8_mg_len_cache_update||| utf8_mg_pos_cache_update||| utf8_to_bytes||5.006001| utf8_to_uvchr||5.007001| utf8_to_uvuni||5.007001| utf8n_to_uvchr||| utf8n_to_uvuni||5.007001| utilize||| uvchr_to_utf8_flags||5.007003| uvchr_to_utf8||| uvuni_to_utf8_flags||5.007003| uvuni_to_utf8||5.007001| validate_suid||| varname||| vcmp||5.009000| vcroak||5.006000| vdeb||5.007003| vform||5.006000| visit||| vivify_defelem||| vivify_ref||| vload_module|5.006000||p vmess||5.006000| vnewSVpvf|5.006000|5.004000|p vnormal||5.009002| vnumify||5.009000| vstringify||5.009000| vverify||5.009003| vwarner||5.006000| vwarn||5.006000| wait4pid||| warn_nocontext|||vn warn_sv||5.013001| warner_nocontext|||vn warner|5.006000|5.004000|pv warn|||v watch||| whichsig||| with_queued_errors||| write_no_mem||| write_to_stderr||| xmldump_all_perl||| xmldump_all||| xmldump_attr||| xmldump_eval||| xmldump_form||| xmldump_indent|||v xmldump_packsubs_perl||| xmldump_packsubs||| xmldump_sub_perl||| xmldump_sub||| xmldump_vindent||| xs_apiversion_bootcheck||| xs_version_bootcheck||| yyerror||| yylex||| yyparse||| yyunlex||| yywarn||| ); if (exists $opt{'list-unsupported'}) { my $f; for $f (sort { lc $a cmp lc $b } keys %API) { next unless $API{$f}{todo}; print "$f ", '.'x(40-length($f)), " ", format_version($API{$f}{todo}), "\n"; } exit 0; } # Scan for possible replacement candidates my(%replace, %need, %hints, %warnings, %depends); my $replace = 0; my($hint, $define, $function); sub find_api { my $code = shift; $code =~ s{ / (?: \*[^*]*\*+(?:[^$ccs][^*]*\*+)* / | /[^\r\n]*) | "[^"\\]*(?:\\.[^"\\]*)*" | '[^'\\]*(?:\\.[^'\\]*)*' }{}egsx; grep { exists $API{$_} } $code =~ /(\w+)/mg; } while () { if ($hint) { my $h = $hint->[0] eq 'Hint' ? \%hints : \%warnings; if (m{^\s*\*\s(.*?)\s*$}) { for (@{$hint->[1]}) { $h->{$_} ||= ''; # suppress warning with older perls $h->{$_} .= "$1\n"; } } else { undef $hint } } $hint = [$1, [split /,?\s+/, $2]] if m{^\s*$rccs\s+(Hint|Warning):\s+(\w+(?:,?\s+\w+)*)\s*$}; if ($define) { if ($define->[1] =~ /\\$/) { $define->[1] .= $_; } else { if (exists $API{$define->[0]} && $define->[1] !~ /^DPPP_\(/) { my @n = find_api($define->[1]); push @{$depends{$define->[0]}}, @n if @n } undef $define; } } $define = [$1, $2] if m{^\s*#\s*define\s+(\w+)(?:\([^)]*\))?\s+(.*)}; if ($function) { if (/^}/) { if (exists $API{$function->[0]}) { my @n = find_api($function->[1]); push @{$depends{$function->[0]}}, @n if @n } undef $function; } else { $function->[1] .= $_; } } $function = [$1, ''] if m{^DPPP_\(my_(\w+)\)}; $replace = $1 if m{^\s*$rccs\s+Replace:\s+(\d+)\s+$rcce\s*$}; $replace{$2} = $1 if $replace and m{^\s*#\s*define\s+(\w+)(?:\([^)]*\))?\s+(\w+)}; $replace{$2} = $1 if m{^\s*#\s*define\s+(\w+)(?:\([^)]*\))?\s+(\w+).*$rccs\s+Replace\s+$rcce}; $replace{$1} = $2 if m{^\s*$rccs\s+Replace (\w+) with (\w+)\s+$rcce\s*$}; if (m{^\s*$rccs\s+(\w+(\s*,\s*\w+)*)\s+depends\s+on\s+(\w+(\s*,\s*\w+)*)\s+$rcce\s*$}) { my @deps = map { s/\s+//g; $_ } split /,/, $3; my $d; for $d (map { s/\s+//g; $_ } split /,/, $1) { push @{$depends{$d}}, @deps; } } $need{$1} = 1 if m{^#if\s+defined\(NEED_(\w+)(?:_GLOBAL)?\)}; } for (values %depends) { my %s; $_ = [sort grep !$s{$_}++, @$_]; } if (exists $opt{'api-info'}) { my $f; my $count = 0; my $match = $opt{'api-info'} =~ m!^/(.*)/$! ? $1 : "^\Q$opt{'api-info'}\E\$"; for $f (sort { lc $a cmp lc $b } keys %API) { next unless $f =~ /$match/; print "\n=== $f ===\n\n"; my $info = 0; if ($API{$f}{base} || $API{$f}{todo}) { my $base = format_version($API{$f}{base} || $API{$f}{todo}); print "Supported at least starting from perl-$base.\n"; $info++; } if ($API{$f}{provided}) { my $todo = $API{$f}{todo} ? format_version($API{$f}{todo}) : "5.003"; print "Support by $ppport provided back to perl-$todo.\n"; print "Support needs to be explicitly requested by NEED_$f.\n" if exists $need{$f}; print "Depends on: ", join(', ', @{$depends{$f}}), ".\n" if exists $depends{$f}; print "\n$hints{$f}" if exists $hints{$f}; print "\nWARNING:\n$warnings{$f}" if exists $warnings{$f}; $info++; } print "No portability information available.\n" unless $info; $count++; } $count or print "Found no API matching '$opt{'api-info'}'."; print "\n"; exit 0; } if (exists $opt{'list-provided'}) { my $f; for $f (sort { lc $a cmp lc $b } keys %API) { next unless $API{$f}{provided}; my @flags; push @flags, 'explicit' if exists $need{$f}; push @flags, 'depend' if exists $depends{$f}; push @flags, 'hint' if exists $hints{$f}; push @flags, 'warning' if exists $warnings{$f}; my $flags = @flags ? ' ['.join(', ', @flags).']' : ''; print "$f$flags\n"; } exit 0; } my @files; my @srcext = qw( .xs .c .h .cc .cpp -c.inc -xs.inc ); my $srcext = join '|', map { quotemeta $_ } @srcext; if (@ARGV) { my %seen; for (@ARGV) { if (-e) { if (-f) { push @files, $_ unless $seen{$_}++; } else { warn "'$_' is not a file.\n" } } else { my @new = grep { -f } glob $_ or warn "'$_' does not exist.\n"; push @files, grep { !$seen{$_}++ } @new; } } } else { eval { require File::Find; File::Find::find(sub { $File::Find::name =~ /($srcext)$/i and push @files, $File::Find::name; }, '.'); }; if ($@) { @files = map { glob "*$_" } @srcext; } } if (!@ARGV || $opt{filter}) { my(@in, @out); my %xsc = map { /(.*)\.xs$/ ? ("$1.c" => 1, "$1.cc" => 1) : () } @files; for (@files) { my $out = exists $xsc{$_} || /\b\Q$ppport\E$/i || !/($srcext)$/i; push @{ $out ? \@out : \@in }, $_; } if (@ARGV && @out) { warning("Skipping the following files (use --nofilter to avoid this):\n| ", join "\n| ", @out); } @files = @in; } die "No input files given!\n" unless @files; my(%files, %global, %revreplace); %revreplace = reverse %replace; my $filename; my $patch_opened = 0; for $filename (@files) { unless (open IN, "<$filename") { warn "Unable to read from $filename: $!\n"; next; } info("Scanning $filename ..."); my $c = do { local $/; }; close IN; my %file = (orig => $c, changes => 0); # Temporarily remove C/XS comments and strings from the code my @ccom; $c =~ s{ ( ^$HS*\#$HS*include\b[^\r\n]+\b(?:\Q$ppport\E|XSUB\.h)\b[^\r\n]* | ^$HS*\#$HS*(?:define|elif|if(?:def)?)\b[^\r\n]* ) | ( ^$HS*\#[^\r\n]* | "[^"\\]*(?:\\.[^"\\]*)*" | '[^'\\]*(?:\\.[^'\\]*)*' | / (?: \*[^*]*\*+(?:[^$ccs][^*]*\*+)* / | /[^\r\n]* ) ) }{ defined $2 and push @ccom, $2; defined $1 ? $1 : "$ccs$#ccom$cce" }mgsex; $file{ccom} = \@ccom; $file{code} = $c; $file{has_inc_ppport} = $c =~ /^$HS*#$HS*include[^\r\n]+\b\Q$ppport\E\b/m; my $func; for $func (keys %API) { my $match = $func; $match .= "|$revreplace{$func}" if exists $revreplace{$func}; if ($c =~ /\b(?:Perl_)?($match)\b/) { $file{uses_replace}{$1}++ if exists $revreplace{$func} && $1 eq $revreplace{$func}; $file{uses_Perl}{$func}++ if $c =~ /\bPerl_$func\b/; if (exists $API{$func}{provided}) { $file{uses_provided}{$func}++; if (!exists $API{$func}{base} || $API{$func}{base} > $opt{'compat-version'}) { $file{uses}{$func}++; my @deps = rec_depend($func); if (@deps) { $file{uses_deps}{$func} = \@deps; for (@deps) { $file{uses}{$_} = 0 unless exists $file{uses}{$_}; } } for ($func, @deps) { $file{needs}{$_} = 'static' if exists $need{$_}; } } } if (exists $API{$func}{todo} && $API{$func}{todo} > $opt{'compat-version'}) { if ($c =~ /\b$func\b/) { $file{uses_todo}{$func}++; } } } } while ($c =~ /^$HS*#$HS*define$HS+(NEED_(\w+?)(_GLOBAL)?)\b/mg) { if (exists $need{$2}) { $file{defined $3 ? 'needed_global' : 'needed_static'}{$2}++; } else { warning("Possibly wrong #define $1 in $filename") } } for (qw(uses needs uses_todo needed_global needed_static)) { for $func (keys %{$file{$_}}) { push @{$global{$_}{$func}}, $filename; } } $files{$filename} = \%file; } # Globally resolve NEED_'s my $need; for $need (keys %{$global{needs}}) { if (@{$global{needs}{$need}} > 1) { my @targets = @{$global{needs}{$need}}; my @t = grep $files{$_}{needed_global}{$need}, @targets; @targets = @t if @t; @t = grep /\.xs$/i, @targets; @targets = @t if @t; my $target = shift @targets; $files{$target}{needs}{$need} = 'global'; for (@{$global{needs}{$need}}) { $files{$_}{needs}{$need} = 'extern' if $_ ne $target; } } } for $filename (@files) { exists $files{$filename} or next; info("=== Analyzing $filename ==="); my %file = %{$files{$filename}}; my $func; my $c = $file{code}; my $warnings = 0; for $func (sort keys %{$file{uses_Perl}}) { if ($API{$func}{varargs}) { unless ($API{$func}{nothxarg}) { my $changes = ($c =~ s{\b(Perl_$func\s*\(\s*)(?!aTHX_?)(\)|[^\s)]*\))} { $1 . ($2 eq ')' ? 'aTHX' : 'aTHX_ ') . $2 }ge); if ($changes) { warning("Doesn't pass interpreter argument aTHX to Perl_$func"); $file{changes} += $changes; } } } else { warning("Uses Perl_$func instead of $func"); $file{changes} += ($c =~ s{\bPerl_$func(\s*)\((\s*aTHX_?)?\s*} {$func$1(}g); } } for $func (sort keys %{$file{uses_replace}}) { warning("Uses $func instead of $replace{$func}"); $file{changes} += ($c =~ s/\b$func\b/$replace{$func}/g); } for $func (sort keys %{$file{uses_provided}}) { if ($file{uses}{$func}) { if (exists $file{uses_deps}{$func}) { diag("Uses $func, which depends on ", join(', ', @{$file{uses_deps}{$func}})); } else { diag("Uses $func"); } } $warnings += hint($func); } unless ($opt{quiet}) { for $func (sort keys %{$file{uses_todo}}) { print "*** WARNING: Uses $func, which may not be portable below perl ", format_version($API{$func}{todo}), ", even with '$ppport'\n"; $warnings++; } } for $func (sort keys %{$file{needed_static}}) { my $message = ''; if (not exists $file{uses}{$func}) { $message = "No need to define NEED_$func if $func is never used"; } elsif (exists $file{needs}{$func} && $file{needs}{$func} ne 'static') { $message = "No need to define NEED_$func when already needed globally"; } if ($message) { diag($message); $file{changes} += ($c =~ s/^$HS*#$HS*define$HS+NEED_$func\b.*$LF//mg); } } for $func (sort keys %{$file{needed_global}}) { my $message = ''; if (not exists $global{uses}{$func}) { $message = "No need to define NEED_${func}_GLOBAL if $func is never used"; } elsif (exists $file{needs}{$func}) { if ($file{needs}{$func} eq 'extern') { $message = "No need to define NEED_${func}_GLOBAL when already needed globally"; } elsif ($file{needs}{$func} eq 'static') { $message = "No need to define NEED_${func}_GLOBAL when only used in this file"; } } if ($message) { diag($message); $file{changes} += ($c =~ s/^$HS*#$HS*define$HS+NEED_${func}_GLOBAL\b.*$LF//mg); } } $file{needs_inc_ppport} = keys %{$file{uses}}; if ($file{needs_inc_ppport}) { my $pp = ''; for $func (sort keys %{$file{needs}}) { my $type = $file{needs}{$func}; next if $type eq 'extern'; my $suffix = $type eq 'global' ? '_GLOBAL' : ''; unless (exists $file{"needed_$type"}{$func}) { if ($type eq 'global') { diag("Files [@{$global{needs}{$func}}] need $func, adding global request"); } else { diag("File needs $func, adding static request"); } $pp .= "#define NEED_$func$suffix\n"; } } if ($pp && ($c =~ s/^(?=$HS*#$HS*define$HS+NEED_\w+)/$pp/m)) { $pp = ''; $file{changes}++; } unless ($file{has_inc_ppport}) { diag("Needs to include '$ppport'"); $pp .= qq(#include "$ppport"\n) } if ($pp) { $file{changes} += ($c =~ s/^($HS*#$HS*define$HS+NEED_\w+.*?)^/$1$pp/ms) || ($c =~ s/^(?=$HS*#$HS*include.*\Q$ppport\E)/$pp/m) || ($c =~ s/^($HS*#$HS*include.*XSUB.*\s*?)^/$1$pp/m) || ($c =~ s/^/$pp/); } } else { if ($file{has_inc_ppport}) { diag("No need to include '$ppport'"); $file{changes} += ($c =~ s/^$HS*?#$HS*include.*\Q$ppport\E.*?$LF//m); } } # put back in our C comments my $ix; my $cppc = 0; my @ccom = @{$file{ccom}}; for $ix (0 .. $#ccom) { if (!$opt{cplusplus} && $ccom[$ix] =~ s!^//!!) { $cppc++; $file{changes} += $c =~ s/$rccs$ix$rcce/$ccs$ccom[$ix] $cce/; } else { $c =~ s/$rccs$ix$rcce/$ccom[$ix]/; } } if ($cppc) { my $s = $cppc != 1 ? 's' : ''; warning("Uses $cppc C++ style comment$s, which is not portable"); } my $s = $warnings != 1 ? 's' : ''; my $warn = $warnings ? " ($warnings warning$s)" : ''; info("Analysis completed$warn"); if ($file{changes}) { if (exists $opt{copy}) { my $newfile = "$filename$opt{copy}"; if (-e $newfile) { error("'$newfile' already exists, refusing to write copy of '$filename'"); } else { local *F; if (open F, ">$newfile") { info("Writing copy of '$filename' with changes to '$newfile'"); print F $c; close F; } else { error("Cannot open '$newfile' for writing: $!"); } } } elsif (exists $opt{patch} || $opt{changes}) { if (exists $opt{patch}) { unless ($patch_opened) { if (open PATCH, ">$opt{patch}") { $patch_opened = 1; } else { error("Cannot open '$opt{patch}' for writing: $!"); delete $opt{patch}; $opt{changes} = 1; goto fallback; } } mydiff(\*PATCH, $filename, $c); } else { fallback: info("Suggested changes:"); mydiff(\*STDOUT, $filename, $c); } } else { my $s = $file{changes} == 1 ? '' : 's'; info("$file{changes} potentially required change$s detected"); } } else { info("Looks good"); } } close PATCH if $patch_opened; exit 0; sub try_use { eval "use @_;"; return $@ eq '' } sub mydiff { local *F = shift; my($file, $str) = @_; my $diff; if (exists $opt{diff}) { $diff = run_diff($opt{diff}, $file, $str); } if (!defined $diff and try_use('Text::Diff')) { $diff = Text::Diff::diff($file, \$str, { STYLE => 'Unified' }); $diff = <
$tmp") { print F $str; close F; if (open F, "$prog $file $tmp |") { while () { s/\Q$tmp\E/$file.patched/; $diff .= $_; } close F; unlink $tmp; return $diff; } unlink $tmp; } else { error("Cannot open '$tmp' for writing: $!"); } return undef; } sub rec_depend { my($func, $seen) = @_; return () unless exists $depends{$func}; $seen = {%{$seen||{}}}; return () if $seen->{$func}++; my %s; grep !$s{$_}++, map { ($_, rec_depend($_, $seen)) } @{$depends{$func}}; } sub parse_version { my $ver = shift; if ($ver =~ /^(\d+)\.(\d+)\.(\d+)$/) { return ($1, $2, $3); } elsif ($ver !~ /^\d+\.[\d_]+$/) { die "cannot parse version '$ver'\n"; } $ver =~ s/_//g; $ver =~ s/$/000000/; my($r,$v,$s) = $ver =~ /(\d+)\.(\d{3})(\d{3})/; $v = int $v; $s = int $s; if ($r < 5 || ($r == 5 && $v < 6)) { if ($s % 10) { die "cannot parse version '$ver'\n"; } } return ($r, $v, $s); } sub format_version { my $ver = shift; $ver =~ s/$/000000/; my($r,$v,$s) = $ver =~ /(\d+)\.(\d{3})(\d{3})/; $v = int $v; $s = int $s; if ($r < 5 || ($r == 5 && $v < 6)) { if ($s % 10) { die "invalid version '$ver'\n"; } $s /= 10; $ver = sprintf "%d.%03d", $r, $v; $s > 0 and $ver .= sprintf "_%02d", $s; return $ver; } return sprintf "%d.%d.%d", $r, $v, $s; } sub info { $opt{quiet} and return; print @_, "\n"; } sub diag { $opt{quiet} and return; $opt{diag} and print @_, "\n"; } sub warning { $opt{quiet} and return; print "*** ", @_, "\n"; } sub error { print "*** ERROR: ", @_, "\n"; } my %given_hints; my %given_warnings; sub hint { $opt{quiet} and return; my $func = shift; my $rv = 0; if (exists $warnings{$func} && !$given_warnings{$func}++) { my $warn = $warnings{$func}; $warn =~ s!^!*** !mg; print "*** WARNING: $func\n", $warn; $rv++; } if ($opt{hints} && exists $hints{$func} && !$given_hints{$func}++) { my $hint = $hints{$func}; $hint =~ s/^/ /mg; print " --- hint for $func ---\n", $hint; } $rv; } sub usage { my($usage) = do { local(@ARGV,$/)=($0); <> } =~ /^=head\d$HS+SYNOPSIS\s*^(.*?)\s*^=/ms; my %M = ( 'I' => '*' ); $usage =~ s/^\s*perl\s+\S+/$^X $0/; $usage =~ s/([A-Z])<([^>]+)>/$M{$1}$2$M{$1}/g; print < }; my($copy) = $self =~ /^=head\d\s+COPYRIGHT\s*^(.*?)^=\w+/ms; $copy =~ s/^(?=\S+)/ /gms; $self =~ s/^$HS+Do NOT edit.*?(?=^-)/$copy/ms; $self =~ s/^SKIP.*(?=^__DATA__)/SKIP if (\@ARGV && \$ARGV[0] eq '--unstrip') { eval { require Devel::PPPort }; \$@ and die "Cannot require Devel::PPPort, please install.\\n"; if (eval \$Devel::PPPort::VERSION < $VERSION) { die "$0 was originally generated with Devel::PPPort $VERSION.\\n" . "Your Devel::PPPort is only version \$Devel::PPPort::VERSION.\\n" . "Please install a newer version, or --unstrip will not work.\\n"; } Devel::PPPort::WriteFile(\$0); exit 0; } print <$0" or die "cannot strip $0: $!\n"; print OUT "$pl$c\n"; exit 0; } __DATA__ */ #ifndef _P_P_PORTABILITY_H_ #define _P_P_PORTABILITY_H_ #ifndef DPPP_NAMESPACE # define DPPP_NAMESPACE DPPP_ #endif #define DPPP_CAT2(x,y) CAT2(x,y) #define DPPP_(name) DPPP_CAT2(DPPP_NAMESPACE, name) #ifndef PERL_REVISION # if !defined(__PATCHLEVEL_H_INCLUDED__) && !(defined(PATCHLEVEL) && defined(SUBVERSION)) # define PERL_PATCHLEVEL_H_IMPLICIT # include # endif # if !(defined(PERL_VERSION) || (defined(SUBVERSION) && defined(PATCHLEVEL))) # include # endif # ifndef PERL_REVISION # define PERL_REVISION (5) /* Replace: 1 */ # define PERL_VERSION PATCHLEVEL # define PERL_SUBVERSION SUBVERSION /* Replace PERL_PATCHLEVEL with PERL_VERSION */ /* Replace: 0 */ # endif #endif #define _dpppDEC2BCD(dec) ((((dec)/100)<<8)|((((dec)%100)/10)<<4)|((dec)%10)) #define PERL_BCDVERSION ((_dpppDEC2BCD(PERL_REVISION)<<24)|(_dpppDEC2BCD(PERL_VERSION)<<12)|_dpppDEC2BCD(PERL_SUBVERSION)) /* It is very unlikely that anyone will try to use this with Perl 6 (or greater), but who knows. */ #if PERL_REVISION != 5 # error ppport.h only works with Perl version 5 #endif /* PERL_REVISION != 5 */ #ifndef dTHR # define dTHR dNOOP #endif #ifndef dTHX # define dTHX dNOOP #endif #ifndef dTHXa # define dTHXa(x) dNOOP #endif #ifndef pTHX # define pTHX void #endif #ifndef pTHX_ # define pTHX_ #endif #ifndef aTHX # define aTHX #endif #ifndef aTHX_ # define aTHX_ #endif #if (PERL_BCDVERSION < 0x5006000) # ifdef USE_THREADS # define aTHXR thr # define aTHXR_ thr, # else # define aTHXR # define aTHXR_ # endif # define dTHXR dTHR #else # define aTHXR aTHX # define aTHXR_ aTHX_ # define dTHXR dTHX #endif #ifndef dTHXoa # define dTHXoa(x) dTHXa(x) #endif #ifdef I_LIMITS # include #endif #ifndef PERL_UCHAR_MIN # define PERL_UCHAR_MIN ((unsigned char)0) #endif #ifndef PERL_UCHAR_MAX # ifdef UCHAR_MAX # define PERL_UCHAR_MAX ((unsigned char)UCHAR_MAX) # else # ifdef MAXUCHAR # define PERL_UCHAR_MAX ((unsigned char)MAXUCHAR) # else # define PERL_UCHAR_MAX ((unsigned char)~(unsigned)0) # endif # endif #endif #ifndef PERL_USHORT_MIN # define PERL_USHORT_MIN ((unsigned short)0) #endif #ifndef PERL_USHORT_MAX # ifdef USHORT_MAX # define PERL_USHORT_MAX ((unsigned short)USHORT_MAX) # else # ifdef MAXUSHORT # define PERL_USHORT_MAX ((unsigned short)MAXUSHORT) # else # ifdef USHRT_MAX # define PERL_USHORT_MAX ((unsigned short)USHRT_MAX) # else # define PERL_USHORT_MAX ((unsigned short)~(unsigned)0) # endif # endif # endif #endif #ifndef PERL_SHORT_MAX # ifdef SHORT_MAX # define PERL_SHORT_MAX ((short)SHORT_MAX) # else # ifdef MAXSHORT /* Often used in */ # define PERL_SHORT_MAX ((short)MAXSHORT) # else # ifdef SHRT_MAX # define PERL_SHORT_MAX ((short)SHRT_MAX) # else # define PERL_SHORT_MAX ((short) (PERL_USHORT_MAX >> 1)) # endif # endif # endif #endif #ifndef PERL_SHORT_MIN # ifdef SHORT_MIN # define PERL_SHORT_MIN ((short)SHORT_MIN) # else # ifdef MINSHORT # define PERL_SHORT_MIN ((short)MINSHORT) # else # ifdef SHRT_MIN # define PERL_SHORT_MIN ((short)SHRT_MIN) # else # define PERL_SHORT_MIN (-PERL_SHORT_MAX - ((3 & -1) == 3)) # endif # endif # endif #endif #ifndef PERL_UINT_MAX # ifdef UINT_MAX # define PERL_UINT_MAX ((unsigned int)UINT_MAX) # else # ifdef MAXUINT # define PERL_UINT_MAX ((unsigned int)MAXUINT) # else # define PERL_UINT_MAX (~(unsigned int)0) # endif # endif #endif #ifndef PERL_UINT_MIN # define PERL_UINT_MIN ((unsigned int)0) #endif #ifndef PERL_INT_MAX # ifdef INT_MAX # define PERL_INT_MAX ((int)INT_MAX) # else # ifdef MAXINT /* Often used in */ # define PERL_INT_MAX ((int)MAXINT) # else # define PERL_INT_MAX ((int)(PERL_UINT_MAX >> 1)) # endif # endif #endif #ifndef PERL_INT_MIN # ifdef INT_MIN # define PERL_INT_MIN ((int)INT_MIN) # else # ifdef MININT # define PERL_INT_MIN ((int)MININT) # else # define PERL_INT_MIN (-PERL_INT_MAX - ((3 & -1) == 3)) # endif # endif #endif #ifndef PERL_ULONG_MAX # ifdef ULONG_MAX # define PERL_ULONG_MAX ((unsigned long)ULONG_MAX) # else # ifdef MAXULONG # define PERL_ULONG_MAX ((unsigned long)MAXULONG) # else # define PERL_ULONG_MAX (~(unsigned long)0) # endif # endif #endif #ifndef PERL_ULONG_MIN # define PERL_ULONG_MIN ((unsigned long)0L) #endif #ifndef PERL_LONG_MAX # ifdef LONG_MAX # define PERL_LONG_MAX ((long)LONG_MAX) # else # ifdef MAXLONG # define PERL_LONG_MAX ((long)MAXLONG) # else # define PERL_LONG_MAX ((long) (PERL_ULONG_MAX >> 1)) # endif # endif #endif #ifndef PERL_LONG_MIN # ifdef LONG_MIN # define PERL_LONG_MIN ((long)LONG_MIN) # else # ifdef MINLONG # define PERL_LONG_MIN ((long)MINLONG) # else # define PERL_LONG_MIN (-PERL_LONG_MAX - ((3 & -1) == 3)) # endif # endif #endif #if defined(HAS_QUAD) && (defined(convex) || defined(uts)) # ifndef PERL_UQUAD_MAX # ifdef ULONGLONG_MAX # define PERL_UQUAD_MAX ((unsigned long long)ULONGLONG_MAX) # else # ifdef MAXULONGLONG # define PERL_UQUAD_MAX ((unsigned long long)MAXULONGLONG) # else # define PERL_UQUAD_MAX (~(unsigned long long)0) # endif # endif # endif # ifndef PERL_UQUAD_MIN # define PERL_UQUAD_MIN ((unsigned long long)0L) # endif # ifndef PERL_QUAD_MAX # ifdef LONGLONG_MAX # define PERL_QUAD_MAX ((long long)LONGLONG_MAX) # else # ifdef MAXLONGLONG # define PERL_QUAD_MAX ((long long)MAXLONGLONG) # else # define PERL_QUAD_MAX ((long long) (PERL_UQUAD_MAX >> 1)) # endif # endif # endif # ifndef PERL_QUAD_MIN # ifdef LONGLONG_MIN # define PERL_QUAD_MIN ((long long)LONGLONG_MIN) # else # ifdef MINLONGLONG # define PERL_QUAD_MIN ((long long)MINLONGLONG) # else # define PERL_QUAD_MIN (-PERL_QUAD_MAX - ((3 & -1) == 3)) # endif # endif # endif #endif /* This is based on code from 5.003 perl.h */ #ifdef HAS_QUAD # ifdef cray #ifndef IVTYPE # define IVTYPE int #endif #ifndef IV_MIN # define IV_MIN PERL_INT_MIN #endif #ifndef IV_MAX # define IV_MAX PERL_INT_MAX #endif #ifndef UV_MIN # define UV_MIN PERL_UINT_MIN #endif #ifndef UV_MAX # define UV_MAX PERL_UINT_MAX #endif # ifdef INTSIZE #ifndef IVSIZE # define IVSIZE INTSIZE #endif # endif # else # if defined(convex) || defined(uts) #ifndef IVTYPE # define IVTYPE long long #endif #ifndef IV_MIN # define IV_MIN PERL_QUAD_MIN #endif #ifndef IV_MAX # define IV_MAX PERL_QUAD_MAX #endif #ifndef UV_MIN # define UV_MIN PERL_UQUAD_MIN #endif #ifndef UV_MAX # define UV_MAX PERL_UQUAD_MAX #endif # ifdef LONGLONGSIZE #ifndef IVSIZE # define IVSIZE LONGLONGSIZE #endif # endif # else #ifndef IVTYPE # define IVTYPE long #endif #ifndef IV_MIN # define IV_MIN PERL_LONG_MIN #endif #ifndef IV_MAX # define IV_MAX PERL_LONG_MAX #endif #ifndef UV_MIN # define UV_MIN PERL_ULONG_MIN #endif #ifndef UV_MAX # define UV_MAX PERL_ULONG_MAX #endif # ifdef LONGSIZE #ifndef IVSIZE # define IVSIZE LONGSIZE #endif # endif # endif # endif #ifndef IVSIZE # define IVSIZE 8 #endif #ifndef PERL_QUAD_MIN # define PERL_QUAD_MIN IV_MIN #endif #ifndef PERL_QUAD_MAX # define PERL_QUAD_MAX IV_MAX #endif #ifndef PERL_UQUAD_MIN # define PERL_UQUAD_MIN UV_MIN #endif #ifndef PERL_UQUAD_MAX # define PERL_UQUAD_MAX UV_MAX #endif #else #ifndef IVTYPE # define IVTYPE long #endif #ifndef IV_MIN # define IV_MIN PERL_LONG_MIN #endif #ifndef IV_MAX # define IV_MAX PERL_LONG_MAX #endif #ifndef UV_MIN # define UV_MIN PERL_ULONG_MIN #endif #ifndef UV_MAX # define UV_MAX PERL_ULONG_MAX #endif #endif #ifndef IVSIZE # ifdef LONGSIZE # define IVSIZE LONGSIZE # else # define IVSIZE 4 /* A bold guess, but the best we can make. */ # endif #endif #ifndef UVTYPE # define UVTYPE unsigned IVTYPE #endif #ifndef UVSIZE # define UVSIZE IVSIZE #endif #ifndef sv_setuv # define sv_setuv(sv, uv) \ STMT_START { \ UV TeMpUv = uv; \ if (TeMpUv <= IV_MAX) \ sv_setiv(sv, TeMpUv); \ else \ sv_setnv(sv, (double)TeMpUv); \ } STMT_END #endif #ifndef newSVuv # define newSVuv(uv) ((uv) <= IV_MAX ? newSViv((IV)uv) : newSVnv((NV)uv)) #endif #ifndef sv_2uv # define sv_2uv(sv) ((PL_Sv = (sv)), (UV) (SvNOK(PL_Sv) ? SvNV(PL_Sv) : sv_2nv(PL_Sv))) #endif #ifndef SvUVX # define SvUVX(sv) ((UV)SvIVX(sv)) #endif #ifndef SvUVXx # define SvUVXx(sv) SvUVX(sv) #endif #ifndef SvUV # define SvUV(sv) (SvIOK(sv) ? SvUVX(sv) : sv_2uv(sv)) #endif #ifndef SvUVx # define SvUVx(sv) ((PL_Sv = (sv)), SvUV(PL_Sv)) #endif /* Hint: sv_uv * Always use the SvUVx() macro instead of sv_uv(). */ #ifndef sv_uv # define sv_uv(sv) SvUVx(sv) #endif #if !defined(SvUOK) && defined(SvIOK_UV) # define SvUOK(sv) SvIOK_UV(sv) #endif #ifndef XST_mUV # define XST_mUV(i,v) (ST(i) = sv_2mortal(newSVuv(v)) ) #endif #ifndef XSRETURN_UV # define XSRETURN_UV(v) STMT_START { XST_mUV(0,v); XSRETURN(1); } STMT_END #endif #ifndef PUSHu # define PUSHu(u) STMT_START { sv_setuv(TARG, (UV)(u)); PUSHTARG; } STMT_END #endif #ifndef XPUSHu # define XPUSHu(u) STMT_START { sv_setuv(TARG, (UV)(u)); XPUSHTARG; } STMT_END #endif #ifdef HAS_MEMCMP #ifndef memNE # define memNE(s1,s2,l) (memcmp(s1,s2,l)) #endif #ifndef memEQ # define memEQ(s1,s2,l) (!memcmp(s1,s2,l)) #endif #else #ifndef memNE # define memNE(s1,s2,l) (bcmp(s1,s2,l)) #endif #ifndef memEQ # define memEQ(s1,s2,l) (!bcmp(s1,s2,l)) #endif #endif #ifndef memEQs # define memEQs(s1, l, s2) \ (sizeof(s2)-1 == l && memEQ(s1, (s2 ""), (sizeof(s2)-1))) #endif #ifndef memNEs # define memNEs(s1, l, s2) !memEQs(s1, l, s2) #endif #ifndef MoveD # define MoveD(s,d,n,t) memmove((char*)(d),(char*)(s), (n) * sizeof(t)) #endif #ifndef CopyD # define CopyD(s,d,n,t) memcpy((char*)(d),(char*)(s), (n) * sizeof(t)) #endif #ifdef HAS_MEMSET #ifndef ZeroD # define ZeroD(d,n,t) memzero((char*)(d), (n) * sizeof(t)) #endif #else #ifndef ZeroD # define ZeroD(d,n,t) ((void)memzero((char*)(d), (n) * sizeof(t)), d) #endif #endif #ifndef PoisonWith # define PoisonWith(d,n,t,b) (void)memset((char*)(d), (U8)(b), (n) * sizeof(t)) #endif #ifndef PoisonNew # define PoisonNew(d,n,t) PoisonWith(d,n,t,0xAB) #endif #ifndef PoisonFree # define PoisonFree(d,n,t) PoisonWith(d,n,t,0xEF) #endif #ifndef Poison # define Poison(d,n,t) PoisonFree(d,n,t) #endif #ifndef Newx # define Newx(v,n,t) New(0,v,n,t) #endif #ifndef Newxc # define Newxc(v,n,t,c) Newc(0,v,n,t,c) #endif #ifndef Newxz # define Newxz(v,n,t) Newz(0,v,n,t) #endif #ifndef PERL_UNUSED_DECL # ifdef HASATTRIBUTE # if (defined(__GNUC__) && defined(__cplusplus)) || defined(__INTEL_COMPILER) # define PERL_UNUSED_DECL # else # define PERL_UNUSED_DECL __attribute__((unused)) # endif # else # define PERL_UNUSED_DECL # endif #endif #ifndef PERL_UNUSED_ARG # if defined(lint) && defined(S_SPLINT_S) /* www.splint.org */ # include # define PERL_UNUSED_ARG(x) NOTE(ARGUNUSED(x)) # else # define PERL_UNUSED_ARG(x) ((void)x) # endif #endif #ifndef PERL_UNUSED_VAR # define PERL_UNUSED_VAR(x) ((void)x) #endif #ifndef PERL_UNUSED_CONTEXT # ifdef USE_ITHREADS # define PERL_UNUSED_CONTEXT PERL_UNUSED_ARG(my_perl) # else # define PERL_UNUSED_CONTEXT # endif #endif #ifndef NOOP # define NOOP /*EMPTY*/(void)0 #endif #ifndef dNOOP # define dNOOP extern int /*@unused@*/ Perl___notused PERL_UNUSED_DECL #endif #ifndef NVTYPE # if defined(USE_LONG_DOUBLE) && defined(HAS_LONG_DOUBLE) # define NVTYPE long double # else # define NVTYPE double # endif typedef NVTYPE NV; #endif #ifndef INT2PTR # if (IVSIZE == PTRSIZE) && (UVSIZE == PTRSIZE) # define PTRV UV # define INT2PTR(any,d) (any)(d) # else # if PTRSIZE == LONGSIZE # define PTRV unsigned long # else # define PTRV unsigned # endif # define INT2PTR(any,d) (any)(PTRV)(d) # endif #endif #ifndef PTR2ul # if PTRSIZE == LONGSIZE # define PTR2ul(p) (unsigned long)(p) # else # define PTR2ul(p) INT2PTR(unsigned long,p) # endif #endif #ifndef PTR2nat # define PTR2nat(p) (PTRV)(p) #endif #ifndef NUM2PTR # define NUM2PTR(any,d) (any)PTR2nat(d) #endif #ifndef PTR2IV # define PTR2IV(p) INT2PTR(IV,p) #endif #ifndef PTR2UV # define PTR2UV(p) INT2PTR(UV,p) #endif #ifndef PTR2NV # define PTR2NV(p) NUM2PTR(NV,p) #endif #undef START_EXTERN_C #undef END_EXTERN_C #undef EXTERN_C #ifdef __cplusplus # define START_EXTERN_C extern "C" { # define END_EXTERN_C } # define EXTERN_C extern "C" #else # define START_EXTERN_C # define END_EXTERN_C # define EXTERN_C extern #endif #if defined(PERL_GCC_PEDANTIC) # ifndef PERL_GCC_BRACE_GROUPS_FORBIDDEN # define PERL_GCC_BRACE_GROUPS_FORBIDDEN # endif #endif #if defined(__GNUC__) && !defined(PERL_GCC_BRACE_GROUPS_FORBIDDEN) && !defined(__cplusplus) # ifndef PERL_USE_GCC_BRACE_GROUPS # define PERL_USE_GCC_BRACE_GROUPS # endif #endif #undef STMT_START #undef STMT_END #ifdef PERL_USE_GCC_BRACE_GROUPS # define STMT_START (void)( /* gcc supports ``({ STATEMENTS; })'' */ # define STMT_END ) #else # if defined(VOIDFLAGS) && (VOIDFLAGS) && (defined(sun) || defined(__sun__)) && !defined(__GNUC__) # define STMT_START if (1) # define STMT_END else (void)0 # else # define STMT_START do # define STMT_END while (0) # endif #endif #ifndef boolSV # define boolSV(b) ((b) ? &PL_sv_yes : &PL_sv_no) #endif /* DEFSV appears first in 5.004_56 */ #ifndef DEFSV # define DEFSV GvSV(PL_defgv) #endif #ifndef SAVE_DEFSV # define SAVE_DEFSV SAVESPTR(GvSV(PL_defgv)) #endif #ifndef DEFSV_set # define DEFSV_set(sv) (DEFSV = (sv)) #endif /* Older perls (<=5.003) lack AvFILLp */ #ifndef AvFILLp # define AvFILLp AvFILL #endif #ifndef ERRSV # define ERRSV get_sv("@",FALSE) #endif /* Hint: gv_stashpvn * This function's backport doesn't support the length parameter, but * rather ignores it. Portability can only be ensured if the length * parameter is used for speed reasons, but the length can always be * correctly computed from the string argument. */ #ifndef gv_stashpvn # define gv_stashpvn(str,len,create) gv_stashpv(str,create) #endif /* Replace: 1 */ #ifndef get_cv # define get_cv perl_get_cv #endif #ifndef get_sv # define get_sv perl_get_sv #endif #ifndef get_av # define get_av perl_get_av #endif #ifndef get_hv # define get_hv perl_get_hv #endif /* Replace: 0 */ #ifndef dUNDERBAR # define dUNDERBAR dNOOP #endif #ifndef UNDERBAR # define UNDERBAR DEFSV #endif #ifndef dAX # define dAX I32 ax = MARK - PL_stack_base + 1 #endif #ifndef dITEMS # define dITEMS I32 items = SP - MARK #endif #ifndef dXSTARG # define dXSTARG SV * targ = sv_newmortal() #endif #ifndef dAXMARK # define dAXMARK I32 ax = POPMARK; \ register SV ** const mark = PL_stack_base + ax++ #endif #ifndef XSprePUSH # define XSprePUSH (sp = PL_stack_base + ax - 1) #endif #if (PERL_BCDVERSION < 0x5005000) # undef XSRETURN # define XSRETURN(off) \ STMT_START { \ PL_stack_sp = PL_stack_base + ax + ((off) - 1); \ return; \ } STMT_END #endif #ifndef XSPROTO # define XSPROTO(name) void name(pTHX_ CV* cv) #endif #ifndef SVfARG # define SVfARG(p) ((void*)(p)) #endif #ifndef PERL_ABS # define PERL_ABS(x) ((x) < 0 ? -(x) : (x)) #endif #ifndef dVAR # define dVAR dNOOP #endif #ifndef SVf # define SVf "_" #endif #ifndef UTF8_MAXBYTES # define UTF8_MAXBYTES UTF8_MAXLEN #endif #ifndef CPERLscope # define CPERLscope(x) x #endif #ifndef PERL_HASH # define PERL_HASH(hash,str,len) \ STMT_START { \ const char *s_PeRlHaSh = str; \ I32 i_PeRlHaSh = len; \ U32 hash_PeRlHaSh = 0; \ while (i_PeRlHaSh--) \ hash_PeRlHaSh = hash_PeRlHaSh * 33 + *s_PeRlHaSh++; \ (hash) = hash_PeRlHaSh; \ } STMT_END #endif #ifndef PERLIO_FUNCS_DECL # ifdef PERLIO_FUNCS_CONST # define PERLIO_FUNCS_DECL(funcs) const PerlIO_funcs funcs # define PERLIO_FUNCS_CAST(funcs) (PerlIO_funcs*)(funcs) # else # define PERLIO_FUNCS_DECL(funcs) PerlIO_funcs funcs # define PERLIO_FUNCS_CAST(funcs) (funcs) # endif #endif /* provide these typedefs for older perls */ #if (PERL_BCDVERSION < 0x5009003) # ifdef ARGSproto typedef OP* (CPERLscope(*Perl_ppaddr_t))(ARGSproto); # else typedef OP* (CPERLscope(*Perl_ppaddr_t))(pTHX); # endif typedef OP* (CPERLscope(*Perl_check_t)) (pTHX_ OP*); #endif #ifndef isPSXSPC # define isPSXSPC(c) (isSPACE(c) || (c) == '\v') #endif #ifndef isBLANK # define isBLANK(c) ((c) == ' ' || (c) == '\t') #endif #ifdef EBCDIC #ifndef isALNUMC # define isALNUMC(c) isalnum(c) #endif #ifndef isASCII # define isASCII(c) isascii(c) #endif #ifndef isCNTRL # define isCNTRL(c) iscntrl(c) #endif #ifndef isGRAPH # define isGRAPH(c) isgraph(c) #endif #ifndef isPRINT # define isPRINT(c) isprint(c) #endif #ifndef isPUNCT # define isPUNCT(c) ispunct(c) #endif #ifndef isXDIGIT # define isXDIGIT(c) isxdigit(c) #endif #else # if (PERL_BCDVERSION < 0x5010000) /* Hint: isPRINT * The implementation in older perl versions includes all of the * isSPACE() characters, which is wrong. The version provided by * Devel::PPPort always overrides a present buggy version. */ # undef isPRINT # endif #ifndef isALNUMC # define isALNUMC(c) (isALPHA(c) || isDIGIT(c)) #endif #ifndef isASCII # define isASCII(c) ((U8) (c) <= 127) #endif #ifndef isCNTRL # define isCNTRL(c) ((U8) (c) < ' ' || (c) == 127) #endif #ifndef isGRAPH # define isGRAPH(c) (isALNUM(c) || isPUNCT(c)) #endif #ifndef isPRINT # define isPRINT(c) (((c) >= 32 && (c) < 127)) #endif #ifndef isPUNCT # define isPUNCT(c) (((c) >= 33 && (c) <= 47) || ((c) >= 58 && (c) <= 64) || ((c) >= 91 && (c) <= 96) || ((c) >= 123 && (c) <= 126)) #endif #ifndef isXDIGIT # define isXDIGIT(c) (isDIGIT(c) || ((c) >= 'a' && (c) <= 'f') || ((c) >= 'A' && (c) <= 'F')) #endif #endif #ifndef PERL_SIGNALS_UNSAFE_FLAG #define PERL_SIGNALS_UNSAFE_FLAG 0x0001 #if (PERL_BCDVERSION < 0x5008000) # define D_PPP_PERL_SIGNALS_INIT PERL_SIGNALS_UNSAFE_FLAG #else # define D_PPP_PERL_SIGNALS_INIT 0 #endif #if defined(NEED_PL_signals) static U32 DPPP_(my_PL_signals) = D_PPP_PERL_SIGNALS_INIT; #elif defined(NEED_PL_signals_GLOBAL) U32 DPPP_(my_PL_signals) = D_PPP_PERL_SIGNALS_INIT; #else extern U32 DPPP_(my_PL_signals); #endif #define PL_signals DPPP_(my_PL_signals) #endif /* Hint: PL_ppaddr * Calling an op via PL_ppaddr requires passing a context argument * for threaded builds. Since the context argument is different for * 5.005 perls, you can use aTHXR (supplied by ppport.h), which will * automatically be defined as the correct argument. */ #if (PERL_BCDVERSION <= 0x5005005) /* Replace: 1 */ # define PL_ppaddr ppaddr # define PL_no_modify no_modify /* Replace: 0 */ #endif #if (PERL_BCDVERSION <= 0x5004005) /* Replace: 1 */ # define PL_DBsignal DBsignal # define PL_DBsingle DBsingle # define PL_DBsub DBsub # define PL_DBtrace DBtrace # define PL_Sv Sv # define PL_bufend bufend # define PL_bufptr bufptr # define PL_compiling compiling # define PL_copline copline # define PL_curcop curcop # define PL_curstash curstash # define PL_debstash debstash # define PL_defgv defgv # define PL_diehook diehook # define PL_dirty dirty # define PL_dowarn dowarn # define PL_errgv errgv # define PL_error_count error_count # define PL_expect expect # define PL_hexdigit hexdigit # define PL_hints hints # define PL_in_my in_my # define PL_laststatval laststatval # define PL_lex_state lex_state # define PL_lex_stuff lex_stuff # define PL_linestr linestr # define PL_na na # define PL_perl_destruct_level perl_destruct_level # define PL_perldb perldb # define PL_rsfp_filters rsfp_filters # define PL_rsfp rsfp # define PL_stack_base stack_base # define PL_stack_sp stack_sp # define PL_statcache statcache # define PL_stdingv stdingv # define PL_sv_arenaroot sv_arenaroot # define PL_sv_no sv_no # define PL_sv_undef sv_undef # define PL_sv_yes sv_yes # define PL_tainted tainted # define PL_tainting tainting # define PL_tokenbuf tokenbuf /* Replace: 0 */ #endif /* Warning: PL_parser * For perl versions earlier than 5.9.5, this is an always * non-NULL dummy. Also, it cannot be dereferenced. Don't * use it if you can avoid is and unless you absolutely know * what you're doing. * If you always check that PL_parser is non-NULL, you can * define DPPP_PL_parser_NO_DUMMY to avoid the creation of * a dummy parser structure. */ #if (PERL_BCDVERSION >= 0x5009005) # ifdef DPPP_PL_parser_NO_DUMMY # define D_PPP_my_PL_parser_var(var) ((PL_parser ? PL_parser : \ (croak("panic: PL_parser == NULL in %s:%d", \ __FILE__, __LINE__), (yy_parser *) NULL))->var) # else # ifdef DPPP_PL_parser_NO_DUMMY_WARNING # define D_PPP_parser_dummy_warning(var) # else # define D_PPP_parser_dummy_warning(var) \ warn("warning: dummy PL_" #var " used in %s:%d", __FILE__, __LINE__), # endif # define D_PPP_my_PL_parser_var(var) ((PL_parser ? PL_parser : \ (D_PPP_parser_dummy_warning(var) &DPPP_(dummy_PL_parser)))->var) #if defined(NEED_PL_parser) static yy_parser DPPP_(dummy_PL_parser); #elif defined(NEED_PL_parser_GLOBAL) yy_parser DPPP_(dummy_PL_parser); #else extern yy_parser DPPP_(dummy_PL_parser); #endif # endif /* PL_expect, PL_copline, PL_rsfp, PL_rsfp_filters, PL_linestr, PL_bufptr, PL_bufend, PL_lex_state, PL_lex_stuff, PL_tokenbuf depends on PL_parser */ /* Warning: PL_expect, PL_copline, PL_rsfp, PL_rsfp_filters, PL_linestr, PL_bufptr, PL_bufend, PL_lex_state, PL_lex_stuff, PL_tokenbuf * Do not use this variable unless you know exactly what you're * doint. It is internal to the perl parser and may change or even * be removed in the future. As of perl 5.9.5, you have to check * for (PL_parser != NULL) for this variable to have any effect. * An always non-NULL PL_parser dummy is provided for earlier * perl versions. * If PL_parser is NULL when you try to access this variable, a * dummy is being accessed instead and a warning is issued unless * you define DPPP_PL_parser_NO_DUMMY_WARNING. * If DPPP_PL_parser_NO_DUMMY is defined, the code trying to access * this variable will croak with a panic message. */ # define PL_expect D_PPP_my_PL_parser_var(expect) # define PL_copline D_PPP_my_PL_parser_var(copline) # define PL_rsfp D_PPP_my_PL_parser_var(rsfp) # define PL_rsfp_filters D_PPP_my_PL_parser_var(rsfp_filters) # define PL_linestr D_PPP_my_PL_parser_var(linestr) # define PL_bufptr D_PPP_my_PL_parser_var(bufptr) # define PL_bufend D_PPP_my_PL_parser_var(bufend) # define PL_lex_state D_PPP_my_PL_parser_var(lex_state) # define PL_lex_stuff D_PPP_my_PL_parser_var(lex_stuff) # define PL_tokenbuf D_PPP_my_PL_parser_var(tokenbuf) # define PL_in_my D_PPP_my_PL_parser_var(in_my) # define PL_in_my_stash D_PPP_my_PL_parser_var(in_my_stash) # define PL_error_count D_PPP_my_PL_parser_var(error_count) #else /* ensure that PL_parser != NULL and cannot be dereferenced */ # define PL_parser ((void *) 1) #endif #ifndef mPUSHs # define mPUSHs(s) PUSHs(sv_2mortal(s)) #endif #ifndef PUSHmortal # define PUSHmortal PUSHs(sv_newmortal()) #endif #ifndef mPUSHp # define mPUSHp(p,l) sv_setpvn(PUSHmortal, (p), (l)) #endif #ifndef mPUSHn # define mPUSHn(n) sv_setnv(PUSHmortal, (NV)(n)) #endif #ifndef mPUSHi # define mPUSHi(i) sv_setiv(PUSHmortal, (IV)(i)) #endif #ifndef mPUSHu # define mPUSHu(u) sv_setuv(PUSHmortal, (UV)(u)) #endif #ifndef mXPUSHs # define mXPUSHs(s) XPUSHs(sv_2mortal(s)) #endif #ifndef XPUSHmortal # define XPUSHmortal XPUSHs(sv_newmortal()) #endif #ifndef mXPUSHp # define mXPUSHp(p,l) STMT_START { EXTEND(sp,1); sv_setpvn(PUSHmortal, (p), (l)); } STMT_END #endif #ifndef mXPUSHn # define mXPUSHn(n) STMT_START { EXTEND(sp,1); sv_setnv(PUSHmortal, (NV)(n)); } STMT_END #endif #ifndef mXPUSHi # define mXPUSHi(i) STMT_START { EXTEND(sp,1); sv_setiv(PUSHmortal, (IV)(i)); } STMT_END #endif #ifndef mXPUSHu # define mXPUSHu(u) STMT_START { EXTEND(sp,1); sv_setuv(PUSHmortal, (UV)(u)); } STMT_END #endif /* Replace: 1 */ #ifndef call_sv # define call_sv perl_call_sv #endif #ifndef call_pv # define call_pv perl_call_pv #endif #ifndef call_argv # define call_argv perl_call_argv #endif #ifndef call_method # define call_method perl_call_method #endif #ifndef eval_sv # define eval_sv perl_eval_sv #endif /* Replace: 0 */ #ifndef PERL_LOADMOD_DENY # define PERL_LOADMOD_DENY 0x1 #endif #ifndef PERL_LOADMOD_NOIMPORT # define PERL_LOADMOD_NOIMPORT 0x2 #endif #ifndef PERL_LOADMOD_IMPORT_OPS # define PERL_LOADMOD_IMPORT_OPS 0x4 #endif #ifndef G_METHOD # define G_METHOD 64 # ifdef call_sv # undef call_sv # endif # if (PERL_BCDVERSION < 0x5006000) # define call_sv(sv, flags) ((flags) & G_METHOD ? perl_call_method((char *) SvPV_nolen_const(sv), \ (flags) & ~G_METHOD) : perl_call_sv(sv, flags)) # else # define call_sv(sv, flags) ((flags) & G_METHOD ? Perl_call_method(aTHX_ (char *) SvPV_nolen_const(sv), \ (flags) & ~G_METHOD) : Perl_call_sv(aTHX_ sv, flags)) # endif #endif /* Replace perl_eval_pv with eval_pv */ #ifndef eval_pv #if defined(NEED_eval_pv) static SV* DPPP_(my_eval_pv)(char *p, I32 croak_on_error); static #else extern SV* DPPP_(my_eval_pv)(char *p, I32 croak_on_error); #endif #ifdef eval_pv # undef eval_pv #endif #define eval_pv(a,b) DPPP_(my_eval_pv)(aTHX_ a,b) #define Perl_eval_pv DPPP_(my_eval_pv) #if defined(NEED_eval_pv) || defined(NEED_eval_pv_GLOBAL) SV* DPPP_(my_eval_pv)(char *p, I32 croak_on_error) { dSP; SV* sv = newSVpv(p, 0); PUSHMARK(sp); eval_sv(sv, G_SCALAR); SvREFCNT_dec(sv); SPAGAIN; sv = POPs; PUTBACK; if (croak_on_error && SvTRUE(GvSV(errgv))) croak(SvPVx(GvSV(errgv), na)); return sv; } #endif #endif #ifndef vload_module #if defined(NEED_vload_module) static void DPPP_(my_vload_module)(U32 flags, SV *name, SV *ver, va_list *args); static #else extern void DPPP_(my_vload_module)(U32 flags, SV *name, SV *ver, va_list *args); #endif #ifdef vload_module # undef vload_module #endif #define vload_module(a,b,c,d) DPPP_(my_vload_module)(aTHX_ a,b,c,d) #define Perl_vload_module DPPP_(my_vload_module) #if defined(NEED_vload_module) || defined(NEED_vload_module_GLOBAL) void DPPP_(my_vload_module)(U32 flags, SV *name, SV *ver, va_list *args) { dTHR; dVAR; OP *veop, *imop; OP * const modname = newSVOP(OP_CONST, 0, name); /* 5.005 has a somewhat hacky force_normal that doesn't croak on SvREADONLY() if PL_compling is true. Current perls take care in ck_require() to correctly turn off SvREADONLY before calling force_normal_flags(). This seems a better fix than fudging PL_compling */ SvREADONLY_off(((SVOP*)modname)->op_sv); modname->op_private |= OPpCONST_BARE; if (ver) { veop = newSVOP(OP_CONST, 0, ver); } else veop = NULL; if (flags & PERL_LOADMOD_NOIMPORT) { imop = sawparens(newNULLLIST()); } else if (flags & PERL_LOADMOD_IMPORT_OPS) { imop = va_arg(*args, OP*); } else { SV *sv; imop = NULL; sv = va_arg(*args, SV*); while (sv) { imop = append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv)); sv = va_arg(*args, SV*); } } { const line_t ocopline = PL_copline; COP * const ocurcop = PL_curcop; const int oexpect = PL_expect; #if (PERL_BCDVERSION >= 0x5004000) utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(FALSE, 0), veop, modname, imop); #else utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(), modname, imop); #endif PL_expect = oexpect; PL_copline = ocopline; PL_curcop = ocurcop; } } #endif #endif #ifndef load_module #if defined(NEED_load_module) static void DPPP_(my_load_module)(U32 flags, SV *name, SV *ver, ...); static #else extern void DPPP_(my_load_module)(U32 flags, SV *name, SV *ver, ...); #endif #ifdef load_module # undef load_module #endif #define load_module DPPP_(my_load_module) #define Perl_load_module DPPP_(my_load_module) #if defined(NEED_load_module) || defined(NEED_load_module_GLOBAL) void DPPP_(my_load_module)(U32 flags, SV *name, SV *ver, ...) { va_list args; va_start(args, ver); vload_module(flags, name, ver, &args); va_end(args); } #endif #endif #ifndef newRV_inc # define newRV_inc(sv) newRV(sv) /* Replace */ #endif #ifndef newRV_noinc #if defined(NEED_newRV_noinc) static SV * DPPP_(my_newRV_noinc)(SV *sv); static #else extern SV * DPPP_(my_newRV_noinc)(SV *sv); #endif #ifdef newRV_noinc # undef newRV_noinc #endif #define newRV_noinc(a) DPPP_(my_newRV_noinc)(aTHX_ a) #define Perl_newRV_noinc DPPP_(my_newRV_noinc) #if defined(NEED_newRV_noinc) || defined(NEED_newRV_noinc_GLOBAL) SV * DPPP_(my_newRV_noinc)(SV *sv) { SV *rv = (SV *)newRV(sv); SvREFCNT_dec(sv); return rv; } #endif #endif /* Hint: newCONSTSUB * Returns a CV* as of perl-5.7.1. This return value is not supported * by Devel::PPPort. */ /* newCONSTSUB from IO.xs is in the core starting with 5.004_63 */ #if (PERL_BCDVERSION < 0x5004063) && (PERL_BCDVERSION != 0x5004005) #if defined(NEED_newCONSTSUB) static void DPPP_(my_newCONSTSUB)(HV *stash, const char *name, SV *sv); static #else extern void DPPP_(my_newCONSTSUB)(HV *stash, const char *name, SV *sv); #endif #ifdef newCONSTSUB # undef newCONSTSUB #endif #define newCONSTSUB(a,b,c) DPPP_(my_newCONSTSUB)(aTHX_ a,b,c) #define Perl_newCONSTSUB DPPP_(my_newCONSTSUB) #if defined(NEED_newCONSTSUB) || defined(NEED_newCONSTSUB_GLOBAL) /* This is just a trick to avoid a dependency of newCONSTSUB on PL_parser */ /* (There's no PL_parser in perl < 5.005, so this is completely safe) */ #define D_PPP_PL_copline PL_copline void DPPP_(my_newCONSTSUB)(HV *stash, const char *name, SV *sv) { U32 oldhints = PL_hints; HV *old_cop_stash = PL_curcop->cop_stash; HV *old_curstash = PL_curstash; line_t oldline = PL_curcop->cop_line; PL_curcop->cop_line = D_PPP_PL_copline; PL_hints &= ~HINT_BLOCK_SCOPE; if (stash) PL_curstash = PL_curcop->cop_stash = stash; newSUB( #if (PERL_BCDVERSION < 0x5003022) start_subparse(), #elif (PERL_BCDVERSION == 0x5003022) start_subparse(0), #else /* 5.003_23 onwards */ start_subparse(FALSE, 0), #endif newSVOP(OP_CONST, 0, newSVpv((char *) name, 0)), newSVOP(OP_CONST, 0, &PL_sv_no), /* SvPV(&PL_sv_no) == "" -- GMB */ newSTATEOP(0, Nullch, newSVOP(OP_CONST, 0, sv)) ); PL_hints = oldhints; PL_curcop->cop_stash = old_cop_stash; PL_curstash = old_curstash; PL_curcop->cop_line = oldline; } #endif #endif /* * Boilerplate macros for initializing and accessing interpreter-local * data from C. All statics in extensions should be reworked to use * this, if you want to make the extension thread-safe. See ext/re/re.xs * for an example of the use of these macros. * * Code that uses these macros is responsible for the following: * 1. #define MY_CXT_KEY to a unique string, e.g. "DynaLoader_guts" * 2. Declare a typedef named my_cxt_t that is a structure that contains * all the data that needs to be interpreter-local. * 3. Use the START_MY_CXT macro after the declaration of my_cxt_t. * 4. Use the MY_CXT_INIT macro such that it is called exactly once * (typically put in the BOOT: section). * 5. Use the members of the my_cxt_t structure everywhere as * MY_CXT.member. * 6. Use the dMY_CXT macro (a declaration) in all the functions that * access MY_CXT. */ #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || \ defined(PERL_CAPI) || defined(PERL_IMPLICIT_CONTEXT) #ifndef START_MY_CXT /* This must appear in all extensions that define a my_cxt_t structure, * right after the definition (i.e. at file scope). The non-threads * case below uses it to declare the data as static. */ #define START_MY_CXT #if (PERL_BCDVERSION < 0x5004068) /* Fetches the SV that keeps the per-interpreter data. */ #define dMY_CXT_SV \ SV *my_cxt_sv = get_sv(MY_CXT_KEY, FALSE) #else /* >= perl5.004_68 */ #define dMY_CXT_SV \ SV *my_cxt_sv = *hv_fetch(PL_modglobal, MY_CXT_KEY, \ sizeof(MY_CXT_KEY)-1, TRUE) #endif /* < perl5.004_68 */ /* This declaration should be used within all functions that use the * interpreter-local data. */ #define dMY_CXT \ dMY_CXT_SV; \ my_cxt_t *my_cxtp = INT2PTR(my_cxt_t*,SvUV(my_cxt_sv)) /* Creates and zeroes the per-interpreter data. * (We allocate my_cxtp in a Perl SV so that it will be released when * the interpreter goes away.) */ #define MY_CXT_INIT \ dMY_CXT_SV; \ /* newSV() allocates one more than needed */ \ my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1));\ Zero(my_cxtp, 1, my_cxt_t); \ sv_setuv(my_cxt_sv, PTR2UV(my_cxtp)) /* This macro must be used to access members of the my_cxt_t structure. * e.g. MYCXT.some_data */ #define MY_CXT (*my_cxtp) /* Judicious use of these macros can reduce the number of times dMY_CXT * is used. Use is similar to pTHX, aTHX etc. */ #define pMY_CXT my_cxt_t *my_cxtp #define pMY_CXT_ pMY_CXT, #define _pMY_CXT ,pMY_CXT #define aMY_CXT my_cxtp #define aMY_CXT_ aMY_CXT, #define _aMY_CXT ,aMY_CXT #endif /* START_MY_CXT */ #ifndef MY_CXT_CLONE /* Clones the per-interpreter data. */ #define MY_CXT_CLONE \ dMY_CXT_SV; \ my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1));\ Copy(INT2PTR(my_cxt_t*, SvUV(my_cxt_sv)), my_cxtp, 1, my_cxt_t);\ sv_setuv(my_cxt_sv, PTR2UV(my_cxtp)) #endif #else /* single interpreter */ #ifndef START_MY_CXT #define START_MY_CXT static my_cxt_t my_cxt; #define dMY_CXT_SV dNOOP #define dMY_CXT dNOOP #define MY_CXT_INIT NOOP #define MY_CXT my_cxt #define pMY_CXT void #define pMY_CXT_ #define _pMY_CXT #define aMY_CXT #define aMY_CXT_ #define _aMY_CXT #endif /* START_MY_CXT */ #ifndef MY_CXT_CLONE #define MY_CXT_CLONE NOOP #endif #endif #ifndef IVdf # if IVSIZE == LONGSIZE # define IVdf "ld" # define UVuf "lu" # define UVof "lo" # define UVxf "lx" # define UVXf "lX" # else # if IVSIZE == INTSIZE # define IVdf "d" # define UVuf "u" # define UVof "o" # define UVxf "x" # define UVXf "X" # endif # endif #endif #ifndef NVef # if defined(USE_LONG_DOUBLE) && defined(HAS_LONG_DOUBLE) && \ defined(PERL_PRIfldbl) && (PERL_BCDVERSION != 0x5006000) /* Not very likely, but let's try anyway. */ # define NVef PERL_PRIeldbl # define NVff PERL_PRIfldbl # define NVgf PERL_PRIgldbl # else # define NVef "e" # define NVff "f" # define NVgf "g" # endif #endif #ifndef SvREFCNT_inc # ifdef PERL_USE_GCC_BRACE_GROUPS # define SvREFCNT_inc(sv) \ ({ \ SV * const _sv = (SV*)(sv); \ if (_sv) \ (SvREFCNT(_sv))++; \ _sv; \ }) # else # define SvREFCNT_inc(sv) \ ((PL_Sv=(SV*)(sv)) ? (++(SvREFCNT(PL_Sv)),PL_Sv) : NULL) # endif #endif #ifndef SvREFCNT_inc_simple # ifdef PERL_USE_GCC_BRACE_GROUPS # define SvREFCNT_inc_simple(sv) \ ({ \ if (sv) \ (SvREFCNT(sv))++; \ (SV *)(sv); \ }) # else # define SvREFCNT_inc_simple(sv) \ ((sv) ? (SvREFCNT(sv)++,(SV*)(sv)) : NULL) # endif #endif #ifndef SvREFCNT_inc_NN # ifdef PERL_USE_GCC_BRACE_GROUPS # define SvREFCNT_inc_NN(sv) \ ({ \ SV * const _sv = (SV*)(sv); \ SvREFCNT(_sv)++; \ _sv; \ }) # else # define SvREFCNT_inc_NN(sv) \ (PL_Sv=(SV*)(sv),++(SvREFCNT(PL_Sv)),PL_Sv) # endif #endif #ifndef SvREFCNT_inc_void # ifdef PERL_USE_GCC_BRACE_GROUPS # define SvREFCNT_inc_void(sv) \ ({ \ SV * const _sv = (SV*)(sv); \ if (_sv) \ (void)(SvREFCNT(_sv)++); \ }) # else # define SvREFCNT_inc_void(sv) \ (void)((PL_Sv=(SV*)(sv)) ? ++(SvREFCNT(PL_Sv)) : 0) # endif #endif #ifndef SvREFCNT_inc_simple_void # define SvREFCNT_inc_simple_void(sv) STMT_START { if (sv) SvREFCNT(sv)++; } STMT_END #endif #ifndef SvREFCNT_inc_simple_NN # define SvREFCNT_inc_simple_NN(sv) (++SvREFCNT(sv), (SV*)(sv)) #endif #ifndef SvREFCNT_inc_void_NN # define SvREFCNT_inc_void_NN(sv) (void)(++SvREFCNT((SV*)(sv))) #endif #ifndef SvREFCNT_inc_simple_void_NN # define SvREFCNT_inc_simple_void_NN(sv) (void)(++SvREFCNT((SV*)(sv))) #endif #ifndef newSV_type #if defined(NEED_newSV_type) static SV* DPPP_(my_newSV_type)(pTHX_ svtype const t); static #else extern SV* DPPP_(my_newSV_type)(pTHX_ svtype const t); #endif #ifdef newSV_type # undef newSV_type #endif #define newSV_type(a) DPPP_(my_newSV_type)(aTHX_ a) #define Perl_newSV_type DPPP_(my_newSV_type) #if defined(NEED_newSV_type) || defined(NEED_newSV_type_GLOBAL) SV* DPPP_(my_newSV_type)(pTHX_ svtype const t) { SV* const sv = newSV(0); sv_upgrade(sv, t); return sv; } #endif #endif #if (PERL_BCDVERSION < 0x5006000) # define D_PPP_CONSTPV_ARG(x) ((char *) (x)) #else # define D_PPP_CONSTPV_ARG(x) (x) #endif #ifndef newSVpvn # define newSVpvn(data,len) ((data) \ ? ((len) ? newSVpv((data), (len)) : newSVpv("", 0)) \ : newSV(0)) #endif #ifndef newSVpvn_utf8 # define newSVpvn_utf8(s, len, u) newSVpvn_flags((s), (len), (u) ? SVf_UTF8 : 0) #endif #ifndef SVf_UTF8 # define SVf_UTF8 0 #endif #ifndef newSVpvn_flags #if defined(NEED_newSVpvn_flags) static SV * DPPP_(my_newSVpvn_flags)(pTHX_ const char *s, STRLEN len, U32 flags); static #else extern SV * DPPP_(my_newSVpvn_flags)(pTHX_ const char *s, STRLEN len, U32 flags); #endif #ifdef newSVpvn_flags # undef newSVpvn_flags #endif #define newSVpvn_flags(a,b,c) DPPP_(my_newSVpvn_flags)(aTHX_ a,b,c) #define Perl_newSVpvn_flags DPPP_(my_newSVpvn_flags) #if defined(NEED_newSVpvn_flags) || defined(NEED_newSVpvn_flags_GLOBAL) SV * DPPP_(my_newSVpvn_flags)(pTHX_ const char *s, STRLEN len, U32 flags) { SV *sv = newSVpvn(D_PPP_CONSTPV_ARG(s), len); SvFLAGS(sv) |= (flags & SVf_UTF8); return (flags & SVs_TEMP) ? sv_2mortal(sv) : sv; } #endif #endif /* Backwards compatibility stuff... :-( */ #if !defined(NEED_sv_2pv_flags) && defined(NEED_sv_2pv_nolen) # define NEED_sv_2pv_flags #endif #if !defined(NEED_sv_2pv_flags_GLOBAL) && defined(NEED_sv_2pv_nolen_GLOBAL) # define NEED_sv_2pv_flags_GLOBAL #endif /* Hint: sv_2pv_nolen * Use the SvPV_nolen() or SvPV_nolen_const() macros instead of sv_2pv_nolen(). */ #ifndef sv_2pv_nolen # define sv_2pv_nolen(sv) SvPV_nolen(sv) #endif #ifdef SvPVbyte /* Hint: SvPVbyte * Does not work in perl-5.6.1, ppport.h implements a version * borrowed from perl-5.7.3. */ #if (PERL_BCDVERSION < 0x5007000) #if defined(NEED_sv_2pvbyte) static char * DPPP_(my_sv_2pvbyte)(pTHX_ SV *sv, STRLEN *lp); static #else extern char * DPPP_(my_sv_2pvbyte)(pTHX_ SV *sv, STRLEN *lp); #endif #ifdef sv_2pvbyte # undef sv_2pvbyte #endif #define sv_2pvbyte(a,b) DPPP_(my_sv_2pvbyte)(aTHX_ a,b) #define Perl_sv_2pvbyte DPPP_(my_sv_2pvbyte) #if defined(NEED_sv_2pvbyte) || defined(NEED_sv_2pvbyte_GLOBAL) char * DPPP_(my_sv_2pvbyte)(pTHX_ SV *sv, STRLEN *lp) { sv_utf8_downgrade(sv,0); return SvPV(sv,*lp); } #endif /* Hint: sv_2pvbyte * Use the SvPVbyte() macro instead of sv_2pvbyte(). */ #undef SvPVbyte #define SvPVbyte(sv, lp) \ ((SvFLAGS(sv) & (SVf_POK|SVf_UTF8)) == (SVf_POK) \ ? ((lp = SvCUR(sv)), SvPVX(sv)) : sv_2pvbyte(sv, &lp)) #endif #else # define SvPVbyte SvPV # define sv_2pvbyte sv_2pv #endif #ifndef sv_2pvbyte_nolen # define sv_2pvbyte_nolen(sv) sv_2pv_nolen(sv) #endif /* Hint: sv_pvn * Always use the SvPV() macro instead of sv_pvn(). */ /* Hint: sv_pvn_force * Always use the SvPV_force() macro instead of sv_pvn_force(). */ /* If these are undefined, they're not handled by the core anyway */ #ifndef SV_IMMEDIATE_UNREF # define SV_IMMEDIATE_UNREF 0 #endif #ifndef SV_GMAGIC # define SV_GMAGIC 0 #endif #ifndef SV_COW_DROP_PV # define SV_COW_DROP_PV 0 #endif #ifndef SV_UTF8_NO_ENCODING # define SV_UTF8_NO_ENCODING 0 #endif #ifndef SV_NOSTEAL # define SV_NOSTEAL 0 #endif #ifndef SV_CONST_RETURN # define SV_CONST_RETURN 0 #endif #ifndef SV_MUTABLE_RETURN # define SV_MUTABLE_RETURN 0 #endif #ifndef SV_SMAGIC # define SV_SMAGIC 0 #endif #ifndef SV_HAS_TRAILING_NUL # define SV_HAS_TRAILING_NUL 0 #endif #ifndef SV_COW_SHARED_HASH_KEYS # define SV_COW_SHARED_HASH_KEYS 0 #endif #if (PERL_BCDVERSION < 0x5007002) #if defined(NEED_sv_2pv_flags) static char * DPPP_(my_sv_2pv_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags); static #else extern char * DPPP_(my_sv_2pv_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags); #endif #ifdef sv_2pv_flags # undef sv_2pv_flags #endif #define sv_2pv_flags(a,b,c) DPPP_(my_sv_2pv_flags)(aTHX_ a,b,c) #define Perl_sv_2pv_flags DPPP_(my_sv_2pv_flags) #if defined(NEED_sv_2pv_flags) || defined(NEED_sv_2pv_flags_GLOBAL) char * DPPP_(my_sv_2pv_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags) { STRLEN n_a = (STRLEN) flags; return sv_2pv(sv, lp ? lp : &n_a); } #endif #if defined(NEED_sv_pvn_force_flags) static char * DPPP_(my_sv_pvn_force_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags); static #else extern char * DPPP_(my_sv_pvn_force_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags); #endif #ifdef sv_pvn_force_flags # undef sv_pvn_force_flags #endif #define sv_pvn_force_flags(a,b,c) DPPP_(my_sv_pvn_force_flags)(aTHX_ a,b,c) #define Perl_sv_pvn_force_flags DPPP_(my_sv_pvn_force_flags) #if defined(NEED_sv_pvn_force_flags) || defined(NEED_sv_pvn_force_flags_GLOBAL) char * DPPP_(my_sv_pvn_force_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags) { STRLEN n_a = (STRLEN) flags; return sv_pvn_force(sv, lp ? lp : &n_a); } #endif #endif #if (PERL_BCDVERSION < 0x5008008) || ( (PERL_BCDVERSION >= 0x5009000) && (PERL_BCDVERSION < 0x5009003) ) # define DPPP_SVPV_NOLEN_LP_ARG &PL_na #else # define DPPP_SVPV_NOLEN_LP_ARG 0 #endif #ifndef SvPV_const # define SvPV_const(sv, lp) SvPV_flags_const(sv, lp, SV_GMAGIC) #endif #ifndef SvPV_mutable # define SvPV_mutable(sv, lp) SvPV_flags_mutable(sv, lp, SV_GMAGIC) #endif #ifndef SvPV_flags # define SvPV_flags(sv, lp, flags) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? ((lp = SvCUR(sv)), SvPVX(sv)) : sv_2pv_flags(sv, &lp, flags)) #endif #ifndef SvPV_flags_const # define SvPV_flags_const(sv, lp, flags) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? ((lp = SvCUR(sv)), SvPVX_const(sv)) : \ (const char*) sv_2pv_flags(sv, &lp, flags|SV_CONST_RETURN)) #endif #ifndef SvPV_flags_const_nolen # define SvPV_flags_const_nolen(sv, flags) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? SvPVX_const(sv) : \ (const char*) sv_2pv_flags(sv, DPPP_SVPV_NOLEN_LP_ARG, flags|SV_CONST_RETURN)) #endif #ifndef SvPV_flags_mutable # define SvPV_flags_mutable(sv, lp, flags) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? ((lp = SvCUR(sv)), SvPVX_mutable(sv)) : \ sv_2pv_flags(sv, &lp, flags|SV_MUTABLE_RETURN)) #endif #ifndef SvPV_force # define SvPV_force(sv, lp) SvPV_force_flags(sv, lp, SV_GMAGIC) #endif #ifndef SvPV_force_nolen # define SvPV_force_nolen(sv) SvPV_force_flags_nolen(sv, SV_GMAGIC) #endif #ifndef SvPV_force_mutable # define SvPV_force_mutable(sv, lp) SvPV_force_flags_mutable(sv, lp, SV_GMAGIC) #endif #ifndef SvPV_force_nomg # define SvPV_force_nomg(sv, lp) SvPV_force_flags(sv, lp, 0) #endif #ifndef SvPV_force_nomg_nolen # define SvPV_force_nomg_nolen(sv) SvPV_force_flags_nolen(sv, 0) #endif #ifndef SvPV_force_flags # define SvPV_force_flags(sv, lp, flags) \ ((SvFLAGS(sv) & (SVf_POK|SVf_THINKFIRST)) == SVf_POK \ ? ((lp = SvCUR(sv)), SvPVX(sv)) : sv_pvn_force_flags(sv, &lp, flags)) #endif #ifndef SvPV_force_flags_nolen # define SvPV_force_flags_nolen(sv, flags) \ ((SvFLAGS(sv) & (SVf_POK|SVf_THINKFIRST)) == SVf_POK \ ? SvPVX(sv) : sv_pvn_force_flags(sv, DPPP_SVPV_NOLEN_LP_ARG, flags)) #endif #ifndef SvPV_force_flags_mutable # define SvPV_force_flags_mutable(sv, lp, flags) \ ((SvFLAGS(sv) & (SVf_POK|SVf_THINKFIRST)) == SVf_POK \ ? ((lp = SvCUR(sv)), SvPVX_mutable(sv)) \ : sv_pvn_force_flags(sv, &lp, flags|SV_MUTABLE_RETURN)) #endif #ifndef SvPV_nolen # define SvPV_nolen(sv) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? SvPVX(sv) : sv_2pv_flags(sv, DPPP_SVPV_NOLEN_LP_ARG, SV_GMAGIC)) #endif #ifndef SvPV_nolen_const # define SvPV_nolen_const(sv) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? SvPVX_const(sv) : sv_2pv_flags(sv, DPPP_SVPV_NOLEN_LP_ARG, SV_GMAGIC|SV_CONST_RETURN)) #endif #ifndef SvPV_nomg # define SvPV_nomg(sv, lp) SvPV_flags(sv, lp, 0) #endif #ifndef SvPV_nomg_const # define SvPV_nomg_const(sv, lp) SvPV_flags_const(sv, lp, 0) #endif #ifndef SvPV_nomg_const_nolen # define SvPV_nomg_const_nolen(sv) SvPV_flags_const_nolen(sv, 0) #endif #ifndef SvPV_renew # define SvPV_renew(sv,n) STMT_START { SvLEN_set(sv, n); \ SvPV_set((sv), (char *) saferealloc( \ (Malloc_t)SvPVX(sv), (MEM_SIZE)((n)))); \ } STMT_END #endif #ifndef SvMAGIC_set # define SvMAGIC_set(sv, val) \ STMT_START { assert(SvTYPE(sv) >= SVt_PVMG); \ (((XPVMG*) SvANY(sv))->xmg_magic = (val)); } STMT_END #endif #if (PERL_BCDVERSION < 0x5009003) #ifndef SvPVX_const # define SvPVX_const(sv) ((const char*) (0 + SvPVX(sv))) #endif #ifndef SvPVX_mutable # define SvPVX_mutable(sv) (0 + SvPVX(sv)) #endif #ifndef SvRV_set # define SvRV_set(sv, val) \ STMT_START { assert(SvTYPE(sv) >= SVt_RV); \ (((XRV*) SvANY(sv))->xrv_rv = (val)); } STMT_END #endif #else #ifndef SvPVX_const # define SvPVX_const(sv) ((const char*)((sv)->sv_u.svu_pv)) #endif #ifndef SvPVX_mutable # define SvPVX_mutable(sv) ((sv)->sv_u.svu_pv) #endif #ifndef SvRV_set # define SvRV_set(sv, val) \ STMT_START { assert(SvTYPE(sv) >= SVt_RV); \ ((sv)->sv_u.svu_rv = (val)); } STMT_END #endif #endif #ifndef SvSTASH_set # define SvSTASH_set(sv, val) \ STMT_START { assert(SvTYPE(sv) >= SVt_PVMG); \ (((XPVMG*) SvANY(sv))->xmg_stash = (val)); } STMT_END #endif #if (PERL_BCDVERSION < 0x5004000) #ifndef SvUV_set # define SvUV_set(sv, val) \ STMT_START { assert(SvTYPE(sv) == SVt_IV || SvTYPE(sv) >= SVt_PVIV); \ (((XPVIV*) SvANY(sv))->xiv_iv = (IV) (val)); } STMT_END #endif #else #ifndef SvUV_set # define SvUV_set(sv, val) \ STMT_START { assert(SvTYPE(sv) == SVt_IV || SvTYPE(sv) >= SVt_PVIV); \ (((XPVUV*) SvANY(sv))->xuv_uv = (val)); } STMT_END #endif #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(vnewSVpvf) #if defined(NEED_vnewSVpvf) static SV * DPPP_(my_vnewSVpvf)(pTHX_ const char *pat, va_list *args); static #else extern SV * DPPP_(my_vnewSVpvf)(pTHX_ const char *pat, va_list *args); #endif #ifdef vnewSVpvf # undef vnewSVpvf #endif #define vnewSVpvf(a,b) DPPP_(my_vnewSVpvf)(aTHX_ a,b) #define Perl_vnewSVpvf DPPP_(my_vnewSVpvf) #if defined(NEED_vnewSVpvf) || defined(NEED_vnewSVpvf_GLOBAL) SV * DPPP_(my_vnewSVpvf)(pTHX_ const char *pat, va_list *args) { register SV *sv = newSV(0); sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*)); return sv; } #endif #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_vcatpvf) # define sv_vcatpvf(sv, pat, args) sv_vcatpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*)) #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_vsetpvf) # define sv_vsetpvf(sv, pat, args) sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*)) #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_catpvf_mg) #if defined(NEED_sv_catpvf_mg) static void DPPP_(my_sv_catpvf_mg)(pTHX_ SV *sv, const char *pat, ...); static #else extern void DPPP_(my_sv_catpvf_mg)(pTHX_ SV *sv, const char *pat, ...); #endif #define Perl_sv_catpvf_mg DPPP_(my_sv_catpvf_mg) #if defined(NEED_sv_catpvf_mg) || defined(NEED_sv_catpvf_mg_GLOBAL) void DPPP_(my_sv_catpvf_mg)(pTHX_ SV *sv, const char *pat, ...) { va_list args; va_start(args, pat); sv_vcatpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*)); SvSETMAGIC(sv); va_end(args); } #endif #endif #ifdef PERL_IMPLICIT_CONTEXT #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_catpvf_mg_nocontext) #if defined(NEED_sv_catpvf_mg_nocontext) static void DPPP_(my_sv_catpvf_mg_nocontext)(SV *sv, const char *pat, ...); static #else extern void DPPP_(my_sv_catpvf_mg_nocontext)(SV *sv, const char *pat, ...); #endif #define sv_catpvf_mg_nocontext DPPP_(my_sv_catpvf_mg_nocontext) #define Perl_sv_catpvf_mg_nocontext DPPP_(my_sv_catpvf_mg_nocontext) #if defined(NEED_sv_catpvf_mg_nocontext) || defined(NEED_sv_catpvf_mg_nocontext_GLOBAL) void DPPP_(my_sv_catpvf_mg_nocontext)(SV *sv, const char *pat, ...) { dTHX; va_list args; va_start(args, pat); sv_vcatpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*)); SvSETMAGIC(sv); va_end(args); } #endif #endif #endif /* sv_catpvf_mg depends on sv_catpvf_mg_nocontext */ #ifndef sv_catpvf_mg # ifdef PERL_IMPLICIT_CONTEXT # define sv_catpvf_mg Perl_sv_catpvf_mg_nocontext # else # define sv_catpvf_mg Perl_sv_catpvf_mg # endif #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_vcatpvf_mg) # define sv_vcatpvf_mg(sv, pat, args) \ STMT_START { \ sv_vcatpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*)); \ SvSETMAGIC(sv); \ } STMT_END #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_setpvf_mg) #if defined(NEED_sv_setpvf_mg) static void DPPP_(my_sv_setpvf_mg)(pTHX_ SV *sv, const char *pat, ...); static #else extern void DPPP_(my_sv_setpvf_mg)(pTHX_ SV *sv, const char *pat, ...); #endif #define Perl_sv_setpvf_mg DPPP_(my_sv_setpvf_mg) #if defined(NEED_sv_setpvf_mg) || defined(NEED_sv_setpvf_mg_GLOBAL) void DPPP_(my_sv_setpvf_mg)(pTHX_ SV *sv, const char *pat, ...) { va_list args; va_start(args, pat); sv_vsetpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*)); SvSETMAGIC(sv); va_end(args); } #endif #endif #ifdef PERL_IMPLICIT_CONTEXT #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_setpvf_mg_nocontext) #if defined(NEED_sv_setpvf_mg_nocontext) static void DPPP_(my_sv_setpvf_mg_nocontext)(SV *sv, const char *pat, ...); static #else extern void DPPP_(my_sv_setpvf_mg_nocontext)(SV *sv, const char *pat, ...); #endif #define sv_setpvf_mg_nocontext DPPP_(my_sv_setpvf_mg_nocontext) #define Perl_sv_setpvf_mg_nocontext DPPP_(my_sv_setpvf_mg_nocontext) #if defined(NEED_sv_setpvf_mg_nocontext) || defined(NEED_sv_setpvf_mg_nocontext_GLOBAL) void DPPP_(my_sv_setpvf_mg_nocontext)(SV *sv, const char *pat, ...) { dTHX; va_list args; va_start(args, pat); sv_vsetpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*)); SvSETMAGIC(sv); va_end(args); } #endif #endif #endif /* sv_setpvf_mg depends on sv_setpvf_mg_nocontext */ #ifndef sv_setpvf_mg # ifdef PERL_IMPLICIT_CONTEXT # define sv_setpvf_mg Perl_sv_setpvf_mg_nocontext # else # define sv_setpvf_mg Perl_sv_setpvf_mg # endif #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_vsetpvf_mg) # define sv_vsetpvf_mg(sv, pat, args) \ STMT_START { \ sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*)); \ SvSETMAGIC(sv); \ } STMT_END #endif /* Hint: newSVpvn_share * The SVs created by this function only mimic the behaviour of * shared PVs without really being shared. Only use if you know * what you're doing. */ #ifndef newSVpvn_share #if defined(NEED_newSVpvn_share) static SV * DPPP_(my_newSVpvn_share)(pTHX_ const char *src, I32 len, U32 hash); static #else extern SV * DPPP_(my_newSVpvn_share)(pTHX_ const char *src, I32 len, U32 hash); #endif #ifdef newSVpvn_share # undef newSVpvn_share #endif #define newSVpvn_share(a,b,c) DPPP_(my_newSVpvn_share)(aTHX_ a,b,c) #define Perl_newSVpvn_share DPPP_(my_newSVpvn_share) #if defined(NEED_newSVpvn_share) || defined(NEED_newSVpvn_share_GLOBAL) SV * DPPP_(my_newSVpvn_share)(pTHX_ const char *src, I32 len, U32 hash) { SV *sv; if (len < 0) len = -len; if (!hash) PERL_HASH(hash, (char*) src, len); sv = newSVpvn((char *) src, len); sv_upgrade(sv, SVt_PVIV); SvIVX(sv) = hash; SvREADONLY_on(sv); SvPOK_on(sv); return sv; } #endif #endif #ifndef SvSHARED_HASH # define SvSHARED_HASH(sv) (0 + SvUVX(sv)) #endif #ifndef HvNAME_get # define HvNAME_get(hv) HvNAME(hv) #endif #ifndef HvNAMELEN_get # define HvNAMELEN_get(hv) (HvNAME_get(hv) ? (I32)strlen(HvNAME_get(hv)) : 0) #endif #ifndef GvSVn # define GvSVn(gv) GvSV(gv) #endif #ifndef isGV_with_GP # define isGV_with_GP(gv) isGV(gv) #endif #ifndef gv_fetchpvn_flags # define gv_fetchpvn_flags(name, len, flags, svt) gv_fetchpv(name, flags, svt) #endif #ifndef gv_fetchsv # define gv_fetchsv(name, flags, svt) gv_fetchpv(SvPV_nolen_const(name), flags, svt) #endif #ifndef get_cvn_flags # define get_cvn_flags(name, namelen, flags) get_cv(name, flags) #endif #ifndef WARN_ALL # define WARN_ALL 0 #endif #ifndef WARN_CLOSURE # define WARN_CLOSURE 1 #endif #ifndef WARN_DEPRECATED # define WARN_DEPRECATED 2 #endif #ifndef WARN_EXITING # define WARN_EXITING 3 #endif #ifndef WARN_GLOB # define WARN_GLOB 4 #endif #ifndef WARN_IO # define WARN_IO 5 #endif #ifndef WARN_CLOSED # define WARN_CLOSED 6 #endif #ifndef WARN_EXEC # define WARN_EXEC 7 #endif #ifndef WARN_LAYER # define WARN_LAYER 8 #endif #ifndef WARN_NEWLINE # define WARN_NEWLINE 9 #endif #ifndef WARN_PIPE # define WARN_PIPE 10 #endif #ifndef WARN_UNOPENED # define WARN_UNOPENED 11 #endif #ifndef WARN_MISC # define WARN_MISC 12 #endif #ifndef WARN_NUMERIC # define WARN_NUMERIC 13 #endif #ifndef WARN_ONCE # define WARN_ONCE 14 #endif #ifndef WARN_OVERFLOW # define WARN_OVERFLOW 15 #endif #ifndef WARN_PACK # define WARN_PACK 16 #endif #ifndef WARN_PORTABLE # define WARN_PORTABLE 17 #endif #ifndef WARN_RECURSION # define WARN_RECURSION 18 #endif #ifndef WARN_REDEFINE # define WARN_REDEFINE 19 #endif #ifndef WARN_REGEXP # define WARN_REGEXP 20 #endif #ifndef WARN_SEVERE # define WARN_SEVERE 21 #endif #ifndef WARN_DEBUGGING # define WARN_DEBUGGING 22 #endif #ifndef WARN_INPLACE # define WARN_INPLACE 23 #endif #ifndef WARN_INTERNAL # define WARN_INTERNAL 24 #endif #ifndef WARN_MALLOC # define WARN_MALLOC 25 #endif #ifndef WARN_SIGNAL # define WARN_SIGNAL 26 #endif #ifndef WARN_SUBSTR # define WARN_SUBSTR 27 #endif #ifndef WARN_SYNTAX # define WARN_SYNTAX 28 #endif #ifndef WARN_AMBIGUOUS # define WARN_AMBIGUOUS 29 #endif #ifndef WARN_BAREWORD # define WARN_BAREWORD 30 #endif #ifndef WARN_DIGIT # define WARN_DIGIT 31 #endif #ifndef WARN_PARENTHESIS # define WARN_PARENTHESIS 32 #endif #ifndef WARN_PRECEDENCE # define WARN_PRECEDENCE 33 #endif #ifndef WARN_PRINTF # define WARN_PRINTF 34 #endif #ifndef WARN_PROTOTYPE # define WARN_PROTOTYPE 35 #endif #ifndef WARN_QW # define WARN_QW 36 #endif #ifndef WARN_RESERVED # define WARN_RESERVED 37 #endif #ifndef WARN_SEMICOLON # define WARN_SEMICOLON 38 #endif #ifndef WARN_TAINT # define WARN_TAINT 39 #endif #ifndef WARN_THREADS # define WARN_THREADS 40 #endif #ifndef WARN_UNINITIALIZED # define WARN_UNINITIALIZED 41 #endif #ifndef WARN_UNPACK # define WARN_UNPACK 42 #endif #ifndef WARN_UNTIE # define WARN_UNTIE 43 #endif #ifndef WARN_UTF8 # define WARN_UTF8 44 #endif #ifndef WARN_VOID # define WARN_VOID 45 #endif #ifndef WARN_ASSERTIONS # define WARN_ASSERTIONS 46 #endif #ifndef packWARN # define packWARN(a) (a) #endif #ifndef ckWARN # ifdef G_WARN_ON # define ckWARN(a) (PL_dowarn & G_WARN_ON) # else # define ckWARN(a) PL_dowarn # endif #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(warner) #if defined(NEED_warner) static void DPPP_(my_warner)(U32 err, const char *pat, ...); static #else extern void DPPP_(my_warner)(U32 err, const char *pat, ...); #endif #define Perl_warner DPPP_(my_warner) #if defined(NEED_warner) || defined(NEED_warner_GLOBAL) void DPPP_(my_warner)(U32 err, const char *pat, ...) { SV *sv; va_list args; PERL_UNUSED_ARG(err); va_start(args, pat); sv = vnewSVpvf(pat, &args); va_end(args); sv_2mortal(sv); warn("%s", SvPV_nolen(sv)); } #define warner Perl_warner #define Perl_warner_nocontext Perl_warner #endif #endif /* concatenating with "" ensures that only literal strings are accepted as argument * note that STR_WITH_LEN() can't be used as argument to macros or functions that * under some configurations might be macros */ #ifndef STR_WITH_LEN # define STR_WITH_LEN(s) (s ""), (sizeof(s)-1) #endif #ifndef newSVpvs # define newSVpvs(str) newSVpvn(str "", sizeof(str) - 1) #endif #ifndef newSVpvs_flags # define newSVpvs_flags(str, flags) newSVpvn_flags(str "", sizeof(str) - 1, flags) #endif #ifndef newSVpvs_share # define newSVpvs_share(str) newSVpvn_share(str "", sizeof(str) - 1, 0) #endif #ifndef sv_catpvs # define sv_catpvs(sv, str) sv_catpvn(sv, str "", sizeof(str) - 1) #endif #ifndef sv_setpvs # define sv_setpvs(sv, str) sv_setpvn(sv, str "", sizeof(str) - 1) #endif #ifndef hv_fetchs # define hv_fetchs(hv, key, lval) hv_fetch(hv, key "", sizeof(key) - 1, lval) #endif #ifndef hv_stores # define hv_stores(hv, key, val) hv_store(hv, key "", sizeof(key) - 1, val, 0) #endif #ifndef gv_fetchpvs # define gv_fetchpvs(name, flags, svt) gv_fetchpvn_flags(name "", sizeof(name) - 1, flags, svt) #endif #ifndef gv_stashpvs # define gv_stashpvs(name, flags) gv_stashpvn(name "", sizeof(name) - 1, flags) #endif #ifndef get_cvs # define get_cvs(name, flags) get_cvn_flags(name "", sizeof(name)-1, flags) #endif #ifndef SvGETMAGIC # define SvGETMAGIC(x) STMT_START { if (SvGMAGICAL(x)) mg_get(x); } STMT_END #endif #ifndef PERL_MAGIC_sv # define PERL_MAGIC_sv '\0' #endif #ifndef PERL_MAGIC_overload # define PERL_MAGIC_overload 'A' #endif #ifndef PERL_MAGIC_overload_elem # define PERL_MAGIC_overload_elem 'a' #endif #ifndef PERL_MAGIC_overload_table # define PERL_MAGIC_overload_table 'c' #endif #ifndef PERL_MAGIC_bm # define PERL_MAGIC_bm 'B' #endif #ifndef PERL_MAGIC_regdata # define PERL_MAGIC_regdata 'D' #endif #ifndef PERL_MAGIC_regdatum # define PERL_MAGIC_regdatum 'd' #endif #ifndef PERL_MAGIC_env # define PERL_MAGIC_env 'E' #endif #ifndef PERL_MAGIC_envelem # define PERL_MAGIC_envelem 'e' #endif #ifndef PERL_MAGIC_fm # define PERL_MAGIC_fm 'f' #endif #ifndef PERL_MAGIC_regex_global # define PERL_MAGIC_regex_global 'g' #endif #ifndef PERL_MAGIC_isa # define PERL_MAGIC_isa 'I' #endif #ifndef PERL_MAGIC_isaelem # define PERL_MAGIC_isaelem 'i' #endif #ifndef PERL_MAGIC_nkeys # define PERL_MAGIC_nkeys 'k' #endif #ifndef PERL_MAGIC_dbfile # define PERL_MAGIC_dbfile 'L' #endif #ifndef PERL_MAGIC_dbline # define PERL_MAGIC_dbline 'l' #endif #ifndef PERL_MAGIC_mutex # define PERL_MAGIC_mutex 'm' #endif #ifndef PERL_MAGIC_shared # define PERL_MAGIC_shared 'N' #endif #ifndef PERL_MAGIC_shared_scalar # define PERL_MAGIC_shared_scalar 'n' #endif #ifndef PERL_MAGIC_collxfrm # define PERL_MAGIC_collxfrm 'o' #endif #ifndef PERL_MAGIC_tied # define PERL_MAGIC_tied 'P' #endif #ifndef PERL_MAGIC_tiedelem # define PERL_MAGIC_tiedelem 'p' #endif #ifndef PERL_MAGIC_tiedscalar # define PERL_MAGIC_tiedscalar 'q' #endif #ifndef PERL_MAGIC_qr # define PERL_MAGIC_qr 'r' #endif #ifndef PERL_MAGIC_sig # define PERL_MAGIC_sig 'S' #endif #ifndef PERL_MAGIC_sigelem # define PERL_MAGIC_sigelem 's' #endif #ifndef PERL_MAGIC_taint # define PERL_MAGIC_taint 't' #endif #ifndef PERL_MAGIC_uvar # define PERL_MAGIC_uvar 'U' #endif #ifndef PERL_MAGIC_uvar_elem # define PERL_MAGIC_uvar_elem 'u' #endif #ifndef PERL_MAGIC_vstring # define PERL_MAGIC_vstring 'V' #endif #ifndef PERL_MAGIC_vec # define PERL_MAGIC_vec 'v' #endif #ifndef PERL_MAGIC_utf8 # define PERL_MAGIC_utf8 'w' #endif #ifndef PERL_MAGIC_substr # define PERL_MAGIC_substr 'x' #endif #ifndef PERL_MAGIC_defelem # define PERL_MAGIC_defelem 'y' #endif #ifndef PERL_MAGIC_glob # define PERL_MAGIC_glob '*' #endif #ifndef PERL_MAGIC_arylen # define PERL_MAGIC_arylen '#' #endif #ifndef PERL_MAGIC_pos # define PERL_MAGIC_pos '.' #endif #ifndef PERL_MAGIC_backref # define PERL_MAGIC_backref '<' #endif #ifndef PERL_MAGIC_ext # define PERL_MAGIC_ext '~' #endif /* That's the best we can do... */ #ifndef sv_catpvn_nomg # define sv_catpvn_nomg sv_catpvn #endif #ifndef sv_catsv_nomg # define sv_catsv_nomg sv_catsv #endif #ifndef sv_setsv_nomg # define sv_setsv_nomg sv_setsv #endif #ifndef sv_pvn_nomg # define sv_pvn_nomg sv_pvn #endif #ifndef SvIV_nomg # define SvIV_nomg SvIV #endif #ifndef SvUV_nomg # define SvUV_nomg SvUV #endif #ifndef sv_catpv_mg # define sv_catpv_mg(sv, ptr) \ STMT_START { \ SV *TeMpSv = sv; \ sv_catpv(TeMpSv,ptr); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_catpvn_mg # define sv_catpvn_mg(sv, ptr, len) \ STMT_START { \ SV *TeMpSv = sv; \ sv_catpvn(TeMpSv,ptr,len); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_catsv_mg # define sv_catsv_mg(dsv, ssv) \ STMT_START { \ SV *TeMpSv = dsv; \ sv_catsv(TeMpSv,ssv); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setiv_mg # define sv_setiv_mg(sv, i) \ STMT_START { \ SV *TeMpSv = sv; \ sv_setiv(TeMpSv,i); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setnv_mg # define sv_setnv_mg(sv, num) \ STMT_START { \ SV *TeMpSv = sv; \ sv_setnv(TeMpSv,num); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setpv_mg # define sv_setpv_mg(sv, ptr) \ STMT_START { \ SV *TeMpSv = sv; \ sv_setpv(TeMpSv,ptr); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setpvn_mg # define sv_setpvn_mg(sv, ptr, len) \ STMT_START { \ SV *TeMpSv = sv; \ sv_setpvn(TeMpSv,ptr,len); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setsv_mg # define sv_setsv_mg(dsv, ssv) \ STMT_START { \ SV *TeMpSv = dsv; \ sv_setsv(TeMpSv,ssv); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setuv_mg # define sv_setuv_mg(sv, i) \ STMT_START { \ SV *TeMpSv = sv; \ sv_setuv(TeMpSv,i); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_usepvn_mg # define sv_usepvn_mg(sv, ptr, len) \ STMT_START { \ SV *TeMpSv = sv; \ sv_usepvn(TeMpSv,ptr,len); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef SvVSTRING_mg # define SvVSTRING_mg(sv) (SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_vstring) : NULL) #endif /* Hint: sv_magic_portable * This is a compatibility function that is only available with * Devel::PPPort. It is NOT in the perl core. * Its purpose is to mimic the 5.8.0 behaviour of sv_magic() when * it is being passed a name pointer with namlen == 0. In that * case, perl 5.8.0 and later store the pointer, not a copy of it. * The compatibility can be provided back to perl 5.004. With * earlier versions, the code will not compile. */ #if (PERL_BCDVERSION < 0x5004000) /* code that uses sv_magic_portable will not compile */ #elif (PERL_BCDVERSION < 0x5008000) # define sv_magic_portable(sv, obj, how, name, namlen) \ STMT_START { \ SV *SvMp_sv = (sv); \ char *SvMp_name = (char *) (name); \ I32 SvMp_namlen = (namlen); \ if (SvMp_name && SvMp_namlen == 0) \ { \ MAGIC *mg; \ sv_magic(SvMp_sv, obj, how, 0, 0); \ mg = SvMAGIC(SvMp_sv); \ mg->mg_len = -42; /* XXX: this is the tricky part */ \ mg->mg_ptr = SvMp_name; \ } \ else \ { \ sv_magic(SvMp_sv, obj, how, SvMp_name, SvMp_namlen); \ } \ } STMT_END #else # define sv_magic_portable(a, b, c, d, e) sv_magic(a, b, c, d, e) #endif #ifdef USE_ITHREADS #ifndef CopFILE # define CopFILE(c) ((c)->cop_file) #endif #ifndef CopFILEGV # define CopFILEGV(c) (CopFILE(c) ? gv_fetchfile(CopFILE(c)) : Nullgv) #endif #ifndef CopFILE_set # define CopFILE_set(c,pv) ((c)->cop_file = savepv(pv)) #endif #ifndef CopFILESV # define CopFILESV(c) (CopFILE(c) ? GvSV(gv_fetchfile(CopFILE(c))) : Nullsv) #endif #ifndef CopFILEAV # define CopFILEAV(c) (CopFILE(c) ? GvAV(gv_fetchfile(CopFILE(c))) : Nullav) #endif #ifndef CopSTASHPV # define CopSTASHPV(c) ((c)->cop_stashpv) #endif #ifndef CopSTASHPV_set # define CopSTASHPV_set(c,pv) ((c)->cop_stashpv = ((pv) ? savepv(pv) : Nullch)) #endif #ifndef CopSTASH # define CopSTASH(c) (CopSTASHPV(c) ? gv_stashpv(CopSTASHPV(c),GV_ADD) : Nullhv) #endif #ifndef CopSTASH_set # define CopSTASH_set(c,hv) CopSTASHPV_set(c, (hv) ? HvNAME(hv) : Nullch) #endif #ifndef CopSTASH_eq # define CopSTASH_eq(c,hv) ((hv) && (CopSTASHPV(c) == HvNAME(hv) \ || (CopSTASHPV(c) && HvNAME(hv) \ && strEQ(CopSTASHPV(c), HvNAME(hv))))) #endif #else #ifndef CopFILEGV # define CopFILEGV(c) ((c)->cop_filegv) #endif #ifndef CopFILEGV_set # define CopFILEGV_set(c,gv) ((c)->cop_filegv = (GV*)SvREFCNT_inc(gv)) #endif #ifndef CopFILE_set # define CopFILE_set(c,pv) CopFILEGV_set((c), gv_fetchfile(pv)) #endif #ifndef CopFILESV # define CopFILESV(c) (CopFILEGV(c) ? GvSV(CopFILEGV(c)) : Nullsv) #endif #ifndef CopFILEAV # define CopFILEAV(c) (CopFILEGV(c) ? GvAV(CopFILEGV(c)) : Nullav) #endif #ifndef CopFILE # define CopFILE(c) (CopFILESV(c) ? SvPVX(CopFILESV(c)) : Nullch) #endif #ifndef CopSTASH # define CopSTASH(c) ((c)->cop_stash) #endif #ifndef CopSTASH_set # define CopSTASH_set(c,hv) ((c)->cop_stash = (hv)) #endif #ifndef CopSTASHPV # define CopSTASHPV(c) (CopSTASH(c) ? HvNAME(CopSTASH(c)) : Nullch) #endif #ifndef CopSTASHPV_set # define CopSTASHPV_set(c,pv) CopSTASH_set((c), gv_stashpv(pv,GV_ADD)) #endif #ifndef CopSTASH_eq # define CopSTASH_eq(c,hv) (CopSTASH(c) == (hv)) #endif #endif /* USE_ITHREADS */ #ifndef IN_PERL_COMPILETIME # define IN_PERL_COMPILETIME (PL_curcop == &PL_compiling) #endif #ifndef IN_LOCALE_RUNTIME # define IN_LOCALE_RUNTIME (PL_curcop->op_private & HINT_LOCALE) #endif #ifndef IN_LOCALE_COMPILETIME # define IN_LOCALE_COMPILETIME (PL_hints & HINT_LOCALE) #endif #ifndef IN_LOCALE # define IN_LOCALE (IN_PERL_COMPILETIME ? IN_LOCALE_COMPILETIME : IN_LOCALE_RUNTIME) #endif #ifndef IS_NUMBER_IN_UV # define IS_NUMBER_IN_UV 0x01 #endif #ifndef IS_NUMBER_GREATER_THAN_UV_MAX # define IS_NUMBER_GREATER_THAN_UV_MAX 0x02 #endif #ifndef IS_NUMBER_NOT_INT # define IS_NUMBER_NOT_INT 0x04 #endif #ifndef IS_NUMBER_NEG # define IS_NUMBER_NEG 0x08 #endif #ifndef IS_NUMBER_INFINITY # define IS_NUMBER_INFINITY 0x10 #endif #ifndef IS_NUMBER_NAN # define IS_NUMBER_NAN 0x20 #endif #ifndef GROK_NUMERIC_RADIX # define GROK_NUMERIC_RADIX(sp, send) grok_numeric_radix(sp, send) #endif #ifndef PERL_SCAN_GREATER_THAN_UV_MAX # define PERL_SCAN_GREATER_THAN_UV_MAX 0x02 #endif #ifndef PERL_SCAN_SILENT_ILLDIGIT # define PERL_SCAN_SILENT_ILLDIGIT 0x04 #endif #ifndef PERL_SCAN_ALLOW_UNDERSCORES # define PERL_SCAN_ALLOW_UNDERSCORES 0x01 #endif #ifndef PERL_SCAN_DISALLOW_PREFIX # define PERL_SCAN_DISALLOW_PREFIX 0x02 #endif #ifndef grok_numeric_radix #if defined(NEED_grok_numeric_radix) static bool DPPP_(my_grok_numeric_radix)(pTHX_ const char ** sp, const char * send); static #else extern bool DPPP_(my_grok_numeric_radix)(pTHX_ const char ** sp, const char * send); #endif #ifdef grok_numeric_radix # undef grok_numeric_radix #endif #define grok_numeric_radix(a,b) DPPP_(my_grok_numeric_radix)(aTHX_ a,b) #define Perl_grok_numeric_radix DPPP_(my_grok_numeric_radix) #if defined(NEED_grok_numeric_radix) || defined(NEED_grok_numeric_radix_GLOBAL) bool DPPP_(my_grok_numeric_radix)(pTHX_ const char **sp, const char *send) { #ifdef USE_LOCALE_NUMERIC #ifdef PL_numeric_radix_sv if (PL_numeric_radix_sv && IN_LOCALE) { STRLEN len; char* radix = SvPV(PL_numeric_radix_sv, len); if (*sp + len <= send && memEQ(*sp, radix, len)) { *sp += len; return TRUE; } } #else /* older perls don't have PL_numeric_radix_sv so the radix * must manually be requested from locale.h */ #include dTHR; /* needed for older threaded perls */ struct lconv *lc = localeconv(); char *radix = lc->decimal_point; if (radix && IN_LOCALE) { STRLEN len = strlen(radix); if (*sp + len <= send && memEQ(*sp, radix, len)) { *sp += len; return TRUE; } } #endif #endif /* USE_LOCALE_NUMERIC */ /* always try "." if numeric radix didn't match because * we may have data from different locales mixed */ if (*sp < send && **sp == '.') { ++*sp; return TRUE; } return FALSE; } #endif #endif #ifndef grok_number #if defined(NEED_grok_number) static int DPPP_(my_grok_number)(pTHX_ const char * pv, STRLEN len, UV * valuep); static #else extern int DPPP_(my_grok_number)(pTHX_ const char * pv, STRLEN len, UV * valuep); #endif #ifdef grok_number # undef grok_number #endif #define grok_number(a,b,c) DPPP_(my_grok_number)(aTHX_ a,b,c) #define Perl_grok_number DPPP_(my_grok_number) #if defined(NEED_grok_number) || defined(NEED_grok_number_GLOBAL) int DPPP_(my_grok_number)(pTHX_ const char *pv, STRLEN len, UV *valuep) { const char *s = pv; const char *send = pv + len; const UV max_div_10 = UV_MAX / 10; const char max_mod_10 = UV_MAX % 10; int numtype = 0; int sawinf = 0; int sawnan = 0; while (s < send && isSPACE(*s)) s++; if (s == send) { return 0; } else if (*s == '-') { s++; numtype = IS_NUMBER_NEG; } else if (*s == '+') s++; if (s == send) return 0; /* next must be digit or the radix separator or beginning of infinity */ if (isDIGIT(*s)) { /* UVs are at least 32 bits, so the first 9 decimal digits cannot overflow. */ UV value = *s - '0'; /* This construction seems to be more optimiser friendly. (without it gcc does the isDIGIT test and the *s - '0' separately) With it gcc on arm is managing 6 instructions (6 cycles) per digit. In theory the optimiser could deduce how far to unroll the loop before checking for overflow. */ if (++s < send) { int digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { /* Now got 9 digits, so need to check each time for overflow. */ digit = *s - '0'; while (digit >= 0 && digit <= 9 && (value < max_div_10 || (value == max_div_10 && digit <= max_mod_10))) { value = value * 10 + digit; if (++s < send) digit = *s - '0'; else break; } if (digit >= 0 && digit <= 9 && (s < send)) { /* value overflowed. skip the remaining digits, don't worry about setting *valuep. */ do { s++; } while (s < send && isDIGIT(*s)); numtype |= IS_NUMBER_GREATER_THAN_UV_MAX; goto skip_value; } } } } } } } } } } } } } } } } } } numtype |= IS_NUMBER_IN_UV; if (valuep) *valuep = value; skip_value: if (GROK_NUMERIC_RADIX(&s, send)) { numtype |= IS_NUMBER_NOT_INT; while (s < send && isDIGIT(*s)) /* optional digits after the radix */ s++; } } else if (GROK_NUMERIC_RADIX(&s, send)) { numtype |= IS_NUMBER_NOT_INT | IS_NUMBER_IN_UV; /* valuep assigned below */ /* no digits before the radix means we need digits after it */ if (s < send && isDIGIT(*s)) { do { s++; } while (s < send && isDIGIT(*s)); if (valuep) { /* integer approximation is valid - it's 0. */ *valuep = 0; } } else return 0; } else if (*s == 'I' || *s == 'i') { s++; if (s == send || (*s != 'N' && *s != 'n')) return 0; s++; if (s == send || (*s != 'F' && *s != 'f')) return 0; s++; if (s < send && (*s == 'I' || *s == 'i')) { s++; if (s == send || (*s != 'N' && *s != 'n')) return 0; s++; if (s == send || (*s != 'I' && *s != 'i')) return 0; s++; if (s == send || (*s != 'T' && *s != 't')) return 0; s++; if (s == send || (*s != 'Y' && *s != 'y')) return 0; s++; } sawinf = 1; } else if (*s == 'N' || *s == 'n') { /* XXX TODO: There are signaling NaNs and quiet NaNs. */ s++; if (s == send || (*s != 'A' && *s != 'a')) return 0; s++; if (s == send || (*s != 'N' && *s != 'n')) return 0; s++; sawnan = 1; } else return 0; if (sawinf) { numtype &= IS_NUMBER_NEG; /* Keep track of sign */ numtype |= IS_NUMBER_INFINITY | IS_NUMBER_NOT_INT; } else if (sawnan) { numtype &= IS_NUMBER_NEG; /* Keep track of sign */ numtype |= IS_NUMBER_NAN | IS_NUMBER_NOT_INT; } else if (s < send) { /* we can have an optional exponent part */ if (*s == 'e' || *s == 'E') { /* The only flag we keep is sign. Blow away any "it's UV" */ numtype &= IS_NUMBER_NEG; numtype |= IS_NUMBER_NOT_INT; s++; if (s < send && (*s == '-' || *s == '+')) s++; if (s < send && isDIGIT(*s)) { do { s++; } while (s < send && isDIGIT(*s)); } else return 0; } } while (s < send && isSPACE(*s)) s++; if (s >= send) return numtype; if (len == 10 && memEQ(pv, "0 but true", 10)) { if (valuep) *valuep = 0; return IS_NUMBER_IN_UV; } return 0; } #endif #endif /* * The grok_* routines have been modified to use warn() instead of * Perl_warner(). Also, 'hexdigit' was the former name of PL_hexdigit, * which is why the stack variable has been renamed to 'xdigit'. */ #ifndef grok_bin #if defined(NEED_grok_bin) static UV DPPP_(my_grok_bin)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); static #else extern UV DPPP_(my_grok_bin)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); #endif #ifdef grok_bin # undef grok_bin #endif #define grok_bin(a,b,c,d) DPPP_(my_grok_bin)(aTHX_ a,b,c,d) #define Perl_grok_bin DPPP_(my_grok_bin) #if defined(NEED_grok_bin) || defined(NEED_grok_bin_GLOBAL) UV DPPP_(my_grok_bin)(pTHX_ const char *start, STRLEN *len_p, I32 *flags, NV *result) { const char *s = start; STRLEN len = *len_p; UV value = 0; NV value_nv = 0; const UV max_div_2 = UV_MAX / 2; bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES; bool overflowed = FALSE; if (!(*flags & PERL_SCAN_DISALLOW_PREFIX)) { /* strip off leading b or 0b. for compatibility silently suffer "b" and "0b" as valid binary numbers. */ if (len >= 1) { if (s[0] == 'b') { s++; len--; } else if (len >= 2 && s[0] == '0' && s[1] == 'b') { s+=2; len-=2; } } } for (; len-- && *s; s++) { char bit = *s; if (bit == '0' || bit == '1') { /* Write it in this wonky order with a goto to attempt to get the compiler to make the common case integer-only loop pretty tight. With gcc seems to be much straighter code than old scan_bin. */ redo: if (!overflowed) { if (value <= max_div_2) { value = (value << 1) | (bit - '0'); continue; } /* Bah. We're just overflowed. */ warn("Integer overflow in binary number"); overflowed = TRUE; value_nv = (NV) value; } value_nv *= 2.0; /* If an NV has not enough bits in its mantissa to * represent a UV this summing of small low-order numbers * is a waste of time (because the NV cannot preserve * the low-order bits anyway): we could just remember when * did we overflow and in the end just multiply value_nv by the * right amount. */ value_nv += (NV)(bit - '0'); continue; } if (bit == '_' && len && allow_underscores && (bit = s[1]) && (bit == '0' || bit == '1')) { --len; ++s; goto redo; } if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT)) warn("Illegal binary digit '%c' ignored", *s); break; } if ( ( overflowed && value_nv > 4294967295.0) #if UVSIZE > 4 || (!overflowed && value > 0xffffffff ) #endif ) { warn("Binary number > 0b11111111111111111111111111111111 non-portable"); } *len_p = s - start; if (!overflowed) { *flags = 0; return value; } *flags = PERL_SCAN_GREATER_THAN_UV_MAX; if (result) *result = value_nv; return UV_MAX; } #endif #endif #ifndef grok_hex #if defined(NEED_grok_hex) static UV DPPP_(my_grok_hex)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); static #else extern UV DPPP_(my_grok_hex)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); #endif #ifdef grok_hex # undef grok_hex #endif #define grok_hex(a,b,c,d) DPPP_(my_grok_hex)(aTHX_ a,b,c,d) #define Perl_grok_hex DPPP_(my_grok_hex) #if defined(NEED_grok_hex) || defined(NEED_grok_hex_GLOBAL) UV DPPP_(my_grok_hex)(pTHX_ const char *start, STRLEN *len_p, I32 *flags, NV *result) { const char *s = start; STRLEN len = *len_p; UV value = 0; NV value_nv = 0; const UV max_div_16 = UV_MAX / 16; bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES; bool overflowed = FALSE; const char *xdigit; if (!(*flags & PERL_SCAN_DISALLOW_PREFIX)) { /* strip off leading x or 0x. for compatibility silently suffer "x" and "0x" as valid hex numbers. */ if (len >= 1) { if (s[0] == 'x') { s++; len--; } else if (len >= 2 && s[0] == '0' && s[1] == 'x') { s+=2; len-=2; } } } for (; len-- && *s; s++) { xdigit = strchr((char *) PL_hexdigit, *s); if (xdigit) { /* Write it in this wonky order with a goto to attempt to get the compiler to make the common case integer-only loop pretty tight. With gcc seems to be much straighter code than old scan_hex. */ redo: if (!overflowed) { if (value <= max_div_16) { value = (value << 4) | ((xdigit - PL_hexdigit) & 15); continue; } warn("Integer overflow in hexadecimal number"); overflowed = TRUE; value_nv = (NV) value; } value_nv *= 16.0; /* If an NV has not enough bits in its mantissa to * represent a UV this summing of small low-order numbers * is a waste of time (because the NV cannot preserve * the low-order bits anyway): we could just remember when * did we overflow and in the end just multiply value_nv by the * right amount of 16-tuples. */ value_nv += (NV)((xdigit - PL_hexdigit) & 15); continue; } if (*s == '_' && len && allow_underscores && s[1] && (xdigit = strchr((char *) PL_hexdigit, s[1]))) { --len; ++s; goto redo; } if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT)) warn("Illegal hexadecimal digit '%c' ignored", *s); break; } if ( ( overflowed && value_nv > 4294967295.0) #if UVSIZE > 4 || (!overflowed && value > 0xffffffff ) #endif ) { warn("Hexadecimal number > 0xffffffff non-portable"); } *len_p = s - start; if (!overflowed) { *flags = 0; return value; } *flags = PERL_SCAN_GREATER_THAN_UV_MAX; if (result) *result = value_nv; return UV_MAX; } #endif #endif #ifndef grok_oct #if defined(NEED_grok_oct) static UV DPPP_(my_grok_oct)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); static #else extern UV DPPP_(my_grok_oct)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); #endif #ifdef grok_oct # undef grok_oct #endif #define grok_oct(a,b,c,d) DPPP_(my_grok_oct)(aTHX_ a,b,c,d) #define Perl_grok_oct DPPP_(my_grok_oct) #if defined(NEED_grok_oct) || defined(NEED_grok_oct_GLOBAL) UV DPPP_(my_grok_oct)(pTHX_ const char *start, STRLEN *len_p, I32 *flags, NV *result) { const char *s = start; STRLEN len = *len_p; UV value = 0; NV value_nv = 0; const UV max_div_8 = UV_MAX / 8; bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES; bool overflowed = FALSE; for (; len-- && *s; s++) { /* gcc 2.95 optimiser not smart enough to figure that this subtraction out front allows slicker code. */ int digit = *s - '0'; if (digit >= 0 && digit <= 7) { /* Write it in this wonky order with a goto to attempt to get the compiler to make the common case integer-only loop pretty tight. */ redo: if (!overflowed) { if (value <= max_div_8) { value = (value << 3) | digit; continue; } /* Bah. We're just overflowed. */ warn("Integer overflow in octal number"); overflowed = TRUE; value_nv = (NV) value; } value_nv *= 8.0; /* If an NV has not enough bits in its mantissa to * represent a UV this summing of small low-order numbers * is a waste of time (because the NV cannot preserve * the low-order bits anyway): we could just remember when * did we overflow and in the end just multiply value_nv by the * right amount of 8-tuples. */ value_nv += (NV)digit; continue; } if (digit == ('_' - '0') && len && allow_underscores && (digit = s[1] - '0') && (digit >= 0 && digit <= 7)) { --len; ++s; goto redo; } /* Allow \octal to work the DWIM way (that is, stop scanning * as soon as non-octal characters are seen, complain only iff * someone seems to want to use the digits eight and nine). */ if (digit == 8 || digit == 9) { if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT)) warn("Illegal octal digit '%c' ignored", *s); } break; } if ( ( overflowed && value_nv > 4294967295.0) #if UVSIZE > 4 || (!overflowed && value > 0xffffffff ) #endif ) { warn("Octal number > 037777777777 non-portable"); } *len_p = s - start; if (!overflowed) { *flags = 0; return value; } *flags = PERL_SCAN_GREATER_THAN_UV_MAX; if (result) *result = value_nv; return UV_MAX; } #endif #endif #if !defined(my_snprintf) #if defined(NEED_my_snprintf) static int DPPP_(my_my_snprintf)(char * buffer, const Size_t len, const char * format, ...); static #else extern int DPPP_(my_my_snprintf)(char * buffer, const Size_t len, const char * format, ...); #endif #define my_snprintf DPPP_(my_my_snprintf) #define Perl_my_snprintf DPPP_(my_my_snprintf) #if defined(NEED_my_snprintf) || defined(NEED_my_snprintf_GLOBAL) int DPPP_(my_my_snprintf)(char *buffer, const Size_t len, const char *format, ...) { dTHX; int retval; va_list ap; va_start(ap, format); #ifdef HAS_VSNPRINTF retval = vsnprintf(buffer, len, format, ap); #else retval = vsprintf(buffer, format, ap); #endif va_end(ap); if (retval < 0 || (len > 0 && (Size_t)retval >= len)) Perl_croak(aTHX_ "panic: my_snprintf buffer overflow"); return retval; } #endif #endif #if !defined(my_sprintf) #if defined(NEED_my_sprintf) static int DPPP_(my_my_sprintf)(char * buffer, const char * pat, ...); static #else extern int DPPP_(my_my_sprintf)(char * buffer, const char * pat, ...); #endif #define my_sprintf DPPP_(my_my_sprintf) #define Perl_my_sprintf DPPP_(my_my_sprintf) #if defined(NEED_my_sprintf) || defined(NEED_my_sprintf_GLOBAL) int DPPP_(my_my_sprintf)(char *buffer, const char* pat, ...) { va_list args; va_start(args, pat); vsprintf(buffer, pat, args); va_end(args); return strlen(buffer); } #endif #endif #ifdef NO_XSLOCKS # ifdef dJMPENV # define dXCPT dJMPENV; int rEtV = 0 # define XCPT_TRY_START JMPENV_PUSH(rEtV); if (rEtV == 0) # define XCPT_TRY_END JMPENV_POP; # define XCPT_CATCH if (rEtV != 0) # define XCPT_RETHROW JMPENV_JUMP(rEtV) # else # define dXCPT Sigjmp_buf oldTOP; int rEtV = 0 # define XCPT_TRY_START Copy(top_env, oldTOP, 1, Sigjmp_buf); rEtV = Sigsetjmp(top_env, 1); if (rEtV == 0) # define XCPT_TRY_END Copy(oldTOP, top_env, 1, Sigjmp_buf); # define XCPT_CATCH if (rEtV != 0) # define XCPT_RETHROW Siglongjmp(top_env, rEtV) # endif #endif #if !defined(my_strlcat) #if defined(NEED_my_strlcat) static Size_t DPPP_(my_my_strlcat)(char * dst, const char * src, Size_t size); static #else extern Size_t DPPP_(my_my_strlcat)(char * dst, const char * src, Size_t size); #endif #define my_strlcat DPPP_(my_my_strlcat) #define Perl_my_strlcat DPPP_(my_my_strlcat) #if defined(NEED_my_strlcat) || defined(NEED_my_strlcat_GLOBAL) Size_t DPPP_(my_my_strlcat)(char *dst, const char *src, Size_t size) { Size_t used, length, copy; used = strlen(dst); length = strlen(src); if (size > 0 && used < size - 1) { copy = (length >= size - used) ? size - used - 1 : length; memcpy(dst + used, src, copy); dst[used + copy] = '\0'; } return used + length; } #endif #endif #if !defined(my_strlcpy) #if defined(NEED_my_strlcpy) static Size_t DPPP_(my_my_strlcpy)(char * dst, const char * src, Size_t size); static #else extern Size_t DPPP_(my_my_strlcpy)(char * dst, const char * src, Size_t size); #endif #define my_strlcpy DPPP_(my_my_strlcpy) #define Perl_my_strlcpy DPPP_(my_my_strlcpy) #if defined(NEED_my_strlcpy) || defined(NEED_my_strlcpy_GLOBAL) Size_t DPPP_(my_my_strlcpy)(char *dst, const char *src, Size_t size) { Size_t length, copy; length = strlen(src); if (size > 0) { copy = (length >= size) ? size - 1 : length; memcpy(dst, src, copy); dst[copy] = '\0'; } return length; } #endif #endif #ifndef PERL_PV_ESCAPE_QUOTE # define PERL_PV_ESCAPE_QUOTE 0x0001 #endif #ifndef PERL_PV_PRETTY_QUOTE # define PERL_PV_PRETTY_QUOTE PERL_PV_ESCAPE_QUOTE #endif #ifndef PERL_PV_PRETTY_ELLIPSES # define PERL_PV_PRETTY_ELLIPSES 0x0002 #endif #ifndef PERL_PV_PRETTY_LTGT # define PERL_PV_PRETTY_LTGT 0x0004 #endif #ifndef PERL_PV_ESCAPE_FIRSTCHAR # define PERL_PV_ESCAPE_FIRSTCHAR 0x0008 #endif #ifndef PERL_PV_ESCAPE_UNI # define PERL_PV_ESCAPE_UNI 0x0100 #endif #ifndef PERL_PV_ESCAPE_UNI_DETECT # define PERL_PV_ESCAPE_UNI_DETECT 0x0200 #endif #ifndef PERL_PV_ESCAPE_ALL # define PERL_PV_ESCAPE_ALL 0x1000 #endif #ifndef PERL_PV_ESCAPE_NOBACKSLASH # define PERL_PV_ESCAPE_NOBACKSLASH 0x2000 #endif #ifndef PERL_PV_ESCAPE_NOCLEAR # define PERL_PV_ESCAPE_NOCLEAR 0x4000 #endif #ifndef PERL_PV_ESCAPE_RE # define PERL_PV_ESCAPE_RE 0x8000 #endif #ifndef PERL_PV_PRETTY_NOCLEAR # define PERL_PV_PRETTY_NOCLEAR PERL_PV_ESCAPE_NOCLEAR #endif #ifndef PERL_PV_PRETTY_DUMP # define PERL_PV_PRETTY_DUMP PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE #endif #ifndef PERL_PV_PRETTY_REGPROP # define PERL_PV_PRETTY_REGPROP PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_LTGT|PERL_PV_ESCAPE_RE #endif /* Hint: pv_escape * Note that unicode functionality is only backported to * those perl versions that support it. For older perl * versions, the implementation will fall back to bytes. */ #ifndef pv_escape #if defined(NEED_pv_escape) static char * DPPP_(my_pv_escape)(pTHX_ SV * dsv, char const * const str, const STRLEN count, const STRLEN max, STRLEN * const escaped, const U32 flags); static #else extern char * DPPP_(my_pv_escape)(pTHX_ SV * dsv, char const * const str, const STRLEN count, const STRLEN max, STRLEN * const escaped, const U32 flags); #endif #ifdef pv_escape # undef pv_escape #endif #define pv_escape(a,b,c,d,e,f) DPPP_(my_pv_escape)(aTHX_ a,b,c,d,e,f) #define Perl_pv_escape DPPP_(my_pv_escape) #if defined(NEED_pv_escape) || defined(NEED_pv_escape_GLOBAL) char * DPPP_(my_pv_escape)(pTHX_ SV *dsv, char const * const str, const STRLEN count, const STRLEN max, STRLEN * const escaped, const U32 flags) { const char esc = flags & PERL_PV_ESCAPE_RE ? '%' : '\\'; const char dq = flags & PERL_PV_ESCAPE_QUOTE ? '"' : esc; char octbuf[32] = "%123456789ABCDF"; STRLEN wrote = 0; STRLEN chsize = 0; STRLEN readsize = 1; #if defined(is_utf8_string) && defined(utf8_to_uvchr) bool isuni = flags & PERL_PV_ESCAPE_UNI ? 1 : 0; #endif const char *pv = str; const char * const end = pv + count; octbuf[0] = esc; if (!(flags & PERL_PV_ESCAPE_NOCLEAR)) sv_setpvs(dsv, ""); #if defined(is_utf8_string) && defined(utf8_to_uvchr) if ((flags & PERL_PV_ESCAPE_UNI_DETECT) && is_utf8_string((U8*)pv, count)) isuni = 1; #endif for (; pv < end && (!max || wrote < max) ; pv += readsize) { const UV u = #if defined(is_utf8_string) && defined(utf8_to_uvchr) isuni ? utf8_to_uvchr((U8*)pv, &readsize) : #endif (U8)*pv; const U8 c = (U8)u & 0xFF; if (u > 255 || (flags & PERL_PV_ESCAPE_ALL)) { if (flags & PERL_PV_ESCAPE_FIRSTCHAR) chsize = my_snprintf(octbuf, sizeof octbuf, "%"UVxf, u); else chsize = my_snprintf(octbuf, sizeof octbuf, "%cx{%"UVxf"}", esc, u); } else if (flags & PERL_PV_ESCAPE_NOBACKSLASH) { chsize = 1; } else { if (c == dq || c == esc || !isPRINT(c)) { chsize = 2; switch (c) { case '\\' : /* fallthrough */ case '%' : if (c == esc) octbuf[1] = esc; else chsize = 1; break; case '\v' : octbuf[1] = 'v'; break; case '\t' : octbuf[1] = 't'; break; case '\r' : octbuf[1] = 'r'; break; case '\n' : octbuf[1] = 'n'; break; case '\f' : octbuf[1] = 'f'; break; case '"' : if (dq == '"') octbuf[1] = '"'; else chsize = 1; break; default: chsize = my_snprintf(octbuf, sizeof octbuf, pv < end && isDIGIT((U8)*(pv+readsize)) ? "%c%03o" : "%c%o", esc, c); } } else { chsize = 1; } } if (max && wrote + chsize > max) { break; } else if (chsize > 1) { sv_catpvn(dsv, octbuf, chsize); wrote += chsize; } else { char tmp[2]; my_snprintf(tmp, sizeof tmp, "%c", c); sv_catpvn(dsv, tmp, 1); wrote++; } if (flags & PERL_PV_ESCAPE_FIRSTCHAR) break; } if (escaped != NULL) *escaped= pv - str; return SvPVX(dsv); } #endif #endif #ifndef pv_pretty #if defined(NEED_pv_pretty) static char * DPPP_(my_pv_pretty)(pTHX_ SV * dsv, char const * const str, const STRLEN count, const STRLEN max, char const * const start_color, char const * const end_color, const U32 flags); static #else extern char * DPPP_(my_pv_pretty)(pTHX_ SV * dsv, char const * const str, const STRLEN count, const STRLEN max, char const * const start_color, char const * const end_color, const U32 flags); #endif #ifdef pv_pretty # undef pv_pretty #endif #define pv_pretty(a,b,c,d,e,f,g) DPPP_(my_pv_pretty)(aTHX_ a,b,c,d,e,f,g) #define Perl_pv_pretty DPPP_(my_pv_pretty) #if defined(NEED_pv_pretty) || defined(NEED_pv_pretty_GLOBAL) char * DPPP_(my_pv_pretty)(pTHX_ SV *dsv, char const * const str, const STRLEN count, const STRLEN max, char const * const start_color, char const * const end_color, const U32 flags) { const U8 dq = (flags & PERL_PV_PRETTY_QUOTE) ? '"' : '%'; STRLEN escaped; if (!(flags & PERL_PV_PRETTY_NOCLEAR)) sv_setpvs(dsv, ""); if (dq == '"') sv_catpvs(dsv, "\""); else if (flags & PERL_PV_PRETTY_LTGT) sv_catpvs(dsv, "<"); if (start_color != NULL) sv_catpv(dsv, D_PPP_CONSTPV_ARG(start_color)); pv_escape(dsv, str, count, max, &escaped, flags | PERL_PV_ESCAPE_NOCLEAR); if (end_color != NULL) sv_catpv(dsv, D_PPP_CONSTPV_ARG(end_color)); if (dq == '"') sv_catpvs(dsv, "\""); else if (flags & PERL_PV_PRETTY_LTGT) sv_catpvs(dsv, ">"); if ((flags & PERL_PV_PRETTY_ELLIPSES) && escaped < count) sv_catpvs(dsv, "..."); return SvPVX(dsv); } #endif #endif #ifndef pv_display #if defined(NEED_pv_display) static char * DPPP_(my_pv_display)(pTHX_ SV * dsv, const char * pv, STRLEN cur, STRLEN len, STRLEN pvlim); static #else extern char * DPPP_(my_pv_display)(pTHX_ SV * dsv, const char * pv, STRLEN cur, STRLEN len, STRLEN pvlim); #endif #ifdef pv_display # undef pv_display #endif #define pv_display(a,b,c,d,e) DPPP_(my_pv_display)(aTHX_ a,b,c,d,e) #define Perl_pv_display DPPP_(my_pv_display) #if defined(NEED_pv_display) || defined(NEED_pv_display_GLOBAL) char * DPPP_(my_pv_display)(pTHX_ SV *dsv, const char *pv, STRLEN cur, STRLEN len, STRLEN pvlim) { pv_pretty(dsv, pv, cur, pvlim, NULL, NULL, PERL_PV_PRETTY_DUMP); if (len > cur && pv[cur] == '\0') sv_catpvs(dsv, "\\0"); return SvPVX(dsv); } #endif #endif #endif /* _P_P_PORTABILITY_H_ */ /* End of File ppport.h */ Cpanel-JSON-XS-3.0210/README0000644000076500001200000023461012630027164014125 0ustar rurbanadminNAME Cpanel::JSON::XS - cPanel fork of JSON::XS, fast and correct serializing SYNOPSIS use Cpanel::JSON::XS; # exported functions, they croak on error # and expect/generate UTF-8 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref; $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text; # OO-interface $coder = Cpanel::JSON::XS->new->ascii->pretty->allow_nonref; $pretty_printed_unencoded = $coder->encode ($perl_scalar); $perl_scalar = $coder->decode ($unicode_json_text); # Note that 5.6 misses most smart utf8 and encoding functionalities # of newer releases. # Note that L will automatically use Cpanel::JSON::XS # if available, at virtually no speed overhead either, so you should # be able to just: use JSON::MaybeXS; # and do the same things, except that you have a pure-perl fallback now. DESCRIPTION This module converts Perl data structures to JSON and vice versa. Its primary goal is to be *correct* and its secondary goal is to be *fast*. To reach the latter goal it was written in C. As this is the n-th-something JSON module on CPAN, what was the reason to write yet another JSON module? While it seems there are many JSON modules, none of them correctly handle all corner cases, and in most cases their maintainers are unresponsive, gone missing, or not listening to bug reports for other reasons. See below for the cPanel fork. See MAPPING, below, on how Cpanel::JSON::XS maps perl values to JSON values and vice versa. FEATURES * correct Unicode handling This module knows how to handle Unicode with Perl version higher than 5.8.5, documents how and when it does so, and even documents what "correct" means. * round-trip integrity When you serialize a perl data structure using only data types supported by JSON and Perl, the deserialized data structure is identical on the Perl level. (e.g. the string "2.0" doesn't suddenly become "2" just because it looks like a number). There *are* minor exceptions to this, read the MAPPING section below to learn about those. * strict checking of JSON correctness There is no guessing, no generating of illegal JSON texts by default, and only JSON is accepted as input by default (the latter is a security feature). * fast Compared to other JSON modules and other serializers such as Storable, this module usually compares favourably in terms of speed, too. * simple to use This module has both a simple functional interface as well as an object oriented interface. * reasonably versatile output formats You can choose between the most compact guaranteed-single-line format possible (nice for simple line-based protocols), a pure-ASCII format (for when your transport is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed format (for when you want to read that stuff). Or you can combine those features in whatever way you like. cPanel fork Since the original author MLEHMANN has no public bugtracker, this cPanel fork sits now on github. src repo: original: RT: or Changes to JSON::XS - stricter decode_json() as documented. non-refs are disallowed. added a 2nd optional argument. decode() honors now allow_nonref. - fixed encode of numbers for dual-vars. Different string representations are preserved, but numbers with temporary strings which represent the same number are here treated as numbers, not strings. Cpanel::JSON::XS is a bit slower, but preserves numeric types better. - different handling of inf/nan. Default now to null, optionally with -DSTRINGIFY_INFNAN to "inf"/"nan". [#28, #32] - added "binary" extension, non-JSON and non JSON parsable, allows "\xNN" and "\NNN" sequences. - 5.6.2 support; sacrificing some utf8 features (assuming bytes all-over), no multi-byte unicode characters. - interop for true/false overloading. JSON::XS, JSON::PP and Mojo::JSON representations for booleans are accepted and JSON::XS accepts Cpanel::JSON::XS booleans [#13, #37] Fixed overloading of booleans. Cpanel::JSON::XS::true stringifies now to true, not 1. - native boolean mapping of yes and no to true and false, as in YAML::XS. In perl "!0" is yes, "!1" is no. The JSON value true maps to 1, false maps to 0. [#39] - support arbitrary stringification with encode, with convert_blessed and allow_blessed. - ithread support. Cpanel::JSON::XS is thread-safe, JSON::XS not - is_bool can be called as method, JSON::XS::is_bool not. - Performance Optimizations for threaded Perls - additional fixes for: - [cpan #88061] AIX atof without USE_LONG_DOUBLE - #10 unshare_hek crash - #7, #29 avoid re-blessing where possible. It fails in JSON::XS for READONLY values, i.e. restricted hashes. - #41 overloading of booleans, use the object not the reference. - public maintenance and bugtracker - use ppport.h, sanify XS.xs comment styles, harness C coding style - common::sense is optional. When available it is not used in the published production module, just during development and testing. - extended testsuite - support many more options and methods from JSON::PP FUNCTIONAL INTERFACE The following convenience methods are provided by this module. They are exported by default: $json_text = encode_json $perl_scalar Converts the given Perl data structure to a UTF-8 encoded, binary string (that is, the string contains octets only). Croaks on error. This function call is functionally identical to: $json_text = Cpanel::JSON::XS->new->utf8->encode ($perl_scalar) Except being faster. $perl_scalar = decode_json $json_text [, $allow_nonref ] The opposite of "encode_json": expects an UTF-8 (binary) string of an json reference and tries to parse that as an UTF-8 encoded JSON text, returning the resulting reference. Croaks on error. This function call is functionally identical to: $perl_scalar = Cpanel::JSON::XS->new->utf8->decode ($json_text) except being faster. Note that older decode_json versions in Cpanel::JSON::XS older than 3.0116 and JSON::XS did not set allow_nonref but allowed them due to a bug in the decoder. If the new optional $allow_nonref argument is set and not false, the allow_nonref option will be set and the function will act is described as in the relaxed RFC 7159 allowing all values such as objects, arrays, strings, numbers, "null", "true", and "false". $is_boolean = Cpanel::JSON::XS::is_bool $scalar Returns true if the passed scalar represents either "JSON::XS::true" or "JSON::XS::false", two constants that act like 1 and 0, respectively and are used to represent JSON "true" and "false" values in Perl. See MAPPING, below, for more information on how JSON values are mapped to Perl. DEPRECATED FUNCTIONS from_json from_json has been renamed to decode_json to_json to_json has been renamed to encode_json A FEW NOTES ON UNICODE AND PERL Since this often leads to confusion, here are a few very clear words on how Unicode works in Perl, modulo bugs. 1. Perl strings can store characters with ordinal values > 255. This enables you to store Unicode characters as single characters in a Perl string - very natural. 2. Perl does *not* associate an encoding with your strings. ... until you force it to, e.g. when matching it against a regex, or printing the scalar to a file, in which case Perl either interprets your string as locale-encoded text, octets/binary, or as Unicode, depending on various settings. In no case is an encoding stored together with your data, it is *use* that decides encoding, not any magical meta data. 3. The internal utf-8 flag has no meaning with regards to the encoding of your string. 4. A "Unicode String" is simply a string where each character can be validly interpreted as a Unicode code point. If you have UTF-8 encoded data, it is no longer a Unicode string, but a Unicode string encoded in UTF-8, giving you a binary string. 5. A string containing "high" (> 255) character values is *not* a UTF-8 string. I hope this helps :) OBJECT-ORIENTED INTERFACE The object oriented interface lets you configure your own encoding or decoding style, within the limits of supported formats. $json = new Cpanel::JSON::XS Creates a new JSON object that can be used to de/encode JSON strings. All boolean flags described below are by default *disabled*. The mutators for flags all return the JSON object again and thus calls can be chained: my $json = Cpanel::JSON::XS->new->utf8->space_after->encode ({a => [1,2]}) => {"a": [1, 2]} $json = $json->ascii ([$enable]) $enabled = $json->get_ascii If $enable is true (or missing), then the "encode" method will not generate characters outside the code range 0..127 (which is ASCII). Any Unicode characters outside that range will be escaped using either a single "\uXXXX" (BMP characters) or a double "\uHHHH\uLLLLL" escape sequence, as per RFC4627. The resulting encoded JSON text can be treated as a native Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string, or any other superset of ASCII. If $enable is false, then the "encode" method will not escape Unicode characters unless required by the JSON syntax or other flags. This results in a faster and more compact format. See also the section *ENCODING/CODESET FLAG NOTES* later in this document. The main use for this flag is to produce JSON texts that can be transmitted over a 7-bit channel, as the encoded JSON texts will not contain any 8 bit characters. Cpanel::JSON::XS->new->ascii (1)->encode ([chr 0x10401]) => ["\ud801\udc01"] $json = $json->latin1 ([$enable]) $enabled = $json->get_latin1 If $enable is true (or missing), then the "encode" method will encode the resulting JSON text as latin1 (or ISO-8859-1), escaping any characters outside the code range 0..255. The resulting string can be treated as a latin1-encoded JSON text or a native Unicode string. The "decode" method will not be affected in any way by this flag, as "decode" by default expects Unicode, which is a strict superset of latin1. If $enable is false, then the "encode" method will not escape Unicode characters unless required by the JSON syntax or other flags. See also the section *ENCODING/CODESET FLAG NOTES* later in this document. The main use for this flag is efficiently encoding binary data as JSON text, as most octets will not be escaped, resulting in a smaller encoded size. The disadvantage is that the resulting JSON text is encoded in latin1 (and must correctly be treated as such when storing and transferring), a rare encoding for JSON. It is therefore most useful when you want to store data structures known to contain binary data efficiently in files or databases, not when talking to other JSON encoders/decoders. Cpanel::JSON::XS->new->latin1->encode (["\x{89}\x{abc}"] => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) $json = $json->binary ([$enable]) $enabled = $json = $json->get_binary If the $enable argument is true (or missing), then the "encode" method will not try to detect an UTF-8 encoding in any JSON string, it will strictly interpret it as byte sequence. The result might contain new "\xNN" sequences, which is unparsable JSON. The "decode" method forbids "\uNNNN" sequences and accepts "\xNN" and octal "\NNN" sequences. There is also a special logic for perl 5.6 and utf8. 5.6 encodes any string to utf-8 automatically when seeing a codepoint >= 0x80 and < 0x100. With the binary flag enabled decode the perl utf8 encoded string to the original byte encoding and encode this with "\xNN" escapes. This will result to the same encodings as with newer perls. But note that binary multi-byte codepoints with 5.6 will result in "illegal unicode character in binary string" errors, unlike with newer perls. If $enable is false, then the "encode" method will smartly try to detect Unicode characters unless required by the JSON syntax or other flags and hex and octal sequences are forbidden. See also the section *ENCODING/CODESET FLAG NOTES* later in this document. The main use for this flag is to avoid the smart unicode detection and possible double encoding. The disadvantage is that the resulting JSON text is encoded in new "\xNN" and in latin1 characters and must correctly be treated as such when storing and transferring, a rare encoding for JSON. It will produce non-readable JSON strings in the browser. It is therefore most useful when you want to store data structures known to contain binary data efficiently in files or databases, not when talking to other JSON encoders/decoders. The binary decoding method can also be used when an encoder produced a non-JSON conformant hex or octal encoding "\xNN" or "\NNN". Cpanel::JSON::XS->new->binary->encode (["\x{89}\x{abc}"]) 5.6: Error: malformed or illegal unicode character in binary string >=5.8: ['\x89\xe0\xaa\xbc'] Cpanel::JSON::XS->new->binary->encode (["\x{89}\x{bc}"]) => ["\x89\xbc"] Cpanel::JSON::XS->new->binary->decode (["\x89\ua001"]) Error: malformed or illegal unicode character in binary string Cpanel::JSON::XS->new->decode (["\x89"]) Error: illegal hex character in non-binary string $json = $json->utf8 ([$enable]) $enabled = $json->get_utf8 If $enable is true (or missing), then the "encode" method will encode the JSON result into UTF-8, as required by many protocols, while the "decode" method expects to be handled an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any characters outside the range 0..255, they are thus useful for bytewise/binary I/O. In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32 encoding families, as described in RFC4627. If $enable is false, then the "encode" method will return the JSON string as a (non-encoded) Unicode string, while "decode" expects thus a Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module. See also the section *ENCODING/CODESET FLAG NOTES* later in this document. Example, output UTF-16BE-encoded JSON: use Encode; $jsontext = encode "UTF-16BE", Cpanel::JSON::XS->new->encode ($object); Example, decode UTF-32LE-encoded JSON: use Encode; $object = Cpanel::JSON::XS->new->decode (decode "UTF-32LE", $jsontext); $json = $json->pretty ([$enable]) This enables (or disables) all of the "indent", "space_before" and "space_after" (and in the future possibly more) flags in one call to generate the most readable (or most compact) form possible. Example, pretty-print some simple structure: my $json = Cpanel::JSON::XS->new->pretty(1)->encode ({a => [1,2]}) => { "a" : [ 1, 2 ] } $json = $json->indent ([$enable]) $enabled = $json->get_indent If $enable is true (or missing), then the "encode" method will use a multiline format as output, putting every array member or object/hash key-value pair into its own line, indenting them properly. If $enable is false, no newlines or indenting will be produced, and the resulting JSON text is guaranteed not to contain any "newlines". This setting has no effect when decoding JSON texts. $json = $json->space_before ([$enable]) $enabled = $json->get_space_before If $enable is true (or missing), then the "encode" method will add an extra optional space before the ":" separating keys from values in JSON objects. If $enable is false, then the "encode" method will not add any extra space at those places. This setting has no effect when decoding JSON texts. You will also most likely combine this setting with "space_after". Example, space_before enabled, space_after and indent disabled: {"key" :"value"} $json = $json->space_after ([$enable]) $enabled = $json->get_space_after If $enable is true (or missing), then the "encode" method will add an extra optional space after the ":" separating keys from values in JSON objects and extra whitespace after the "," separating key-value pairs and array members. If $enable is false, then the "encode" method will not add any extra space at those places. This setting has no effect when decoding JSON texts. Example, space_before and indent disabled, space_after enabled: {"key": "value"} $json = $json->relaxed ([$enable]) $enabled = $json->get_relaxed If $enable is true (or missing), then "decode" will accept some extensions to normal JSON syntax (see below). "encode" will not be affected in anyway. *Be aware that this option makes you accept invalid JSON texts as if they were valid!*. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.) If $enable is false (the default), then "decode" will only accept valid JSON texts. Currently accepted extensions are: * list items can have an end-comma JSON *separates* array elements and key-value pairs with commas. This can be annoying if you write JSON texts manually and want to be able to quickly append elements, so this extension accepts comma at the end of such items not just between them: [ 1, 2, <- this comma not normally allowed ] { "k1": "v1", "k2": "v2", <- this comma not normally allowed } * shell-style '#'-comments Whenever JSON allows whitespace, shell-style comments are additionally allowed. They are terminated by the first carriage-return or line-feed character, after which more white-space and comments are allowed. [ 1, # this comment not allowed in JSON # neither this one... ] * literal ASCII TAB characters in strings Literal ASCII TAB characters are now allowed in strings (and treated as "\t") in relaxed mode. Despite JSON mandates, that TAB character is substituted for "\t" sequence. [ "Hello\tWorld", "HelloWorld", # literal would not normally be allowed ] * allow_singlequote Single quotes are accepted instead of double quotes. See the "allow_singlequote" option. { "foo":'bar' } { 'foo':"bar" } { 'foo':'bar' } * allow_barekey Accept unquoted object keys instead of with mandatory double quotes. See the "allow_barekey" option. { foo:"bar" } $json = $json->canonical ([$enable]) $enabled = $json->get_canonical If $enable is true (or missing), then the "encode" method will output JSON objects by sorting their keys. This is adding a comparatively high overhead. If $enable is false, then the "encode" method will output key-value pairs in the order Perl stores them (which will likely change between runs of the same script, and can change even within the same run from 5.18 onwards). This option is useful if you want the same data structure to be encoded as the same JSON text (given the same overall settings). If it is disabled, the same hash might be encoded differently even if contains the same data, as key-value pairs have no inherent ordering in Perl. This setting has no effect when decoding JSON texts. This setting has currently no effect on tied hashes. $json = $json->sort_by (undef, 0, 1 or a block) This currently only (un)sets the "canonical" option, and ignores custom sort blocks. This setting has no effect when decoding JSON texts. This setting has currently no effect on tied hashes. $json = $json->escape_slash ([$enable]) $enabled = $json->get_escape_slash According to the JSON Grammar, the *forward slash* character (U+002F) "/" need to be escaped. But by default strings are encoded without escaping slashes in all perl JSON encoders. If $enable is true (or missing), then "encode" will escape slashes, "\/". This setting has no effect when decoding JSON texts. $json = $json->allow_singlequote ([$enable]) $enabled = $json->get_allow_singlequote $json = $json->allow_singlequote([$enable]) If $enable is true (or missing), then "decode" will accept JSON strings quoted by single quotations that are invalid JSON format. $json->allow_singlequote->decode({"foo":'bar'}); $json->allow_singlequote->decode({'foo':"bar"}); $json->allow_singlequote->decode({'foo':'bar'}); This is also enabled with "relaxed". As same as the "relaxed" option, this option may be used to parse application-specific files written by humans. $json = $json->allow_barekey ([$enable]) $enabled = $json->get_allow_barekey $json = $json->allow_barekey([$enable]) If $enable is true (or missing), then "decode" will accept bare keys of JSON object that are invalid JSON format. Same as with the "relaxed" option, this option may be used to parse application-specific files written by humans. $json->allow_barekey->decode('{foo:"bar"}'); $json = $json->allow_bignum ([$enable]) $enabled = $json->get_allow_bignum $json = $json->allow_bignum([$enable]) If $enable is true (or missing), then "decode" will convert the big integer Perl cannot handle as integer into a Math::BigInt object and convert a floating number (any) into a Math::BigFloat. On the contrary, "encode" converts "Math::BigInt" objects and "Math::BigFloat" objects into JSON numbers with "allow_blessed" enable. $json->allow_nonref->allow_blessed->allow_bignum; $bigfloat = $json->decode('2.000000000000000000000000001'); print $json->encode($bigfloat); # => 2.000000000000000000000000001 See "MAPPING" about the normal conversion of JSON number. $json = $json->allow_bigint ([$enable]) This option is obsolete and replaced by allow_bignum. $json = $json->allow_nonref ([$enable]) $enabled = $json->get_allow_nonref If $enable is true (or missing), then the "encode" method can convert a non-reference into its corresponding string, number or null JSON value, which is an extension to RFC4627. Likewise, "decode" will accept those JSON values instead of croaking. If $enable is false, then the "encode" method will croak if it isn't passed an arrayref or hashref, as JSON texts must either be an object or array. Likewise, "decode" will croak if given something that is not a JSON object or array. Example, encode a Perl scalar as JSON value with enabled "allow_nonref", resulting in an invalid JSON text: Cpanel::JSON::XS->new->allow_nonref->encode ("Hello, World!") => "Hello, World!" $json = $json->allow_unknown ([$enable]) $enabled = $json->get_allow_unknown If $enable is true (or missing), then "encode" will *not* throw an exception when it encounters values it cannot represent in JSON (for example, filehandles) but instead will encode a JSON "null" value. Note that blessed objects are not included here and are handled separately by c. If $enable is false (the default), then "encode" will throw an exception when it encounters anything it cannot encode as JSON. This option does not affect "decode" in any way, and it is recommended to leave it off unless you know your communications partner. $json = $json->allow_stringify ([$enable]) $enabled = $json->get_allow_stringify If $enable is true (or missing), then "encode" will stringify the non-object perl value or reference. Note that blessed objects are not included here and are handled separately by "allow_blessed" and "convert_blessed". String references are stringified to the string value, other references as in perl. This option does not affect "decode" in any way. This option is special to this module, it is not supported by other encoders. So it is not recommended to use it. $json = $json->allow_blessed ([$enable]) $enabled = $json->get_allow_blessed If $enable is true (or missing), then the "encode" method will not barf when it encounters a blessed reference. Instead, the value of the convert_blessed option will decide whether "null" ("convert_blessed" disabled or no "TO_JSON" method found) or a representation of the object ("convert_blessed" enabled and "TO_JSON" method found) is being encoded. Has no effect on "decode". If $enable is false (the default), then "encode" will throw an exception when it encounters a blessed object. This setting has no effect on "decode". $json = $json->convert_blessed ([$enable]) $enabled = $json->get_convert_blessed If $enable is true (or missing), then "encode", upon encountering a blessed object, will check for the availability of the "TO_JSON" method on the object's class. If found, it will be called in scalar context and the resulting scalar will be encoded instead of the object. If no "TO_JSON" method is found, a stringification overload method is tried next. If both are not found, the value of "allow_blessed" will decide what to do. The "TO_JSON" method may safely call die if it wants. If "TO_JSON" returns other blessed objects, those will be handled in the same way. "TO_JSON" must take care of not causing an endless recursion cycle (== crash) in this case. The name of "TO_JSON" was chosen because other methods called by the Perl core (== not by the user of the object) are usually in upper case letters and to avoid collisions with any "to_json" function or method. If $enable is false (the default), then "encode" will not consider this type of conversion. This setting has no effect on "decode". $json = $json->allow_tags ([$enable]) $enabled = $json->get_allow_tags See "OBJECT SERIALIZATION" for details. If $enable is true (or missing), then "encode", upon encountering a blessed object, will check for the availability of the "FREEZE" method on the object's class. If found, it will be used to serialize the object into a nonstandard tagged JSON value (that JSON decoders cannot decode). It also causes "decode" to parse such tagged JSON values and deserialize them via a call to the "THAW" method. If $enable is false (the default), then "encode" will not consider this type of conversion, and tagged JSON values will cause a parse error in "decode", as if tags were not part of the grammar. $json = $json->filter_json_object ([$coderef->($hashref)]) When $coderef is specified, it will be called from "decode" each time it decodes a JSON object. The only argument is a reference to the newly-created hash. If the code references returns a single scalar (which need not be a reference), this value (i.e. a copy of that scalar to avoid aliasing) is inserted into the deserialized data structure. If it returns an empty list (NOTE: *not* "undef", which is a valid scalar), the original deserialized hash will be inserted. This setting can slow down decoding considerably. When $coderef is omitted or undefined, any existing callback will be removed and "decode" will not change the deserialized hash in any way. Example, convert all JSON objects into the integer 5: my $js = Cpanel::JSON::XS->new->filter_json_object (sub { 5 }); # returns [5] $js->decode ('[{}]') # throw an exception because allow_nonref is not enabled # so a lone 5 is not allowed. $js->decode ('{"a":1, "b":2}'); $json = $json->filter_json_single_key_object ($key [=> $coderef->($value)]) Works remotely similar to "filter_json_object", but is only called for JSON objects having a single key named $key. This $coderef is called before the one specified via "filter_json_object", if any. It gets passed the single value in the JSON object. If it returns a single value, it will be inserted into the data structure. If it returns nothing (not even "undef" but the empty list), the callback from "filter_json_object" will be called next, as if no single-key callback were specified. If $coderef is omitted or undefined, the corresponding callback will be disabled. There can only ever be one callback for a given key. As this callback gets called less often then the "filter_json_object" one, decoding speed will not usually suffer as much. Therefore, single-key objects make excellent targets to serialize Perl objects into, especially as single-key JSON objects are as close to the type-tagged value concept as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not support this in any way, so you need to make sure your data never looks like a serialized Perl hash. Typical names for the single object key are "__class_whatever__", or "$__dollars_are_rarely_used__$" or "}ugly_brace_placement", or even things like "__class_md5sum(classname)__", to reduce the risk of clashing with real hashes. Example, decode JSON objects of the form "{ "__widget__" => }" into the corresponding $WIDGET{} object: # return whatever is in $WIDGET{5}: Cpanel::JSON::XS ->new ->filter_json_single_key_object (__widget__ => sub { $WIDGET{ $_[0] } }) ->decode ('{"__widget__": 5') # this can be used with a TO_JSON method in some "widget" class # for serialization to json: sub WidgetBase::TO_JSON { my ($self) = @_; unless ($self->{id}) { $self->{id} = ..get..some..id..; $WIDGET{$self->{id}} = $self; } { __widget__ => $self->{id} } } $json = $json->shrink ([$enable]) $enabled = $json->get_shrink Perl usually over-allocates memory a bit when allocating space for strings. This flag optionally resizes strings generated by either "encode" or "decode" to their minimum size possible. This can save memory when your JSON texts are either very very long or you have many short strings. It will also try to downgrade any strings to octet-form if possible: perl stores strings internally either in an encoding called UTF-X or in octet-form. The latter cannot store everything but uses less space in general (and some buggy Perl or C code might even rely on that internal representation being used). The actual definition of what shrink does might change in future versions, but it will always try to save space at the expense of time. If $enable is true (or missing), the string returned by "encode" will be shrunk-to-fit, while all strings generated by "decode" will also be shrunk-to-fit. If $enable is false, then the normal perl allocation algorithms are used. If you work with your data, then this is likely to be faster. In the future, this setting might control other things, such as converting strings that look like integers or floats into integers or floats internally (there is no difference on the Perl level), saving space. $json = $json->max_depth ([$maximum_nesting_depth]) $max_depth = $json->get_max_depth Sets the maximum nesting level (default 512) accepted while encoding or decoding. If a higher nesting level is detected in JSON text or a Perl data structure, then the encoder and decoder will stop and croak at that point. Nesting level is defined by number of hash- or arrayrefs that the encoder needs to traverse to reach a given point or the number of "{" or "[" characters without their matching closing parenthesis crossed to reach a given character in a string. Setting the maximum depth to one disallows any nesting, so that ensures that the object is only a single hash/object or array. If no argument is given, the highest possible setting will be used, which is rarely useful. Note that nesting is implemented by recursion in C. The default value has been chosen to be as large as typical operating systems allow without crashing. See SECURITY CONSIDERATIONS, below, for more info on why this is useful. $json = $json->max_size ([$maximum_string_size]) $max_size = $json->get_max_size Set the maximum length a JSON text may have (in bytes) where decoding is being attempted. The default is 0, meaning no limit. When "decode" is called on a string that is longer then this many bytes, it will not attempt to decode the string but throw an exception. This setting has no effect on "encode" (yet). If no argument is given, the limit check will be deactivated (same as when 0 is specified). See SECURITY CONSIDERATIONS, below, for more info on why this is useful. $json->stringify_infnan ([$infnan_mode = 1]) $infnan_mode = $json->get_stringify_infnan Get or set how Cpanel::JSON::XS encodes "inf" or "nan" for numeric values. "null": infnan_mode = 0. Similar to most JSON modules in other languages. stringified: infnan_mode = 1. As in Mojo::JSON. inf/nan: infnan_mode = 2. As in JSON::XS, and older releases. Produces invalid JSON. $json_text = $json->encode ($perl_scalar) Converts the given Perl data structure (a simple scalar or a reference to a hash or array) to its JSON representation. Simple scalars will be converted into JSON string or number sequences, while references to arrays become JSON arrays and references to hashes become JSON objects. Undefined Perl values (e.g. "undef") become JSON "null" values. Neither "true" nor "false" values will be generated. $perl_scalar = $json->decode ($json_text) The opposite of "encode": expects a JSON text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error. JSON numbers and strings become simple Perl scalars. JSON arrays become Perl arrayrefs and JSON objects become Perl hashrefs. "true" becomes 1, "false" becomes 0 and "null" becomes "undef". ($perl_scalar, $characters) = $json->decode_prefix ($json_text) This works like the "decode" method, but instead of raising an exception when there is trailing garbage after the first JSON object, it will silently stop parsing there and return the number of characters consumed so far. This is useful if your JSON texts are not delimited by an outer protocol and you need to know where the JSON text ends. Cpanel::JSON::XS->new->decode_prefix ("[1] the tail") => ([], 3) $json->to_json ($perl_hash_or_arrayref) Deprecated method for perl 5.8 and newer. Use encode_json instead. $json->from_json ($utf8_encoded_json_text) Deprecated method for perl 5.8 and newer. Use decode_json instead. INCREMENTAL PARSING In some cases, there is the need for incremental parsing of JSON texts. While this module always has to keep both JSON text and resulting Perl data structure in memory at one time, it does allow you to parse a JSON stream incrementally. It does so by accumulating text until it has a full JSON object, which it then can decode. This process is similar to using "decode_prefix" to see if a full JSON object is available, but is much more efficient (and can be implemented with a minimum of method calls). Cpanel::JSON::XS will only attempt to parse the JSON text once it is sure it has enough text to get a decisive result, using a very simple but truly incremental parser. This means that it sometimes won't stop as early as the full parser, for example, it doesn't detect mismatched parentheses. The only thing it guarantees is that it starts decoding as soon as a syntactically valid JSON text has been seen. This means you need to set resource limits (e.g. "max_size") to ensure the parser will stop parsing in the presence if syntax errors. The following methods implement this incremental parser. [void, scalar or list context] = $json->incr_parse ([$string]) This is the central parsing function. It can both append new text and extract objects from the stream accumulated so far (both of these functions are optional). If $string is given, then this string is appended to the already existing JSON fragment stored in the $json object. After that, if the function is called in void context, it will simply return without doing anything further. This can be used to add more text in as many chunks as you want. If the method is called in scalar context, then it will try to extract exactly *one* JSON object. If that is successful, it will return this object, otherwise it will return "undef". If there is a parse error, this method will croak just as "decode" would do (one can then use "incr_skip" to skip the erroneous part). This is the most common way of using the method. And finally, in list context, it will try to extract as many objects from the stream as it can find and return them, or the empty list otherwise. For this to work, there must be no separators between the JSON objects or arrays, instead they must be concatenated back-to-back. If an error occurs, an exception will be raised as in the scalar context case. Note that in this case, any previously-parsed JSON texts will be lost. Example: Parse some JSON arrays/objects in a given string and return them. my @objs = Cpanel::JSON::XS->new->incr_parse ("[5][7][1,2]"); $lvalue_string = $json->incr_text (>5.8 only) This method returns the currently stored JSON fragment as an lvalue, that is, you can manipulate it. This *only* works when a preceding call to "incr_parse" in *scalar context* successfully returned an object, and 2. only with Perl >= 5.8 Under all other circumstances you must not call this function (I mean it. although in simple tests it might actually work, it *will* fail under real world conditions). As a special exception, you can also call this method before having parsed anything. This function is useful in two cases: a) finding the trailing text after a JSON object or b) parsing multiple JSON objects separated by non-JSON text (such as commas). $json->incr_skip This will reset the state of the incremental parser and will remove the parsed text from the input buffer so far. This is useful after "incr_parse" died, in which case the input buffer and incremental parser state is left unchanged, to skip the text parsed so far and to reset the parse state. The difference to "incr_reset" is that only text until the parse error occurred is removed. $json->incr_reset This completely resets the incremental parser, that is, after this call, it will be as if the parser had never parsed anything. This is useful if you want to repeatedly parse JSON objects and want to ignore any trailing data, which means you have to reset the parser after each successful decode. LIMITATIONS All options that affect decoding are supported, except "allow_nonref". The reason for this is that it cannot be made to work sensibly: JSON objects and arrays are self-delimited, i.e. you can concatenate them back to back and still decode them perfectly. This does not hold true for JSON numbers, however. For example, is the string 1 a single JSON number, or is it simply the start of 12? Or is 12 a single JSON number, or the concatenation of 1 and 2? In neither case you can tell, and this is why Cpanel::JSON::XS takes the conservative route and disallows this case. EXAMPLES Some examples will make all this clearer. First, a simple example that works similarly to "decode_prefix": We want to decode the JSON object at the start of a string and identify the portion after the JSON object: my $text = "[1,2,3] hello"; my $json = new Cpanel::JSON::XS; my $obj = $json->incr_parse ($text) or die "expected JSON object or array at beginning of string"; my $tail = $json->incr_text; # $tail now contains " hello" Easy, isn't it? Now for a more complicated example: Imagine a hypothetical protocol where you read some requests from a TCP stream, and each request is a JSON array, without any separation between them (in fact, it is often useful to use newlines as "separators", as these get interpreted as whitespace at the start of the JSON text, which makes it possible to test said protocol with "telnet"...). Here is how you'd do it (it is trivial to write this in an event-based manner): my $json = new Cpanel::JSON::XS; # read some data from the socket while (sysread $socket, my $buf, 4096) { # split and decode as many requests as possible for my $request ($json->incr_parse ($buf)) { # act on the $request } } Another complicated example: Assume you have a string with JSON objects or arrays, all separated by (optional) comma characters (e.g. "[1],[2], [3]"). To parse them, we have to skip the commas between the JSON texts, and here is where the lvalue-ness of "incr_text" comes in useful: my $text = "[1],[2], [3]"; my $json = new Cpanel::JSON::XS; # void context, so no parsing done $json->incr_parse ($text); # now extract as many objects as possible. note the # use of scalar context so incr_text can be called. while (my $obj = $json->incr_parse) { # do something with $obj # now skip the optional comma $json->incr_text =~ s/^ \s* , //x; } Now lets go for a very complex example: Assume that you have a gigantic JSON array-of-objects, many gigabytes in size, and you want to parse it, but you cannot load it into memory fully (this has actually happened in the real world :). Well, you lost, you have to implement your own JSON parser. But Cpanel::JSON::XS can still help you: You implement a (very simple) array parser and let JSON decode the array elements, which are all full JSON objects on their own (this wouldn't work if the array elements could be JSON numbers, for example): my $json = new Cpanel::JSON::XS; # open the monster open my $fh, "incr_parse ($buf); # void context, so no parsing # Exit the loop once we found and removed(!) the initial "[". # In essence, we are (ab-)using the $json object as a simple scalar # we append data to. last if $json->incr_text =~ s/^ \s* \[ //x; } # now we have the skipped the initial "[", so continue # parsing all the elements. for (;;) { # in this loop we read data until we got a single JSON object for (;;) { if (my $obj = $json->incr_parse) { # do something with $obj last; } # add more data sysread $fh, my $buf, 65536 or die "read error: $!"; $json->incr_parse ($buf); # void context, so no parsing } # in this loop we read data until we either found and parsed the # separating "," between elements, or the final "]" for (;;) { # first skip whitespace $json->incr_text =~ s/^\s*//; # if we find "]", we are done if ($json->incr_text =~ s/^\]//) { print "finished.\n"; exit; } # if we find ",", we can continue with the next element if ($json->incr_text =~ s/^,//) { last; } # if we find anything else, we have a parse error! if (length $json->incr_text) { die "parse error near ", $json->incr_text; } # else add more data sysread $fh, my $buf, 65536 or die "read error: $!"; $json->incr_parse ($buf); # void context, so no parsing } This is a complex example, but most of the complexity comes from the fact that we are trying to be correct (bear with me if I am wrong, I never ran the above example :). MAPPING This section describes how Cpanel::JSON::XS maps Perl values to JSON values and vice versa. These mappings are designed to "do the right thing" in most circumstances automatically, preserving round-tripping characteristics (what you put in comes out as something equivalent). For the more enlightened: note that in the following descriptions, lowercase *perl* refers to the Perl interpreter, while uppercase *Perl* refers to the abstract Perl language itself. JSON -> PERL object A JSON object becomes a reference to a hash in Perl. No ordering of object keys is preserved (JSON does not preserve object key ordering itself). array A JSON array becomes a reference to an array in Perl. string A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON are represented by the same codepoints in the Perl string, so no manual decoding is necessary. number A JSON number becomes either an integer, numeric (floating point) or string scalar in perl, depending on its range and any fractional parts. On the Perl level, there is no difference between those as Perl handles all the conversion details, but an integer may take slightly less memory and might represent more values exactly than floating point numbers. If the number consists of digits only, Cpanel::JSON::XS will try to represent it as an integer value. If that fails, it will try to represent it as a numeric (floating point) value if that is possible without loss of precision. Otherwise it will preserve the number as a string value (in which case you lose roundtripping ability, as the JSON number will be re-encoded to a JSON string). Numbers containing a fractional or exponential part will always be represented as numeric (floating point) values, possibly at a loss of precision (in which case you might lose perfect roundtripping ability, but the JSON number will still be re-encoded as a JSON number). Note that precision is not accuracy - binary floating point values cannot represent most decimal fractions exactly, and when converting from and to floating point, "Cpanel::JSON::XS" only guarantees precision up to but not including the least significant bit. true, false These JSON atoms become "Cpanel::JSON::XS::true" and "Cpanel::JSON::XS::false", respectively. They are "JSON::PP::Boolean" objects and are overloaded to act almost exactly like the numbers 1 and 0. You can check whether a scalar is a JSON boolean by using the "Cpanel::JSON::XS::is_bool" function. The other round, from perl to JSON, "!0" which is represented as "yes" becomes "true", and "!1" which is represented as "no" becomes "false". null A JSON null atom becomes "undef" in Perl. shell-style comments ("# *text*") As a nonstandard extension to the JSON syntax that is enabled by the "relaxed" setting, shell-style comments are allowed. They can start anywhere outside strings and go till the end of the line. tagged values ("(*tag*)*value*"). Another nonstandard extension to the JSON syntax, enabled with the "allow_tags" setting, are tagged values. In this implementation, the *tag* must be a perl package/class name encoded as a JSON string, and the *value* must be a JSON array encoding optional constructor arguments. See "OBJECT SERIALIZATION", below, for details. PERL -> JSON The mapping from Perl to JSON is slightly more difficult, as Perl is a truly typeless language, so we can only guess which JSON type is meant by a Perl value. hash references Perl hash references become JSON objects. As there is no inherent ordering in hash keys (or JSON objects), they will usually be encoded in a pseudo-random order that can change between runs of the same program but stays generally the same within a single run of a program. Cpanel::JSON::XS can optionally sort the hash keys (determined by the *canonical* flag), so the same datastructure will serialize to the same JSON text (given same settings and version of Cpanel::JSON::XS), but this incurs a runtime overhead and is only rarely useful, e.g. when you want to compare some JSON text against another for equality. array references Perl array references become JSON arrays. other references Other unblessed references are generally not allowed and will cause an exception to be thrown, except for references to the integers 0 and 1, which get turned into "false" and "true" atoms in JSON. With the option "allow_stringify", you can ignore the exception and return the stringification of the perl value. With the option "allow_unknown", you can ignore the exception and return "null" instead. encode_json [\"x"] # => cannot encode reference to scalar 'SCALAR(0x..)' # unless the scalar is 0 or 1 encode_json [\0, \1] # yields [false,true] allow_stringify->encode_json [\"x"] # yields "x" unlike JSON::PP allow_unknown->encode_json [\"x"] # yields null as in JSON::PP Cpanel::JSON::XS::true, Cpanel::JSON::XS::false These special values become JSON true and JSON false values, respectively. You can also use "\1" and "\0" or "!0" and "!1" directly if you want. encode_json [Cpanel::JSON::XS::true, Cpanel::JSON::XS::true] # yields [false,true] encode_json [!1, !0] # yields [false,true] blessed objects Blessed objects are not directly representable in JSON, but "Cpanel::JSON::XS" allows various optional ways of handling objects. See "OBJECT SERIALIZATION", below, for details. See the "allow_blessed" and "convert_blessed" methods on various options on how to deal with this: basically, you can choose between throwing an exception, encoding the reference as if it weren't blessed, use the objects overloaded stringification method or provide your own serializer method. simple scalars Simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode: Cpanel::JSON::XS will encode undefined scalars or inf/nan as JSON "null" values, scalars that have last been used in a string context before encoding as JSON strings, and anything else as number value: # dump as number encode_json [2] # yields [2] encode_json [-3.0e17] # yields [-3e+17] my $value = 5; encode_json [$value] # yields [5] # used as string, but the two representations are for the same number print $value; encode_json [$value] # yields [5] # used as different string (non-matching dual-var) my $str = '0 but true'; my $num = 1 + $str; encode_json [$num, $str] # yields [1,"0 but true"] # undef becomes null encode_json [undef] # yields [null] # inf or nan becomes null, unless you answered # "Do you want to handle inf/nan as strings" with yes encode_json [9**9**9] # yields [null] You can force the type to be a JSON string by stringifying it: my $x = 3.1; # some variable containing a number "$x"; # stringified $x .= ""; # another, more awkward way to stringify print $x; # perl does it for you, too, quite often You can force the type to be a JSON number by numifying it: my $x = "3"; # some variable containing a string $x += 0; # numify it, ensuring it will be dumped as a number $x *= 1; # same thing, the choice is yours. Note that numerical precision has the same meaning as under Perl (so binary to decimal conversion follows the same rules as in Perl, which can differ to other languages). Also, your perl interpreter might expose extensions to the floating point numbers of your platform, such as infinities or NaN's - these cannot be represented in JSON, and thus null is returned instead. Optionally you can configure it to stringify inf and nan values. OBJECT SERIALIZATION As JSON cannot directly represent Perl objects, you have to choose between a pure JSON representation (without the ability to deserialize the object automatically again), and a nonstandard extension to the JSON syntax, tagged values. SERIALIZATION What happens when "Cpanel::JSON::XS" encounters a Perl object depends on the "allow_blessed", "convert_blessed" and "allow_tags" settings, which are used in this order: 1. "allow_tags" is enabled and the object has a "FREEZE" method. In this case, "Cpanel::JSON::XS" uses the Types::Serialiser object serialization protocol to create a tagged JSON value, using a nonstandard extension to the JSON syntax. This works by invoking the "FREEZE" method on the object, with the first argument being the object to serialize, and the second argument being the constant string "JSON" to distinguish it from other serializers. The "FREEZE" method can return any number of values (i.e. zero or more). These values and the paclkage/classname of the object will then be encoded as a tagged JSON value in the following format: ("classname")[FREEZE return values...] e.g.: ("URI")["http://www.google.com/"] ("MyDate")[2013,10,29] ("ImageData::JPEG")["Z3...VlCg=="] For example, the hypothetical "My::Object" "FREEZE" method might use the objects "type" and "id" members to encode the object: sub My::Object::FREEZE { my ($self, $serializer) = @_; ($self->{type}, $self->{id}) } 2. "convert_blessed" is enabled and the object has a "TO_JSON" method. In this case, the "TO_JSON" method of the object is invoked in scalar context. It must return a single scalar that can be directly encoded into JSON. This scalar replaces the object in the JSON text. For example, the following "TO_JSON" method will convert all URI objects to JSON strings when serialized. The fact that these values originally were URI objects is lost. sub URI::TO_JSON { my ($uri) = @_; $uri->as_string } 2. "convert_blessed" is enabled and the object has a stringification overload. In this case, the overloaded "" method of the object is invoked in scalar context. It must return a single scalar that can be directly encoded into JSON. This scalar replaces the object in the JSON text. For example, the following "" method will convert all URI objects to JSON strings when serialized. The fact that these values originally were URI objects is lost. package URI; use overload '""' => sub { shift->as_string }; 3. "allow_blessed" is enabled. The object will be serialized as a JSON null value. 4. none of the above If none of the settings are enabled or the respective methods are missing, "Cpanel::JSON::XS" throws an exception. DESERIALIZATION For deserialization there are only two cases to consider: either nonstandard tagging was used, in which case "allow_tags" decides, or objects cannot be automatically be deserialized, in which case you can use postprocessing or the "filter_json_object" or "filter_json_single_key_object" callbacks to get some real objects our of your JSON. This section only considers the tagged value case: I a tagged JSON object is encountered during decoding and "allow_tags" is disabled, a parse error will result (as if tagged values were not part of the grammar). If "allow_tags" is enabled, "Cpanel::JSON::XS" will look up the "THAW" method of the package/classname used during serialization (it will not attempt to load the package as a Perl module). If there is no such method, the decoding will fail with an error. Otherwise, the "THAW" method is invoked with the classname as first argument, the constant string "JSON" as second argument, and all the values from the JSON array (the values originally returned by the "FREEZE" method) as remaining arguments. The method must then return the object. While technically you can return any Perl scalar, you might have to enable the "enable_nonref" setting to make that work in all cases, so better return an actual blessed reference. As an example, let's implement a "THAW" function that regenerates the "My::Object" from the "FREEZE" example earlier: sub My::Object::THAW { my ($class, $serializer, $type, $id) = @_; $class->new (type => $type, id => $id) } See the "SECURITY CONSIDERATIONS" section below. Allowing external json objects being deserialized to perl objects is usually a very bad idea. ENCODING/CODESET FLAG NOTES The interested reader might have seen a number of flags that signify encodings or codesets - "utf8", "latin1", "binary" and "ascii". There seems to be some confusion on what these do, so here is a short comparison: "utf8" controls whether the JSON text created by "encode" (and expected by "decode") is UTF-8 encoded or not, while "latin1" and "ascii" only control whether "encode" escapes character values outside their respective codeset range. Neither of these flags conflict with each other, although some combinations make less sense than others. Care has been taken to make all flags symmetrical with respect to "encode" and "decode", that is, texts encoded with any combination of these flag values will be correctly decoded when the same flags are used - in general, if you use different flag settings while encoding vs. when decoding you likely have a bug somewhere. Below comes a verbose discussion of these flags. Note that a "codeset" is simply an abstract set of character-codepoint pairs, while an encoding takes those codepoint numbers and *encodes* them, in our case into octets. Unicode is (among other things) a codeset, UTF-8 is an encoding, and ISO-8859-1 (= latin 1) and ASCII are both codesets *and* encodings at the same time, which can be confusing. "utf8" flag disabled When "utf8" is disabled (the default), then "encode"/"decode" generate and expect Unicode strings, that is, characters with high ordinal Unicode values (> 255) will be encoded as such characters, and likewise such characters are decoded as-is, no changes to them will be done, except "(re-)interpreting" them as Unicode codepoints or Unicode characters, respectively (to Perl, these are the same thing in strings unless you do funny/weird/dumb stuff). This is useful when you want to do the encoding yourself (e.g. when you want to have UTF-16 encoded JSON texts) or when some other layer does the encoding for you (for example, when printing to a terminal using a filehandle that transparently encodes to UTF-8 you certainly do NOT want to UTF-8 encode your data first and have Perl encode it another time). "utf8" flag enabled If the "utf8"-flag is enabled, "encode"/"decode" will encode all characters using the corresponding UTF-8 multi-byte sequence, and will expect your input strings to be encoded as UTF-8, that is, no "character" of the input string must have any value > 255, as UTF-8 does not allow that. The "utf8" flag therefore switches between two modes: disabled means you will get a Unicode string in Perl, enabled means you get an UTF-8 encoded octet/binary string in Perl. "latin1", "binary" or "ascii" flags enabled With "latin1" (or "ascii") enabled, "encode" will escape characters with ordinal values > 255 (> 127 with "ascii") and encode the remaining characters as specified by the "utf8" flag. With "binary" enabled, ordinal values > 255 are illegal. If "utf8" is disabled, then the result is also correctly encoded in those character sets (as both are proper subsets of Unicode, meaning that a Unicode string with all character values < 256 is the same thing as a ISO-8859-1 string, and a Unicode string with all character values < 128 is the same thing as an ASCII string in Perl). If "utf8" is enabled, you still get a correct UTF-8-encoded string, regardless of these flags, just some more characters will be escaped using "\uXXXX" then before. Note that ISO-8859-1-*encoded* strings are not compatible with UTF-8 encoding, while ASCII-encoded strings are. That is because the ISO-8859-1 encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 *codeset* being a subset of Unicode), while ASCII is. Surprisingly, "decode" will ignore these flags and so treat all input values as governed by the "utf8" flag. If it is disabled, this allows you to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings. So neither "latin1", "binary" nor "ascii" are incompatible with the "utf8" flag - they only govern when the JSON output engine escapes a character or not. The main use for "latin1" or "binary" is to relatively efficiently store binary data as JSON, at the expense of breaking compatibility with most JSON decoders. The main use for "ascii" is to force the output to not contain characters with values > 127, which means you can interpret the resulting string as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and 8-bit-encoding, and still get the same data structure back. This is useful when your channel for JSON transfer is not 8-bit clean or the encoding might be mangled in between (e.g. in mail), and works because ASCII is a proper subset of most 8-bit and multibyte encodings in use in the world. JSON and ECMAscript JSON syntax is based on how literals are represented in javascript (the not-standardized predecessor of ECMAscript) which is presumably why it is called "JavaScript Object Notation". However, JSON is not a subset (and also not a superset of course) of ECMAscript (the standard) or javascript (whatever browsers actually implement). If you want to use javascript's "eval" function to "parse" JSON, you might run into parse errors for valid JSON texts, or the resulting data structure might not be queryable: One of the problems is that U+2028 and U+2029 are valid characters inside JSON strings, but are not allowed in ECMAscript string literals, so the following Perl fragment will not output something that can be guaranteed to be parsable by javascript's "eval": use Cpanel::JSON::XS; print encode_json [chr 0x2028]; The right fix for this is to use a proper JSON parser in your javascript programs, and not rely on "eval" (see for example Douglas Crockford's json2.js parser). If this is not an option, you can, as a stop-gap measure, simply encode to ASCII-only JSON: use Cpanel::JSON::XS; print Cpanel::JSON::XS->new->ascii->encode ([chr 0x2028]); Note that this will enlarge the resulting JSON text quite a bit if you have many non-ASCII characters. You might be tempted to run some regexes to only escape U+2028 and U+2029, e.g.: # DO NOT USE THIS! my $json = Cpanel::JSON::XS->new->utf8->encode ([chr 0x2028]); $json =~ s/\xe2\x80\xa8/\\u2028/g; # escape U+2028 $json =~ s/\xe2\x80\xa9/\\u2029/g; # escape U+2029 print $json; Note that *this is a bad idea*: the above only works for U+2028 and U+2029 and thus only for fully ECMAscript-compliant parsers. Many existing javascript implementations, however, have issues with other characters as well - using "eval" naively simply *will* cause problems. Another problem is that some javascript implementations reserve some property names for their own purposes (which probably makes them non-ECMAscript-compliant). For example, Iceweasel reserves the "__proto__" property name for its own purposes. If that is a problem, you could parse try to filter the resulting JSON output for these property strings, e.g.: $json =~ s/"__proto__"\s*:/"__proto__renamed":/g; This works because "__proto__" is not valid outside of strings, so every occurrence of ""__proto__"\s*:" must be a string used as property name. If you know of other incompatibilities, please let me know. JSON and YAML You often hear that JSON is a subset of YAML. *in general, there is no way to configure JSON::XS to output a data structure as valid YAML* that works in all cases. If you really must use Cpanel::JSON::XS to generate YAML, you should use this algorithm (subject to change in future versions): my $to_yaml = Cpanel::JSON::XS->new->utf8->space_after (1); my $yaml = $to_yaml->encode ($ref) . "\n"; This will *usually* generate JSON texts that also parse as valid YAML. SPEED It seems that JSON::XS is surprisingly fast, as shown in the following tables. They have been generated with the help of the "eg/bench" program in the JSON::XS distribution, to make it easy to compare on your own system. JSON::XS is with Data::MessagePack and Sereal one of the fastest serializers, because JSON and JSON::XS do not support backrefs (no graph structures), only trees. Storable supports backrefs, i.e. graphs. Data::MessagePack encodes its data binary (as Storable) and supports only very simple subset of JSON. First comes a comparison between various modules using a very short single-line JSON string (also available at ). {"method": "handleMessage", "params": ["user1", "we were just talking"], "id": null, "array":[1,11,234,-5,1e5,1e7, 1, 0]} It shows the number of encodes/decodes per second (JSON::XS uses the functional interface, while Cpanel::JSON::XS/2 uses the OO interface with pretty-printing and hash key sorting enabled, Cpanel::JSON::XS/3 enables shrink. JSON::DWIW/DS uses the deserialize function, while JSON::DWIW::FJ uses the from_json method). Higher is better: module | encode | decode | --------------|------------|------------| JSON::DWIW/DS | 86302.551 | 102300.098 | JSON::DWIW/FJ | 86302.551 | 75983.768 | JSON::PP | 15827.562 | 6638.658 | JSON::Syck | 63358.066 | 47662.545 | JSON::XS | 511500.488 | 511500.488 | JSON::XS/2 | 291271.111 | 388361.481 | JSON::XS/3 | 361577.931 | 361577.931 | Storable | 66788.280 | 265462.278 | --------------+------------+------------+ That is, JSON::XS is almost six times faster than JSON::DWIW on encoding, about five times faster on decoding, and over thirty to seventy times faster than JSON's pure perl implementation. It also compares favourably to Storable for small amounts of data. Using a longer test string (roughly 18KB, generated from Yahoo! Locals search API (). module | encode | decode | --------------|------------|------------| JSON::DWIW/DS | 1647.927 | 2673.916 | JSON::DWIW/FJ | 1630.249 | 2596.128 | JSON::PP | 400.640 | 62.311 | JSON::Syck | 1481.040 | 1524.869 | JSON::XS | 20661.596 | 9541.183 | JSON::XS/2 | 10683.403 | 9416.938 | JSON::XS/3 | 20661.596 | 9400.054 | Storable | 19765.806 | 10000.725 | --------------+------------+------------+ Again, JSON::XS leads by far (except for Storable which non-surprisingly decodes a bit faster). On large strings containing lots of high Unicode characters, some modules (such as JSON::PC) seem to decode faster than JSON::XS, but the result will be broken due to missing (or wrong) Unicode handling. Others refuse to decode or encode properly, so it was impossible to prepare a fair comparison table for that case. For updated graphs see INTEROP with JSON and JSON::XS and other JSON modules JSON-XS-3.01 broke interoperability with JSON-2.90 with booleans. See JSON. Cpanel::JSON::XS needs to know the JSON and JSON::XS versions to be able work with those objects, especially when encoding a booleans like "{"is_true":true}". So you need to load these modules before. true/false overloading and boolean representations are supported. JSON::XS and JSON::PP representations are accepted and older JSON::XS accepts Cpanel::JSON::XS booleans. All JSON modules JSON, JSON, PP, JSON::XS, Cpanel::JSON::XS produce JSON::PP::Boolean objects, just Mojo and JSON::YAJL not. Mojo produces Mojo::JSON::_Bool and JSON::YAJL::Parser just an unblessed IV. Cpanel::JSON::XS accepts JSON::PP::Boolean and Mojo::JSON::_Bool objects as booleans. I cannot think of any reason to still use JSON::XS anymore. SECURITY CONSIDERATIONS JSON::XS is not only fast, JSON is generally the most secure serializing format, because it is the only one besides Data::MessagePack, which does not deserialize objects per default. For all languages, not just perl. The binary variant BSON (MongoDB) does more but is unsafe. It is trivial for any attacker to create such serialized objects in JSON and trick perl into expanding them, thereby triggering certain methods. Watch for an exploit demo for "CVE-2015-1592 SixApart MovableType Storable Perl Code Execution" for a deserializer which expands objects. Deserializing even coderefs (methods, functions) or external data would be considered the most dangerous. Security relevant overview of serializers regarding deserializing objects by default: Objects Coderefs External Data Data::Dumper YES YES YES Storable YES NO (def) NO Sereal YES NO NO YAML YES NO NO B::C YES YES YES B::Bytecode YES YES YES BSON YES YES NO JSON::SL YES NO YES JSON NO (def) NO NO Data::MessagePack NO NO NO XML NO NO YES Pickle YES YES YES PHP Deserialize YES NO NO When you are using JSON in a protocol, talking to untrusted potentially hostile creatures requires relatively few measures. First of all, your JSON decoder should be secure, that is, should not have any buffer overflows. Obviously, this module should ensure that. Second, you need to avoid resource-starving attacks. That means you should limit the size of JSON texts you accept, or make sure then when your resources run out, that's just fine (e.g. by using a separate process that can crash safely). The size of a JSON text in octets or characters is usually a good indication of the size of the resources required to decode it into a Perl structure. While JSON::XS can check the size of the JSON text, it might be too late when you already have it in memory, so you might want to check the size before you accept the string. Third, Cpanel::JSON::XS recurses using the C stack when decoding objects and arrays. The C stack is a limited resource: for instance, on my amd64 machine with 8MB of stack size I can decode around 180k nested arrays but only 14k nested JSON objects (due to perl itself recursing deeply on croak to free the temporary). If that is exceeded, the program crashes. To be conservative, the default nesting limit is set to 512. If your process has a smaller stack, you should adjust this setting accordingly with the "max_depth" method. Also keep in mind that Cpanel::JSON::XS might leak contents of your Perl data structures in its error messages, so when you serialize sensitive information you might want to make sure that exceptions thrown by JSON::XS will not end up in front of untrusted eyes. If you are using Cpanel::JSON::XS to return packets to consumption by JavaScript scripts in a browser you should have a look at to see whether you are vulnerable to some common attack vectors (which really are browser design bugs, but it is still you who will have to deal with it, as major browser developers care only for features, not about getting security right). You might also want to also look at Mojo::JSON special escape rules to prevent from XSS attacks. THREADS Cpanel::JSON::XS has proper ithreads support, unlike JSON::XS. If you encounter any bugs with thread support please report them. BUGS While the goal of the Cpanel::JSON::XS module is to be correct, that unfortunately does not mean it's bug-free, only that the author thinks its design is bug-free. If you keep reporting bugs and tests they will be fixed swiftly, though. Since the JSON::XS author refuses to use a public bugtracker and prefers private emails, we've setup a tracker at RT, so you might want to report any issues twice. Once in private to MLEHMANN to be fixed in JSON::XS and one to our the public tracker. Issues fixed by JSON::XS with a new release will also be backported to Cpanel::JSON::XS and 5.6.2, as long as cPanel relies on 5.6.2 and Cpanel::JSON::XS as our serializer of choice. LICENSE This module is available under the same licences as perl, the Artistic license and the GPL. SEE ALSO The cpanel_json_xs command line utility for quick experiments. JSON, JSON::XS, JSON::MaybeXS, Mojo::JSON, Mojo::JSON::MaybeXS, JSON::SL, JSON::DWIW, JSON::YAJL, JSON::Any, Test::JSON, Locale::Wolowitz, AUTHOR Marc Lehmann , http://home.schmorp.de/ Reini Urban , http://cpanel.net/ MAINTAINER Reini Urban Cpanel-JSON-XS-3.0210/SIGNATURE0000644000076500001200000001231112630027164014521 0ustar rurbanadminThis file contains message digests of all files listed in MANIFEST, signed via the Module::Signature module, version 0.79. To verify the content in this distribution, first make sure you have Module::Signature installed, then type: % cpansign -v It will check each file's integrity, as well as the signature's validity. If "==> Signature verified OK! <==" is not displayed, the distribution may already have been compromised, and you should not run its Makefile.PL or Build.PL. -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 SHA1 be3d9d0a89cb8ec853b170eb93cbd0abfc4edca2 .travis.yml SHA1 9a56f3b919dfc8fced3803e165a2e38de62646e5 COPYING SHA1 2280546ea2461d3be546df7dc272183b9c48183c Changes SHA1 3bf42be051c399e70f2b06cdfc089237e3ca9fa9 MANIFEST SHA1 0ef2466c294aa2e1cee891db1494e83c9d1ebe84 META.json SHA1 fe31cc3af19925a7745889d151df57a22c84087a META.yml SHA1 90a51c05087f4e3eba0714a4c6ccf27d6eb0bd82 Makefile.PL SHA1 267adbbc2a9e9767bafed47998540d1872287df3 README SHA1 d766e9e8bff794b4f6e2877f977d09b890c0d99e XS.pm SHA1 ffdb901a580893087679ca2fac4873e1a88f1023 XS.xs SHA1 27b0bc7e0cd6fe90876fb3d285065c6a07cca028 XS/Boolean.pm SHA1 de7ac568367689ba02ccc53a023d584837682f57 bin/cpanel_json_xs SHA1 ea72bbe602baaabdd0004ef1d7e7cc3334b42bb4 eg/bench SHA1 d169c475eede0a30a9935619fec7352deeabc8d5 ppport.h SHA1 f7101031fd3fde35fe2421a07ab6cee8a822c00c t/00_load.t SHA1 804042342d099ca069f83ac31df695a025fd9287 t/01_utf8.t SHA1 9cf542e0bf68c90749420c7d07d7be80e1860592 t/02_error.t SHA1 eabd83358318ba4c810ad709f7fe9b604cbbf3b2 t/03_types.t SHA1 d876bdffc381f4f67ec90f9c331e3ec2138946e2 t/04_dwiw_encode.t SHA1 94b1130a9b760102e0a24ad518f1e7439ef9122c t/05_dwiw_decode.t SHA1 d8c75d0fc7061469eba29275eb366b593c156f7d t/06_pc_pretty.t SHA1 f184df03869dc2baba2daa8d5c436c3996601607 t/07_pc_esc.t SHA1 18dc9908153d71debc18afd777983819f5ecce9a t/08_pc_base.t SHA1 379ba4aed1c0f88e2ea0b29c35b2bcf5500cff61 t/08_pc_base_nv.t SHA1 94b5a3460023550b79b1d325016c951d9cb99fa1 t/09_pc_extra_number.t SHA1 33fbbc0d6441e41a9e0e62d032784b9731c61b98 t/104_sortby.t SHA1 b2acf0c8828914358ee64a653c670473a96ca6db t/105_esc_slash.t SHA1 5141a64abb4a774b32123a11fc65952493f3dead t/106_allow_barekey.t SHA1 8acd897541f68aaa64668ed42f94af875d86c9e4 t/107_allow_singlequote.t SHA1 446e9e23fbb26aca73c0c1cb168c6c31a68c9fb8 t/108_decode.t SHA1 d4d774595e581777fb13219a211c819c1d2f8575 t/109_encode.t SHA1 849b88cb5f17ca6c2324c78e1c4cb1d7857caccb t/10_pc_keysort.t SHA1 4a1e536ea9f70f514657519358a9ed80c9c378fb t/110_bignum.t SHA1 b007b686bb590e5eed3976edc78310437ae169d4 t/112_upgrade.t SHA1 01a0a0644343059c7185cb0b3b00b869d5211e1d t/113_overloaded_eq.t SHA1 bcd500ccfc0cfb65c3ce4a4fa101ce8f72b5450d t/114_decode_prefix.t SHA1 eb050780996f1e428c87bf6375415ca4c863cbb2 t/115_tie_ixhash.t SHA1 3477b0490b8666e451ac15df97f9f35d72c946b1 t/116_incr_parse_fixed.t SHA1 55e868962b071e2b0eed29c29bbc2308f5cdada6 t/117_numbers.t SHA1 45c400009dbe193dbd6f97fdd87f802a62d35b69 t/11_pc_expo.t SHA1 477cdec7699e931fcc93ea7757f6e63af83ef1cb t/12_blessed.t SHA1 4d553fd6b5e4486f087babff2946e0cb4b2c38fb t/13_limit.t SHA1 2b843abe875bf080d0c949663e32105a13c38122 t/14_latin1.t SHA1 6bc697086f8012be7df967738b560d188a775bcd t/15_prefix.t SHA1 f213614d8ac78feb75464c5c1f1b7ac57530a047 t/16_tied.t SHA1 2b3f68860fc876e1b998124dc3695300bf5bf7bd t/17_relaxed.t SHA1 1523ef12859072ba900344df5f1a8439c74fbad2 t/18_json_checker.t SHA1 33231a52e12866a61c405496947827485ff2a811 t/19_incr.t SHA1 8f266979e62b50271f353e5e6905e52d9038834b t/20_faihu.t SHA1 16d67e7b9a2b721ee2487e408b7c57b13fca81a5 t/20_unknown.t SHA1 1d9c81e5dfc27ff7f790354ce22af335cefe09c2 t/21_evans.t SHA1 3d155f37e687f929bd0cae767dc2dbf1993b73c9 t/22_comment_at_eof.t SHA1 1ffb0242c800720c565a9e148e184bfa9d54b1c4 t/23_array_ctx.t SHA1 2d2ccc7877250f80755a74acd0c3c2f21e606aae t/24_freeze_recursion.t SHA1 de63833eb7d922d21339a210680ebf84508b987a t/25_boolean.t SHA1 ded6191143511074b0cfa5c7ff990e0cbaa11ff9 t/52_object.t SHA1 292cb103dae404294cb77c68e3f28a1239f603b9 t/53_readonly.t SHA1 cf201da353d9930435463aee512fa7dccbad96df t/54_stringify.t SHA1 f08d2ec9499dc0d0e5ede5691c75b865f466b69c t/55_modifiable.t SHA1 7ad4a15bfdec5bbd757a48a4670f0275fb2ffd71 t/96_interop.t SHA1 2a644dd9f32ec6e634dae64e83a7605b146ea44a t/96_mojo.t SHA1 3291c73ec3a19df551d0fff59695153616fc982a t/97_unshare_hek.t SHA1 1bf6336a76101f747b84c35cca38c4e8bacb9224 t/98_56only.t SHA1 e5e4ea9e68154f9adb4e5e19a86c96efb1704d02 t/99_binary.t SHA1 e6078e2fc5c375d45498494bb91487834601a189 t/_unicode_handling.pm SHA1 40520e9823ae0ced03c40d113fd41f16973cbe11 t/z_kwalitee.t SHA1 6dfd7f5112f80b65e84916c780a0b1a71aad32dc t/z_leaktrace.t SHA1 e3259ac6c4bd7f3349cf6f2ff829827483bc749d t/z_meta.t SHA1 741e9e8bf600c7f7441794fe49ea8904cfd4bf58 t/z_perl_minimum_version.t SHA1 d91cc1b39fcb1dbf23c11ebb5885cfaaeb2c3a50 t/z_pod-coverage.t SHA1 2eb526b1649c6306df677d7ae63433856b672476 t/z_pod-spell-mistakes.t SHA1 0e1a7a3cb4aa3db01909bac539ee08f4f369acb0 t/z_pod-spelling.t SHA1 c8aa3903d3aba84c19bbd94d677620c758fa07d5 t/z_pod.t SHA1 3b92cafada1b683bbf03593d22eb40671e744bc7 t/zero-mojibake.t SHA1 8ad74139741a687b63c14bc6b4ae109b556f9af7 typemap -----BEGIN PGP SIGNATURE----- Version: GnuPG v1 iEYEARECAAYFAlZgLm8ACgkQmm2SYo/9yUKvXwCfatC6yc4aTJffePwzT4WnTDZn kNIAn0WUSVrtXnXg9Oc53cgjZWmA6zYw =ApC0 -----END PGP SIGNATURE----- Cpanel-JSON-XS-3.0210/t/0000755000076500001200000000000012630027156013503 5ustar rurbanadminCpanel-JSON-XS-3.0210/t/00_load.t0000644000076500001200000000017612463231643015114 0ustar rurbanadminBEGIN { $| = 1; print "1..1\n"; } END {print "not ok 1\n" unless $loaded;} use Cpanel::JSON::XS; $loaded = 1; print "ok 1\n"; Cpanel-JSON-XS-3.0210/t/01_utf8.t0000644000076500001200000000406112612203156015053 0ustar rurbanadminuse Test::More tests => 13; use utf8; use Cpanel::JSON::XS; is(Cpanel::JSON::XS->new->allow_nonref (1)->utf8 (1)->encode ("ü"), "\"\xc3\xbc\""); is(Cpanel::JSON::XS->new->allow_nonref (1)->encode ("ü"), "\"ü\""); is(Cpanel::JSON::XS->new->allow_nonref (1)->ascii (1)->utf8 (1)->encode (chr 0x8000), '"\u8000"'); is(Cpanel::JSON::XS->new->allow_nonref (1)->ascii (1)->utf8 (1)->pretty (1)->encode (chr 0x10402), "\"\\ud801\\udc02\"\n"); SKIP: { skip "5.6", 1 if $] < 5.008; eval { Cpanel::JSON::XS->new->allow_nonref (1)->utf8 (1)->decode ('"ü"') }; like $@, qr/malformed UTF-8/; } is(Cpanel::JSON::XS->new->allow_nonref (1)->decode ('"ü"'), "ü"); is(Cpanel::JSON::XS->new->allow_nonref (1)->decode ('"\u00fc"'), "ü"); is(Cpanel::JSON::XS->new->allow_nonref (1)->decode ('"\ud801\udc02' . "\x{10204}\""), "\x{10402}\x{10204}"); is(Cpanel::JSON::XS->new->allow_nonref (1)->decode ('"\"\n\\\\\r\t\f\b"'), "\"\012\\\015\011\014\010"); my $love = $] < 5.008 ? "I \342\235\244 perl" : "I ❤ perl"; is(Cpanel::JSON::XS->new->ascii->encode ([$love]), $] < 5.008 ? '["I \u00e2\u009d\u00a4 perl"]' : '["I \u2764 perl"]', 'utf8 enc ascii'); is(Cpanel::JSON::XS->new->latin1->encode ([$love]), $] < 5.008 ? "[\"I \342\235\244 perl\"]" : '["I \u2764 perl"]', 'utf8 enc latin1'); SKIP: { skip "5.6", 1 if $] < 5.008; require Encode; # [RT #84244] wrong complaint: JSON::XS double encodes to ["I ❤ perl"] # and with utf8 triple encodes it to ["I ❤ perl"] if ($Encode::VERSION < 2.40 or $Encode::VERSION >= 2.54) { # Encode stricter check: Cannot decode string with wide characters # see also http://stackoverflow.com/questions/12994100/perl-encode-pm-cannot-decode-string-with-wide-character $love = "I \342\235\244 perl"; } my $s = Encode::decode_utf8($love); # User tries to double decode wide-char to unicode with Encode is(Cpanel::JSON::XS->new->utf8->encode ([$s]), "[\"I \342\235\244 perl\"]", 'utf8 enc utf8 [RT #84244]'); } is(Cpanel::JSON::XS->new->binary->encode ([$love]), '["I \xe2\x9d\xa4 perl"]', 'utf8 enc binary'); Cpanel-JSON-XS-3.0210/t/02_error.t0000644000076500001200000000623612625605705015337 0ustar rurbanadminuse Test::More tests => 36; use utf8; use Cpanel::JSON::XS; no warnings; eval { Cpanel::JSON::XS->new->encode ([\-1]) }; ok $@ =~ /cannot encode reference/; eval { Cpanel::JSON::XS->new->encode ([\undef]) }; ok $@ =~ /cannot encode reference/; eval { Cpanel::JSON::XS->new->encode ([\2]) }; ok $@ =~ /cannot encode reference/; eval { Cpanel::JSON::XS->new->encode ([\{}]) }; ok $@ =~ /cannot encode reference/; eval { Cpanel::JSON::XS->new->encode ([\[]]) }; ok $@ =~ /cannot encode reference/; eval { Cpanel::JSON::XS->new->encode ([\\1]) }; ok $@ =~ /cannot encode reference/; eval { $x = Cpanel::JSON::XS->new->ascii->decode ('croak') }; ok $@ =~ /malformed JSON/, $@; SKIP: { skip "5.6 utf8 mb", 17 if $] < 5.008; eval { Cpanel::JSON::XS->new->allow_nonref (1)->decode ('"\u1234\udc00"') }; ok $@ =~ /missing high /; eval { Cpanel::JSON::XS->new->allow_nonref->decode ('"\ud800"') }; ok $@ =~ /missing low /; eval { Cpanel::JSON::XS->new->allow_nonref (1)->decode ('"\ud800\u1234"') }; ok $@ =~ /surrogate pair /; eval { Cpanel::JSON::XS->new->decode ('null') }; ok $@ =~ /allow_nonref/; eval { Cpanel::JSON::XS->new->allow_nonref (1)->decode ('+0') }; ok $@ =~ /malformed/; eval { Cpanel::JSON::XS->new->allow_nonref->decode ('.2') }; ok $@ =~ /malformed/; eval { Cpanel::JSON::XS->new->allow_nonref (1)->decode ('bare') }; ok $@ =~ /malformed/; eval { Cpanel::JSON::XS->new->allow_nonref->decode ('naughty') }; ok $@ =~ /null/; eval { Cpanel::JSON::XS->new->allow_nonref (1)->decode ('01') }; ok $@ =~ /leading zero/; eval { Cpanel::JSON::XS->new->allow_nonref->decode ('00') }; ok $@ =~ /leading zero/; eval { Cpanel::JSON::XS->new->allow_nonref (1)->decode ('-0.') }; ok $@ =~ /decimal point/; eval { Cpanel::JSON::XS->new->allow_nonref->decode ('-0e') }; ok $@ =~ /exp sign/; eval { Cpanel::JSON::XS->new->allow_nonref (1)->decode ('-e+1') }; ok $@ =~ /initial minus/; eval { Cpanel::JSON::XS->new->allow_nonref->decode ("\"\n\"") }; ok $@ =~ /invalid character/; eval { Cpanel::JSON::XS->new->allow_nonref (1)->decode ("\"\x01\"") }; ok $@ =~ /invalid character/; eval { decode_json ("[\"\xa0]") }; ok $@ =~ /malformed.*character/; eval { decode_json ("[\"\xa0\"]") }; ok $@ =~ /malformed.*character/; } eval { Cpanel::JSON::XS->new->decode ('[5') }; ok $@ =~ /parsing array/; eval { Cpanel::JSON::XS->new->decode ('{"5"') }; ok $@ =~ /':' expected/; eval { Cpanel::JSON::XS->new->decode ('{"5":null') }; ok $@ =~ /parsing object/; eval { Cpanel::JSON::XS->new->decode (undef) }; ok $@ =~ /malformed/; eval { Cpanel::JSON::XS->new->decode (\5) }; ok !!$@; # Can't coerce readonly eval { Cpanel::JSON::XS->new->decode ([]) }; ok $@ =~ /malformed/; eval { Cpanel::JSON::XS->new->decode (\*STDERR) }; ok $@ =~ /malformed/; eval { Cpanel::JSON::XS->new->decode (*STDERR) }; ok !!$@; # cannot coerce GLOB # RFC 7159: missing optional 2nd allow_nonref arg eval { decode_json ("null") }; ok $@ =~ /JSON text must be an object or array/, "null"; eval { decode_json ("true") }; ok $@ =~ /JSON text must be an object or array/, "true $@"; eval { decode_json ("false") }; ok $@ =~ /JSON text must be an object or array/, "false $@"; eval { decode_json ("1") }; ok $@ =~ /JSON text must be an object or array/, "wrong 1"; Cpanel-JSON-XS-3.0210/t/03_types.t0000644000076500001200000000632012625605705015345 0ustar rurbanadminBEGIN { $| = 1; print "1..84\n"; } use utf8; use Cpanel::JSON::XS; our $test; sub ok($;$) { print $_[0] ? "" : "not ", "ok ", ++$test; print @_ > 1 ? " # $_[1]\n" : "\n"; } ok (!defined Cpanel::JSON::XS->new->allow_nonref->decode ('null')); my $null = Cpanel::JSON::XS->new->allow_nonref->decode ('null'); my $true = Cpanel::JSON::XS->new->allow_nonref->decode ('true'); my $false = Cpanel::JSON::XS->new->allow_nonref->decode ('false'); ok ($true == 1, sprintf("true: numified %d", 0+$true)); ok ($false == 0, sprintf("false: numified %d", 0+$false)); ok (Cpanel::JSON::XS::is_bool $true); ok ($false == !$true); ok (Cpanel::JSON::XS::is_bool $false); ok ($false eq "0", "false: eq $false"); ok ($true eq "true", "true: eq $true"); ok ("$false" eq "0", "false: stringified $false eq 0"); #ok ("$false" eq "false", "false: stringified $false eq false"); #ok ("$true" eq "1", "true: stringified $true eq 1"); ok ("$true" eq "true", "true: stringified $true"); { my $FH; my $fn = "tmp_$$"; open $FH, ">", $fn; print $FH "$false$true\n"; # printed upstream as "0". GH #29 close $FH; open $FH, "<", $fn; my $s = <$FH>; close $FH; ok ($s eq "0true\n", $s); # 11 unlink $fn; } ok (++$false == 1); # turns it into true! not sure if we want that ok (!Cpanel::JSON::XS::is_bool $false); ok (Cpanel::JSON::XS->new->allow_nonref (1)->decode ('5') == 5); ok (Cpanel::JSON::XS->new->allow_nonref (1)->decode ('-5') == -5); ok (Cpanel::JSON::XS->new->allow_nonref (1)->decode ('5e1') == 50); ok (Cpanel::JSON::XS->new->allow_nonref (1)->decode ('-333e+0') == -333); ok (Cpanel::JSON::XS->new->allow_nonref (1)->decode ('2.5') == 2.5); ok (Cpanel::JSON::XS->new->allow_nonref (1)->decode ('""') eq ""); ok ('[1,2,3,4]' eq encode_json decode_json ('[1,2, 3,4]')); ok ('[{},[],[],{}]' eq encode_json decode_json ('[{},[], [ ] ,{ }]')); ok ('[{"1":[5]}]' eq encode_json [{1 => [5]}]); ok ('{"1":2,"3":4}' eq Cpanel::JSON::XS->new->canonical (1)->encode (decode_json '{ "1" : 2, "3" : 4 }')); ok ('{"1":2,"3":1.2}' eq Cpanel::JSON::XS->new->canonical (1)->encode (decode_json '{ "1" : 2, "3" : 1.2 }')); ok ('[true]' eq encode_json [Cpanel::JSON::XS::true]); ok ('[false]' eq encode_json [Cpanel::JSON::XS::false]); ok ('[true]' eq encode_json [\1]); ok ('[false]' eq encode_json [\0]); ok ('[null]' eq encode_json [undef]); ok ('[true]' eq encode_json [Cpanel::JSON::XS::true]); ok ('[false]' eq encode_json [Cpanel::JSON::XS::false]); for $v (1, 2, 3, 5, -1, -2, -3, -4, 100, 1000, 10000, -999, -88, -7, 7, 88, 999, -1e5, 1e6, 1e7, 1e8) { ok ($v == ((decode_json "[$v]")->[0])); ok ($v == ((decode_json encode_json [$v])->[0])); } ok (30123 == ((decode_json encode_json [30123])->[0])); ok (32123 == ((decode_json encode_json [32123])->[0])); ok (32456 == ((decode_json encode_json [32456])->[0])); ok (32789 == ((decode_json encode_json [32789])->[0])); ok (32767 == ((decode_json encode_json [32767])->[0])); ok (32768 == ((decode_json encode_json [32768])->[0])); my @sparse; @sparse[0,3] = (1, 4); ok ("[1,null,null,4]" eq encode_json \@sparse); # RFC 7159: optional 2nd allow_nonref arg ok (32768 == decode_json("32768", 1)); ok ("32768" eq decode_json("32768", 1)); ok (1 == decode_json("true", 1)); ok (0 == decode_json("false", 1)); Cpanel-JSON-XS-3.0210/t/04_dwiw_encode.t0000644000076500001200000000402512463231643016465 0ustar rurbanadmin#! perl # copied over from JSON::DWIW and modified to use Cpanel::JSON::XS # Creation date: 2007-02-20 19:51:06 # Authors: don use strict; use Test; # main { BEGIN { plan tests => 5 } use Cpanel::JSON::XS; my $data; # my $expected_str = '{"var1":"val1","var2":["first_element",{"sub_element":"sub_val","sub_element2":"sub_val2"}],"var3":"val3"}'; my $expected_str1 = '{"var1":"val1","var2":["first_element",{"sub_element":"sub_val","sub_element2":"sub_val2"}]}'; my $expected_str2 = '{"var2":["first_element",{"sub_element":"sub_val","sub_element2":"sub_val2"}],"var1":"val1"}'; my $expected_str3 = '{"var2":["first_element",{"sub_element2":"sub_val2","sub_element":"sub_val"}],"var1":"val1"}'; my $expected_str4 = '{"var1":"val1","var2":["first_element",{"sub_element2":"sub_val2","sub_element":"sub_val"}]}'; my $json_obj = Cpanel::JSON::XS->new->allow_nonref (1); my $json_str; # print STDERR "\n" . $json_str . "\n\n"; my $expected_str; $data = 'stuff'; $json_str = $json_obj->encode($data); ok($json_str eq '"stuff"'); $data = "stu\nff"; $json_str = $json_obj->encode($data); ok($json_str eq '"stu\nff"'); $data = [ 1, 2, 3 ]; $expected_str = '[1,2,3]'; $json_str = $json_obj->encode($data); ok($json_str eq $expected_str); $data = { var1 => 'val1', var2 => 'val2' }; $json_str = $json_obj->encode($data); ok($json_str eq '{"var1":"val1","var2":"val2"}' or $json_str eq '{"var2":"val2","var1":"val1"}'); $data = { var1 => 'val1', var2 => [ 'first_element', { sub_element => 'sub_val', sub_element2 => 'sub_val2' }, ], # var3 => 'val3', }; $json_str = $json_obj->encode($data); ok($json_str eq $expected_str1 or $json_str eq $expected_str2 or $json_str eq $expected_str3 or $json_str eq $expected_str4); } exit 0; ############################################################################### # Subroutines Cpanel-JSON-XS-3.0210/t/05_dwiw_decode.t0000644000076500001200000000405112463231643016453 0ustar rurbanadmin#! perl # copied over from JSON::DWIW and modified to use Cpanel::JSON::XS # Creation date: 2007-02-20 21:54:09 # Authors: don use strict; use warnings; use Test; # main { BEGIN { plan tests => 7 } use Cpanel::JSON::XS; my $json_str = '{"var1":"val1","var2":["first_element",{"sub_element":"sub_val","sub_element2":"sub_val2"}],"var3":"val3"}'; my $json_obj = Cpanel::JSON::XS->new->allow_nonref(1); my $data = $json_obj->decode($json_str); my $pass = 1; if ($data->{var1} eq 'val1' and $data->{var3} eq 'val3') { if ($data->{var2}) { my $array = $data->{var2}; if (ref($array) eq 'ARRAY') { if ($array->[0] eq 'first_element') { my $hash = $array->[1]; if (ref($hash) eq 'HASH') { unless ($hash->{sub_element} eq 'sub_val' and $hash->{sub_element2} eq 'sub_val2') { $pass = 0; } } else { $pass = 0; } } else { $pass = 0; } } else { $pass = 0; } } else { $pass = 0; } } ok($pass); $json_str = '"val1"'; $data = $json_obj->decode($json_str); ok($data eq 'val1'); $json_str = '567'; $data = $json_obj->decode($json_str); ok($data == 567); $json_str = "5e1"; $data = $json_obj->decode($json_str); ok($data == 50); $json_str = "5e3"; $data = $json_obj->decode($json_str); ok($data == 5000); $json_str = "5e+1"; $data = $json_obj->decode($json_str); ok($data == 50); $json_str = "5e-1"; $data = $json_obj->decode($json_str); ok($data == 0.5); # use Data::Dumper; # print STDERR Dumper($test_data) . "\n\n"; } exit 0; ############################################################################### # Subroutines Cpanel-JSON-XS-3.0210/t/06_pc_pretty.t0000644000076500001200000000226112463231643016211 0ustar rurbanadmin#! perl # copied over from JSON::PC and modified to use Cpanel::JSON::XS use strict; use Test::More; BEGIN { plan tests => 9 }; use Cpanel::JSON::XS; my ($js,$obj,$json); my $pc = new Cpanel::JSON::XS; $obj = {foo => "bar"}; $js = $pc->encode($obj); is($js,q|{"foo":"bar"}|); $obj = [10, "hoge", {foo => "bar"}]; $pc->pretty (1); $js = $pc->encode($obj); is($js,q|[ 10, "hoge", { "foo" : "bar" } ] |); $obj = { foo => [ {a=>"b"}, 0, 1, 2 ] }; $pc->pretty(0); $js = $pc->encode($obj); is($js,q|{"foo":[{"a":"b"},0,1,2]}|); $obj = { foo => [ {a=>"b"}, 0, 1, 2 ] }; $pc->pretty(1); $js = $pc->encode($obj); is($js,q|{ "foo" : [ { "a" : "b" }, 0, 1, 2 ] } |); $obj = { foo => [ {a=>"b"}, 0, 1, 2 ] }; $pc->pretty(0); $js = $pc->encode($obj); is($js,q|{"foo":[{"a":"b"},0,1,2]}|); $obj = {foo => "bar"}; $pc->indent(1); is($pc->encode($obj), qq|{\n "foo":"bar"\n}\n|, "nospace"); $pc->space_after(1); is($pc->encode($obj), qq|{\n "foo": "bar"\n}\n|, "after"); $pc->space_before(1); is($pc->encode($obj), qq|{\n "foo" : "bar"\n}\n|, "both"); $pc->space_after(0); is($pc->encode($obj), qq|{\n "foo" :"bar"\n}\n|, "before"); Cpanel-JSON-XS-3.0210/t/07_pc_esc.t0000644000076500001200000000402212463231643015432 0ustar rurbanadmin# # このファイルのエンコーディングはUTF-8 # # copied over from JSON::PC and modified to use Cpanel::JSON::XS use Test::More tests => 17; use strict; use utf8; #BEGIN { plan tests => 17 }; use Cpanel::JSON::XS; ######################### my ($js,$obj,$str); my $pc = new Cpanel::JSON::XS; $obj = {test => qq|abc"def|}; $str = $pc->encode($obj); is($str,q|{"test":"abc\"def"}|); $obj = {qq|te"st| => qq|abc"def|}; $str = $pc->encode($obj); is($str,q|{"te\"st":"abc\"def"}|); $obj = {test => qq|abc/def|}; # / => \/ $str = $pc->encode($obj); # but since version 0.99 is($str,q|{"test":"abc/def"}|); # this handling is deleted. $obj = $pc->decode($str); is($obj->{test},q|abc/def|); $obj = {test => q|abc\def|}; $str = $pc->encode($obj); is($str,q|{"test":"abc\\\\def"}|); $obj = {test => "abc\bdef"}; $str = $pc->encode($obj); is($str,q|{"test":"abc\bdef"}|); $obj = {test => "abc\fdef"}; $str = $pc->encode($obj); is($str,q|{"test":"abc\fdef"}|); $obj = {test => "abc\ndef"}; $str = $pc->encode($obj); is($str,q|{"test":"abc\ndef"}|); $obj = {test => "abc\rdef"}; $str = $pc->encode($obj); is($str,q|{"test":"abc\rdef"}|); $obj = {test => "abc-def"}; $str = $pc->encode($obj); is($str,q|{"test":"abc-def"}|); $obj = {test => "abc(def"}; $str = $pc->encode($obj); is($str,q|{"test":"abc(def"}|); $obj = {test => "abc\\def"}; $str = $pc->encode($obj); is($str,q|{"test":"abc\\\\def"}|); SKIP: { skip "5.6", 2 if $] < 5.008; $obj = {test => "あいうえお"}; $str = $pc->encode($obj); is($str,q|{"test":"あいうえお"}|); $obj = {"あいうえお" => "かきくけこ"}; $str = $pc->encode($obj); is($str,q|{"あいうえお":"かきくけこ"}|); } $obj = $pc->decode(q|{"id":"abc\ndef"}|); is($obj->{id},"abc\ndef",q|{"id":"abc\ndef"}|); $obj = $pc->decode(q|{"id":"abc\\\ndef"}|); is($obj->{id},"abc\\ndef",q|{"id":"abc\\\ndef"}|); $obj = $pc->decode(q|{"id":"abc\\\\\ndef"}|); is($obj->{id},"abc\\\ndef",q|{"id":"abc\\\\\ndef"}|); Cpanel-JSON-XS-3.0210/t/08_pc_base.t0000644000076500001200000000405112463231643015575 0ustar rurbanadminuse Test::More tests => 20; # copied over from JSON::PC and modified to use Cpanel::JSON::XS use strict; use Cpanel::JSON::XS; my ($js,$obj); my $pc = new Cpanel::JSON::XS; $js = q|{}|; $obj = $pc->decode($js); $js = $pc->encode($obj); is($js,'{}', '{}'); $js = q|[]|; $obj = $pc->decode($js); $js = $pc->encode($obj); is($js,'[]', '[]'); $js = q|{"foo":"bar"}|; $obj = $pc->decode($js); is($obj->{foo},'bar'); $js = $pc->encode($obj); is($js,'{"foo":"bar"}', '{"foo":"bar"}'); $js = q|{"foo":""}|; $obj = $pc->decode($js); $js = $pc->encode($obj); is($js,'{"foo":""}', '{"foo":""}'); $js = q|{"foo":" "}|; $obj = $pc->decode($js); $js = $pc->encode($obj); is($js,'{"foo":" "}' ,'{"foo":" "}'); $js = q|{"foo":"0"}|; $obj = $pc->decode($js); $js = $pc->encode($obj); is($js,'{"foo":"0"}',q|{"foo":"0"} - autoencode (default)|); $js = q|{"foo":"0 0"}|; $obj = $pc->decode($js); $js = $pc->encode($obj); is($js,'{"foo":"0 0"}','{"foo":"0 0"}'); $js = q|[1,2,3]|; $obj = $pc->decode($js); is($obj->[1],2); $js = $pc->encode($obj); is($js,'[1,2,3]'); $js = q|{"foo":{"bar":"hoge"}}|; $obj = $pc->decode($js); is($obj->{foo}->{bar},'hoge'); $js = $pc->encode($obj); is($js,q|{"foo":{"bar":"hoge"}}|); $js = q|[{"foo":[1,2,3]},-0.12,{"a":"b"}]|; $obj = $pc->decode($js); $js = $pc->encode($obj); is($js,q|[{"foo":[1,2,3]},-0.12,{"a":"b"}]|); $obj = ["\x01"]; is($js = $pc->encode($obj),'["\\u0001"]'); $obj = $pc->decode($js); is($obj->[0],"\x01"); $obj = ["\e"]; is($js = $pc->encode($obj),'["\\u001b"]'); $obj = $pc->decode($js); is($obj->[0],"\e"); SKIP: { skip "5.6", 3 if $] < 5.008; $js = '{"id":"}'; eval q{ $pc->decode($js) }; like($@, qr/unexpected end/i); $obj = { foo => sub { "bar" } }; eval q{ $js = $pc->encode($obj) }; like($@, qr/JSON can only/i, 'invalid value (coderef)'); #$obj = { foo => bless {}, "Hoge" }; #eval q{ $js = $pc->encode($obj) }; #like($@, qr/JSON can only/i, 'invalid value (blessd object)'); $obj = { foo => \$js }; eval q{ $js = $pc->encode($obj) }; like($@, qr/cannot encode reference/i, 'invalid value (ref)'); }Cpanel-JSON-XS-3.0210/t/08_pc_base_nv.t0000644000076500001200000000026612625405341016302 0ustar rurbanadminuse Test::More tests => 1; # copied over from JSON::PC and modified to use Cpanel::JSON::XS use strict; use Cpanel::JSON::XS; my $o = decode_json("[-0.12]"); is($o->[0],"-0.12"); Cpanel-JSON-XS-3.0210/t/09_pc_extra_number.t0000644000076500001200000000124712463231643017363 0ustar rurbanadmin# copied over from JSON::PC and modified to use Cpanel::JSON::XS use Test::More; use strict; BEGIN { plan tests => 6 }; use Cpanel::JSON::XS; use utf8; ######################### my ($js,$obj); my $pc = new Cpanel::JSON::XS; $js = '{"foo":0}'; $obj = $pc->decode($js); is($obj->{foo}, 0, "normal 0"); $js = '{"foo":0.1}'; $obj = $pc->decode($js); is($obj->{foo}, 0.1, "normal 0.1"); $js = '{"foo":10}'; $obj = $pc->decode($js); is($obj->{foo}, 10, "normal 10"); $js = '{"foo":-10}'; $obj = $pc->decode($js); is($obj->{foo}, -10, "normal -10"); $js = '{"foo":0, "bar":0.1}'; $obj = $pc->decode($js); is($obj->{foo},0, "normal 0"); is($obj->{bar},0.1,"normal 0.1"); Cpanel-JSON-XS-3.0210/t/104_sortby.t0000644000076500001200000000122112627073204015573 0ustar rurbanadmin use Test::More tests => 3; use strict; use Cpanel::JSON::XS; ######################### my ($js,$obj); my $pc = Cpanel::JSON::XS->new; $obj = {a=>1, b=>2, c=>3, d=>4, e=>5, f=>6, g=>7, h=>8, i=>9}; $js = $pc->sort_by(1)->encode($obj); is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); $js = $pc->sort_by(sub { $Cpanel::JSON::XS::a cmp $Cpanel::JSON::XS::b })->encode($obj); is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); $js = $pc->sort_by('hoge')->encode($obj); is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); sub Cpanel::JSON::XS::hoge { $Cpanel::JSON::XS::a cmp $Cpanel::JSON::XS::b } Cpanel-JSON-XS-3.0210/t/105_esc_slash.t0000644000076500001200000000034712627073204016226 0ustar rurbanadmin use Test::More tests => 2; use strict; use Cpanel::JSON::XS; ######################### my $json = Cpanel::JSON::XS->new->allow_nonref; my $js = '/'; is($json->encode($js), '"/"'); is($json->escape_slash->encode($js), '"\/"'); Cpanel-JSON-XS-3.0210/t/106_allow_barekey.t0000644000076500001200000000064212627073204017101 0ustar rurbanadmin use Test::More tests => 4; use strict; use Cpanel::JSON::XS; ######################### my $json = Cpanel::JSON::XS->new; eval q| $json->decode('{foo:"bar"}') |; ok($@); # in XS and PP, the error message differs. $json->allow_barekey; is($json->decode('{foo:"bar"}')->{foo}, 'bar'); is($json->decode('{ foo : "bar"}')->{foo}, 'bar', 'with space'); is($json->decode(qq({\tfoo\t:"bar"}))->{foo}, 'bar', 'with tab'); Cpanel-JSON-XS-3.0210/t/107_allow_singlequote.t0000644000076500001200000000154612630007326020017 0ustar rurbanadmin use Test::More tests => 8; use strict; use Cpanel::JSON::XS; ######################### my $json = Cpanel::JSON::XS->new; eval q| $json->decode("{'foo':'bar'}") |; ok($@, "error $@"); # in XS and PP, the error message differs. # '"' expected, at character offset 1 (before "'foo':'bar'}") $json->allow_singlequote; is($json->decode(q|{'foo':"bar"}|)->{foo}, 'bar'); is($json->decode(q|{'foo':'bar'}|)->{foo}, 'bar'); is($json->allow_barekey->decode(q|{foo:'bar'}|)->{foo}, 'bar'); is($json->decode(q|{'foo baz':'bar'}|)->{"foo baz"}, 'bar'); # GH 54 from Locale::Wolowitz is($json->decode(q|{xo:"how's it hangin 1"}|)->{"xo"}, q(how's it hangin 1)); $json->allow_barekey(0); is($json->decode(q|{"xo":"how's it hangin 1"}|)->{"xo"}, q(how's it hangin 1)); $json->allow_singlequote(0); is($json->decode(q|{"xo":"how's it hangin 1"}|)->{"xo"}, q(how's it hangin 1)); Cpanel-JSON-XS-3.0210/t/108_decode.t0000644000076500001200000000241612627615454015520 0ustar rurbanadmin# # decode on Perl 5.005, 5.6, 5.8 or later # use strict; use Test::More tests => 8; use Cpanel::JSON::XS; use lib qw(t); use _unicode_handling; no utf8; my $json = Cpanel::JSON::XS->new->allow_nonref; SKIP: { skip "5.6", 1 if $] < 5.008; is($json->decode(q|"ü"|), "ü"); # utf8 } is($json->decode(q|"\u00fc"|), "\xfc"); # latin1 is($json->decode(q|"\u00c3\u00bc"|), "\xc3\xbc"); # utf8 my $str = 'あ'; # Japanese 'a' in utf8 is($json->decode(q|"\u00e3\u0081\u0082"|), $str); utf8::decode($str) if $] > 5.007; # usually UTF-8 flagged on, but no-op for 5.005. is($json->decode(q|"\u3042"|), $str); my $utf8 = $json->decode(q|"\ud808\udf45"|); # chr 12345 utf8::encode($utf8) if $] > 5.007; # UTf-8 flaged off is($utf8, "\xf0\x92\x8d\x85"); # GH#50 decode >SHORT_STRING_LEN (16384) broken with 3.0206 my $bytes = encode_json(["a" x 32768]); my $decode = eval { decode_json($bytes); }; ok(!$@, "can decode big string $@"); is_deeply $decode, ["a" x 32768], "successful roundtrip" or do { my $fh; open $fh, '>', 'encode.json' or die $!; #END { unlink('encode.json'); } print $fh $bytes; close $fh; open $fh, '>', 'decode.jxt' or die $!; #END { unlink('decode.txt'); } print $fh decode_json($bytes); close $fh; }; Cpanel-JSON-XS-3.0210/t/109_encode.t0000644000076500001200000000143012627571277015532 0ustar rurbanadmin# # decode on Perl 5.005, 5.6, 5.8 or later # use strict; use Test::More tests => 7; use Cpanel::JSON::XS; BEGIN { use lib qw(t); use _unicode_handling; } no utf8; my $json = Cpanel::JSON::XS->new->allow_nonref; is($json->encode("ü"), q|"ü"|); # as is $json->ascii; is($json->encode("\xfc"), q|"\u00fc"|); # latin1 is($json->encode("\xc3\xbc"), q|"\u00c3\u00bc"|); # utf8 is($json->encode("ü"), q|"\u00c3\u00bc"|); # utf8 is($json->encode('あ'), q|"\u00e3\u0081\u0082"|); if ($] >= 5.006) { is($json->encode(chr hex 3042 ), q|"\u3042"|); is($json->encode(chr hex 12345 ), q|"\ud808\udf45"|); } else { is($json->encode(chr hex 3042 ), $json->encode(chr 66)); is($json->encode(chr hex 12345 ), $json->encode(chr 69)); } Cpanel-JSON-XS-3.0210/t/10_pc_keysort.t0000644000076500001200000000060712463231643016357 0ustar rurbanadmin# copied over from JSON::PC and modified to use Cpanel::JSON::XS use Test::More; use strict; BEGIN { plan tests => 1 }; use Cpanel::JSON::XS; ######################### my ($js,$obj); my $pc = Cpanel::JSON::XS->new->canonical(1); $obj = {a=>1, b=>2, c=>3, d=>4, e=>5, f=>6, g=>7, h=>8, i=>9}; $js = $pc->encode($obj); is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); Cpanel-JSON-XS-3.0210/t/110_bignum.t0000644000076500001200000000174612627617171015552 0ustar rurbanadmin use strict; my $has_bignum; BEGIN { eval q| require Math::BigInt |; $has_bignum = $@ ? 0 : 1; } use Test::More $has_bignum ? (tests => 6) : (skip_all => "Can't load Math::BigInt"); use Cpanel::JSON::XS; use Devel::Peek; my $v = Math::BigInt->VERSION; $v =~ s/_.+$// if $v; my $fix = !$v ? '+' : $v < 1.6 ? '+' : ''; my $json = new Cpanel::JSON::XS; $json->allow_nonref->allow_bignum; $json->convert_blessed->allow_blessed; my $num = $json->decode(q|100000000000000000000000000000000000000|); isa_ok($num, 'Math::BigInt'); is("$num", $fix . '100000000000000000000000000000000000000', 'decode bigint') or Dump ($num); my $e = $json->encode($num); is($e, $fix . '100000000000000000000000000000000000000', 'encode bigint') or Dump( $e ); $num = $json->decode(q|2.0000000000000000001|); isa_ok($num, 'Math::BigFloat'); is("$num", '2.0000000000000000001', 'decode bigfloat') or Dump $num; $e = $json->encode($num); is($e, '2.0000000000000000001', 'encode bigfloat') or Dump $e; Cpanel-JSON-XS-3.0210/t/112_upgrade.t0000644000076500001200000000103112627073204015676 0ustar rurbanadminuse strict; use Test::More tests => 3; use Cpanel::JSON::XS; BEGIN { use lib qw(t); use _unicode_handling; } my $json = Cpanel::JSON::XS->new->allow_nonref->utf8; my $str = '\\u00c8'; my $value = $json->decode( '"\\u00c8"' ); #use Devel::Peek; #Dump( $value ); is( $value, chr 0xc8 ); SKIP: { skip "UNICODE handling is disabled.", 1 unless $JSON::can_handle_UTF16_and_utf8; ok( utf8::is_utf8( $value ) ); } eval { $json->decode( '"' . chr(0xc8) . '"' ) }; ok( $@ =~ /malformed UTF-8 character in JSON string/ ); Cpanel-JSON-XS-3.0210/t/113_overloaded_eq.t0000644000076500001200000000162412627073204017071 0ustar rurbanadmin#!/usr/bin/perl use strict; use Test::More tests => 4; use Cpanel::JSON::XS; my $json = Cpanel::JSON::XS->new->convert_blessed; my $obj = OverloadedObject->new( 'foo' ); ok( $obj eq 'foo' ); is( $json->encode( [ $obj ] ), q{["foo"]} ); # rt.cpan.org #64783 my $foo = bless {}, 'Foo'; my $bar = bless {}, 'Bar'; eval q{ $json->encode( $foo ) }; ok($@); eval q{ $json->encode( $bar ) }; ok(!$@); package Foo; use strict; use overload ( 'eq' => sub { 0 }, '""' => sub { $_[0] }, fallback => 1, ); sub TO_JSON { return $_[0]; } package Bar; use strict; use overload ( 'eq' => sub { 0 }, '""' => sub { $_[0] }, fallback => 1, ); sub TO_JSON { return overload::StrVal($_[0]); } package OverloadedObject; use overload 'eq' => sub { $_[0]->{v} eq $_[1] }, '""' => sub { $_[0]->{v} }, fallback => 1; sub new { bless { v => $_[1] }, $_[0]; } sub TO_JSON { "$_[0]"; } Cpanel-JSON-XS-3.0210/t/114_decode_prefix.t0000644000076500001200000000141212627073204017054 0ustar rurbanadmin#!/usr/bin/perl use strict; use Test::More tests => 8; use Cpanel::JSON::XS; my $json = Cpanel::JSON::XS->new; my $complete_text = qq/{"foo":"bar"}/; my $garbaged_text = qq/{"foo":"bar"}\n/; my $garbaged_text2 = qq/{"foo":"bar"}\n\n/; my $garbaged_text3 = qq/{"foo":"bar"}\n----/; is( ( $json->decode_prefix( $complete_text ) ) [1], 13 ); is( ( $json->decode_prefix( $garbaged_text ) ) [1], 13 ); is( ( $json->decode_prefix( $garbaged_text2 ) ) [1], 13 ); is( ( $json->decode_prefix( $garbaged_text3 ) ) [1], 13 ); eval { $json->decode( "\n" ) }; ok( $@ =~ /malformed JSON/ ); eval { $json->decode('null') }; ok $@ =~ /allow_nonref/; eval { $json->decode_prefix( "\n" ) }; ok( $@ =~ /malformed JSON/ ); eval { $json->decode_prefix('null') }; ok $@ =~ /allow_nonref/; Cpanel-JSON-XS-3.0210/t/115_tie_ixhash.t0000644000076500001200000000126012627073204016403 0ustar rurbanadmin use strict; use Test::More tests => 2; use Cpanel::JSON::XS; # from https://rt.cpan.org/Ticket/Display.html?id=25162 SKIP: { eval {require Tie::IxHash}; skip "Can't load Tie::IxHash.", 2 if ($@); my %columns; tie %columns, 'Tie::IxHash'; %columns = ( id => 'int', 1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'e', ); my $json = Cpanel::JSON::XS->new; my $js = $json->encode(\%columns); is( $js, q/{"id":"int","1":"a","2":"b","3":"c","4":"d","5":"e"}/ ); $js = $json->pretty->encode(\%columns); is( $js, <<'STR' ); { "id" : "int", "1" : "a", "2" : "b", "3" : "c", "4" : "d", "5" : "e" } STR } Cpanel-JSON-XS-3.0210/t/116_incr_parse_fixed.t0000644000076500001200000000066012627073204017566 0ustar rurbanadmin#!/usr/bin/perl use strict; use Test::More tests => 4; use Cpanel::JSON::XS; my $json = Cpanel::JSON::XS->new->allow_nonref(); my @vs = $json->incr_parse('"a\"bc'); ok( not scalar(@vs) ); @vs = $json->incr_parse('"'); is( $vs[0], "a\"bc" ); $json = Cpanel::JSON::XS->new; @vs = $json->incr_parse('"a\"bc'); ok( not scalar(@vs) ); @vs = eval { $json->incr_parse('"') }; ok($@ =~ qr/JSON text must be an object or array/); Cpanel-JSON-XS-3.0210/t/117_numbers.t0000644000076500001200000000435712463231643015746 0ustar rurbanadminuse strict; use Cpanel::JSON::XS; use Test::More; use Config; plan tests => 19; is encode_json([9**9**9]), '[null]', "inf -> null"; is encode_json([-sin(9**9**9)]), '[null]', "nan -> null"; is encode_json([-9**9**9]), '[null]', "-inf -> null"; is encode_json([sin(9**9**9)]), '[null]', "-nan -> null"; is encode_json([9**9**9/9**9**9]), '[null]', "-nan -> null"; my $json = Cpanel::JSON::XS->new->stringify_infnan; my ($inf, $nan) = ($^O eq 'MSWin32') ? ('1.#INF','1.#QNAN') : ($^O eq 'solaris') ? ('Infinity','NaN') : ('inf','nan'); my $neg_nan = ($^O eq 'MSWin32') ? "-1.#IND" : "-".$nan; # newlib and glibc 2.5 have no -nan support, just nan. The BSD's neither, but they might # come up with it lateron, as darwin did. #if ($^O eq 'cygwin' or ($Config{glibc_version} && $Config{glibc_version} < 2.6)) { # $neg_nan = $nan; #} is $json->encode([9**9**9]), "[\"$inf\"]", "inf -> \"inf\""; is $json->encode([-9**9**9]), "[\"-$inf\"]", "-inf -> \"-inf\""; # The concept of negative nan is not portable and varies too much. # Windows even emits neg_nan for the first test sometimes. like $json->encode([-sin(9**9**9)]), qr/\[\"($neg_nan|$nan)\"\]/, "nan -> \"nan\""; like $json->encode([sin(9**9**9)]), qr/\[\"($neg_nan|$nan)\"\]/, "-nan -> \"-nan\""; like $json->encode([9**9**9/9**9**9]), qr/\[\"($neg_nan|$nan)\"\]/, "-nan -> \"-nan\""; $json = Cpanel::JSON::XS->new->stringify_infnan(2); is $json->encode([9**9**9]), "[$inf]", "inf"; is $json->encode([-9**9**9]), "[-$inf]", "-inf"; like $json->encode([-sin(9**9**9)]), qr/\[($neg_nan|$nan)\]/, "nan"; like $json->encode([sin(9**9**9)]), qr/\[($neg_nan|$nan)\]/, "-nan"; like $json->encode([9**9**9/9**9**9]), qr/\[($neg_nan|$nan)\]/, "-nan"; my $num = 3; my $str = "$num"; is encode_json({test => [$num, $str]}), '{"test":[3,"3"]}', 'int dualvar'; $num = 3.21; $str = "$num"; is encode_json({test => [$num, $str]}), '{"test":[3.21,"3.21"]}', 'numeric dualvar'; $str = '0 but true'; $num = 1 + $str; is encode_json({test => [$num, $str]}), '{"test":[1,"0 but true"]}', 'int/string dualvar'; $str = 'bar'; { no warnings "numeric"; $num = 23 + $str } is encode_json({test => [$num, $str]}), '{"test":[23,"bar"]}', , 'int/string dualvar'; Cpanel-JSON-XS-3.0210/t/11_pc_expo.t0000644000076500001200000000174412463231643015636 0ustar rurbanadmin# copied over from JSON::XS and modified to use Cpanel::JSON::XS use Test::More; use strict; BEGIN { plan tests => 8 }; use Cpanel::JSON::XS; use Config (); ######################### my ($js,$obj); my $pc = new Cpanel::JSON::XS; $js = q|[-12.34]|; $obj = $pc->decode($js); is($obj->[0], -12.34, 'digit -12.34'); $js = $pc->encode($obj); is($js,'[-12.34]', 'digit -12.34'); $js = q|[-1.234e5]|; $obj = $pc->decode($js); is($obj->[0], -123400, 'digit -1.234e5'); $js = $pc->encode($obj); is($js,'[-123400]', 'digit -1.234e5'); $js = q|[1.23E-4]|; $obj = $pc->decode($js); is($obj->[0], 0.000123, 'digit 1.23E-4'); $js = $pc->encode($obj); if ($] < 5.007 and $Config::Config{d_Gconvert} =~ /^g/ and $js ne '[0.000123]') { is($js,'[1.23e-04]', 'digit 1.23e-4 v5.6'); } else { is($js,'[0.000123]', 'digit 1.23E-4'); } $js = q|[1.01e+30]|; $obj = $pc->decode($js); is($obj->[0], 1.01e+30, 'digit 1.01e+30'); $js = $pc->encode($obj); like($js,qr/\[1.01[Ee]\+0?30\]/, 'digit 1.01e+30'); Cpanel-JSON-XS-3.0210/t/12_blessed.t0000644000076500001200000000373012627615650015626 0ustar rurbanadminBEGIN { $| = 1; print "1..18\n"; } use Cpanel::JSON::XS; our $test; sub ok($;$) { print $_[0] ? "" : "not ", "ok ", ++$test, $_[1]?"# ".$_[1]:"", "\n"; $_[0] } my $o1 = bless { a => 3 }, "XX"; my $o2 = bless \(my $dummy = 1), "YY"; if (eval 'require Hash::Util') { if ($Hash::Util::VERSION > 0.05) { Hash::Util::lock_ref_keys($o1); print "# blessed hash is locked\n"; } else { Hash::Util::lock_hash($o1); print "# hash is locked\n"; } } else { print "# locked hashes are not supported\n"; }; sub XX::TO_JSON { {__,""} } my $js = Cpanel::JSON::XS->new; eval { $js->encode ($o1) }; ok ($@ =~ /allow_blessed/); eval { $js->encode ($o2) }; ok ($@ =~ /allow_blessed/); $js->allow_blessed; ok ($js->encode ($o1) eq "null"); ok ($js->encode ($o2) eq "null"); $js->allow_blessed(0)->convert_blessed; ok ($js->encode ($o1) eq '{"__":""}'); ok ($js->encode ($o2) eq "null"); $js->allow_blessed->convert_blessed; ok ($js->encode ($o1) eq '{"__":""}'); if ($] < 5.008) { print "ok ",++$test," # skip 5.6\n" } else { # PP returns null ok ($js->encode ($o2) eq 'null') or print STDERR "# ",$js->encode ($o2),"\n"; } $js->filter_json_object (sub { 5 }); $js->filter_json_single_key_object (a => sub { shift }); $js->filter_json_single_key_object (b => sub { 7 }); ok ("ARRAY" eq ref $js->decode ("[]")); ok (5 eq join ":", @{ $js->decode ('[{}]') }); ok (6 eq join ":", @{ $js->decode ('[{"a":6}]') }); ok (5 eq join ":", @{ $js->decode ('[{"a":4,"b":7}]') }); $js->filter_json_object; ok (7 == $js->decode ('[{"a":4,"b":7}]')->[0]{b}); ok (3 eq join ":", @{ $js->decode ('[{"a":3}]') }); $js->filter_json_object (sub { }); ok (7 == $js->decode ('[{"a":4,"b":7}]')->[0]{b}); ok (9 eq join ":", @{ $js->decode ('[{"a":9}]') }); $js->filter_json_single_key_object ("a"); ok (4 == $js->decode ('[{"a":4}]')->[0]{a}); if ($]<5.008) { print "ok 18 # skip 5.6\n"; } else { $js->filter_json_single_key_object (a => sub { }); ok (4 == $js->decode ('[{"a":4}]')->[0]{a}); } Cpanel-JSON-XS-3.0210/t/13_limit.t0000644000076500001200000000136612463231643015321 0ustar rurbanadminuse Test::More $] < 5.008 ? (skip_all => "5.6") : (tests => 11); use Cpanel::JSON::XS; my $def = 512; my $js = Cpanel::JSON::XS->new; ok (!eval { $js->decode (("[" x ($def + 1)) . ("]" x ($def + 1))) }); ok (ref $js->decode (("[" x $def) . ("]" x $def))); ok (ref $js->decode (("{\"\":" x ($def - 1)) . "[]" . ("}" x ($def - 1)))); ok (!eval { $js->decode (("{\"\":" x $def) . "[]" . ("}" x $def)) }); ok (ref $js->max_depth (32)->decode (("[" x 32) . ("]" x 32))); ok ($js->max_depth(1)->encode ([])); ok (!eval { $js->encode ([[]]), 1 }); ok ($js->max_depth(2)->encode ([{}])); ok (!eval { $js->encode ([[{}]]), 1 }); ok (eval { ref $js->max_size (8)->decode ("[ ]") }); eval { $js->max_size (8)->decode ("[ ]") }; ok ($@ =~ /max_size/); Cpanel-JSON-XS-3.0210/t/14_latin1.t0000644000076500001200000000314712463231643015373 0ustar rurbanadminuse Cpanel::JSON::XS; no utf8; use Test::More tests => 12; my $xs = Cpanel::JSON::XS->new->latin1->allow_nonref; is($xs->encode ("\x{12}\x{89} "), "\"\\u0012\x{89} \""); is($xs->encode ("\x{12}\x{89}\x{abc}"), "\"\\u0012\x{89}\\u0abc\""); is($xs->decode ("\"\\u0012\x{89}\"" ), "\x{12}\x{89}"); is($xs->decode ("\"\\u0012\x{89}\\u0abc\""), "\x{12}\x{89}\x{abc}"); is(Cpanel::JSON::XS->new->ascii->encode (["I ❤ perl"]), '["I \\u00e2\\u009d\\u00a4 perl"]', 'non-utf8 enc ascii'); is(Cpanel::JSON::XS->new->ascii->decode ('["I \\u00e2\\u009d\\u00a4 perl"]')->[0], "I \x{e2}\x{9d}\x{a4} perl", 'non-utf8 dec ascii'); is(Cpanel::JSON::XS->new->latin1->encode (["I \x{e2}\x{9d}\x{a4} perl"]), "[\"I \x{e2}\x{9d}\x{a4} perl\"]", 'non-utf8 enc latin1'); is(Cpanel::JSON::XS->new->latin1->decode ("[\"I \x{e2}\x{9d}\x{a4} perl\"]")->[0], "I \x{e2}\x{9d}\x{a4} perl", 'non-utf8 dec latin1'); SKIP: { skip "5.6", 2 if $] < 5.008; require Encode; # [RT #84244] complaint: JSON::XS double encodes to ["I ❠perl"] is(Cpanel::JSON::XS->new->utf8->encode ([Encode::decode_utf8("I \x{e2}\x{9d}\x{a4} perl")]), "[\"I \x{e2}\x{9d}\x{a4} perl\"]", 'non-utf8 enc utf8 [RT #84244]'); is(Cpanel::JSON::XS->new->utf8->decode ("[\"I \x{e2}\x{9d}\x{a4} perl\"]")->[0], Encode::decode_utf8("I \x{e2}\x{9d}\x{a4} perl"), 'non-utf8 dec utf8'); } is(Cpanel::JSON::XS->new->binary->encode (["I \x{e2}\x{9d}\x{a4} perl"]), '["I \xe2\x9d\xa4 perl"]', 'non-utf8 enc binary'); is(Cpanel::JSON::XS->new->binary->decode ('["I \xe2\x9d\xa4 perl"]')->[0], "I \x{e2}\x{9d}\x{a4} perl", 'non-utf8 dec binary'); Cpanel-JSON-XS-3.0210/t/15_prefix.t0000644000076500001200000000050012463231643015467 0ustar rurbanadminuse Test::More tests => 4; use Cpanel::JSON::XS; my $xs = Cpanel::JSON::XS->new->latin1->allow_nonref; eval { $xs->decode ("[] ") }; ok (!$@); SKIP: { skip "5.6", 1 if $] < 5.008; eval { $xs->decode ("[] x") }; ok ($@); } ok (2 == ($xs->decode_prefix ("[][]"))[1]); ok (3 == ($xs->decode_prefix ("[1] t"))[1]); Cpanel-JSON-XS-3.0210/t/16_tied.t0000644000076500001200000000055012463231643015125 0ustar rurbanadminBEGIN { $| = 1; print "1..2\n"; } use Cpanel::JSON::XS; use Tie::Hash; use Tie::Array; our $test; sub ok($;$) { print $_[0] ? "" : "not ", "ok ", ++$test, "\n"; } my $js = Cpanel::JSON::XS->new; tie my %h, 'Tie::StdHash'; %h = (a => 1); ok ($js->encode (\%h) eq '{"a":1}'); tie my @a, 'Tie::StdArray'; @a = (1, 2); ok ($js->encode (\@a) eq '[1,2]'); Cpanel-JSON-XS-3.0210/t/17_relaxed.t0000644000076500001200000000153312627537122015632 0ustar rurbanadminuse Test::More $] < 5.008 ? (skip_all => "5.6") : (tests => 12); use Cpanel::JSON::XS; my $json = Cpanel::JSON::XS->new->relaxed; is (encode_json $json->decode (' [1,2, 3]'), '[1,2,3]'); is (encode_json $json->decode ('[1,2, 4 , ]'), '[1,2,4]'); ok (!eval { $json->decode ('[1,2, 3,4,,]') }); ok (!eval { $json->decode ('[,1]') }); is (encode_json $json->decode (' {"1":2}'), '{"1":2}' ); is (encode_json $json->decode ('{"1":2,}'), '{"1":2}'); is (encode_json $json->decode (q({'1':2})), '{"1":2}'); # allow_singlequotes is (encode_json $json->decode ('{a:2}'), '{"a":2}'); # allow_barekey ok (!eval { $json->decode ('{,}') }); is (encode_json $json->decode ("[1#,2\n ,2,# ] \n\t]"), '[1,2]'); is (encode_json $json->decode ("[\"Hello\tWorld\"]"), '["Hello\tWorld"]'); is (encode_json $json->decode ('{"a b":2}'), '{"a b":2}'); # allow_barekey Cpanel-JSON-XS-3.0210/t/18_json_checker.t0000644000076500001200000000747012463231643016647 0ustar rurbanadmin#! perl # use the testsuite from http://www.json.org/JSON_checker/ # except for fail18.json, as we do not support a depth of 20 (but 16 and 32). use strict; no warnings; use Test::More $] < 5.008 ? (skip_all => "5.6") : (tests => 39); use Cpanel::JSON::XS; exit if $] < 5.008; # emulate JSON_checker default config my $json = Cpanel::JSON::XS->new->utf8->max_depth(32)->canonical; $json = Cpanel::JSON::XS->new->max_depth(32)->canonical if $] < 5.008; binmode DATA; for (;;) { $/ = "\n# "; chomp (my $test = ) or last; $/ = "\n"; my $name = ; if (my $perl = eval { $json->decode ($test) }) { ok ($name =~ /^pass/, $name); is ($json->encode ($json->decode ($json->encode ($perl))), $json->encode ($perl)); } else { ok ($name =~ /^fail/, "$name ($@)"); } } __DATA__ "A JSON payload should be an object or array, not a string." # fail1.json {"Extra value after close": true} "misplaced quoted value" # fail10.json {"Illegal expression": 1 + 2} # fail11.json {"Illegal invocation": alert()} # fail12.json {"Numbers cannot have leading zeroes": 013} # fail13.json {"Numbers cannot be hex": 0x14} # fail14.json ["Illegal backslash escape: \x15"] # fail15.json [\naked] # fail16.json ["Illegal backslash escape: \017"] # fail17.json [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] # fail18.json {"Missing colon" null} # fail19.json ["Unclosed array" # fail2.json {"Double colon":: null} # fail20.json {"Comma instead of colon", null} # fail21.json ["Colon instead of comma": false] # fail22.json ["Bad value", truth] # fail23.json ['single quote'] # fail24.json [" tab character in string "] # fail25.json ["tab\ character\ in\ string\ "] # fail26.json ["line break"] # fail27.json ["line\ break"] # fail28.json [0e] # fail29.json {unquoted_key: "keys must be quoted"} # fail3.json [0e+] # fail30.json [0e+-1] # fail31.json {"Comma instead if closing brace": true, # fail32.json ["mismatch"} # fail33.json ["extra comma",] # fail4.json ["double extra comma",,] # fail5.json [ , "<-- missing value"] # fail6.json ["Comma after the close"], # fail7.json ["Extra close"]] # fail8.json {"Extra comma": true,} # fail9.json [ "JSON Test Pattern pass1", {"object with 1 member":["array with 1 element"]}, {}, [], -42, true, false, null, { "integer": 1234567890, "real": -9876.543210, "e": 0.123456789e-12, "E": 1.234567890E+34, "": 23456789012E66, "zero": 0, "one": 1, "space": " ", "quote": "\"", "backslash": "\\", "controls": "\b\f\n\r\t", "slash": "/ & \/", "alpha": "abcdefghijklmnopqrstuvwyz", "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ", "digit": "0123456789", "0123456789": "digit", "special": "`1~!@#$%^&*()_+-={':[,]}|;.?", "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A", "true": true, "false": false, "null": null, "array":[ ], "object":{ }, "address": "50 St. James Street", "url": "http://www.JSON.org/", "comment": "// /* */": " ", " s p a c e d " :[1,2 , 3 , 4 , 5 , 6 ,7 ],"compact":[1,2,3,4,5,6,7], "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}", "quotes": "" \u0022 %22 0x22 034 "", "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?" : "A key can be any string" }, 0.5 ,98.6 , 99.44 , 1066, 1e1, 0.1e1, 1e-1, 1e00,2e+00,2e-00 ,"rosebud"] # pass1.json [[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]] # pass2.json { "JSON Test Pattern pass3": { "The outermost value": "must be an object or array.", "In this test": "It is an object." } } # pass3.json Cpanel-JSON-XS-3.0210/t/19_incr.t0000644000076500001200000000566712463231643015154 0ustar rurbanadmin#! perl use strict; no warnings; use Test::More $] < 5.008 ? (tests => 39) : (tests => 697); use Cpanel::JSON::XS; sub splitter { my ($coder, $text) = @_; for (0 .. length $text) { my $a = substr $text, 0, $_; my $b = substr $text, $_; $coder->incr_parse ($a); $coder->incr_parse ($b); my $data = $coder->incr_parse; ok ($data); ok ($coder->encode ($data) eq $coder->encode ($coder->decode ($text)), "data"); ok ($coder->incr_text =~ /^\s*$/, "tailws"); } } if ($] >= 5.008) { splitter +Cpanel::JSON::XS->new->canonical , ' ["x\\"","\\u1000\\\\n\\nx",1,{"\\\\" :5 , "": "x"}]'; splitter +Cpanel::JSON::XS->new->canonical , '[ "x\\"","\\u1000\\\\n\\nx" , 1,{"\\\\ " :5 , "": " x"} ] '; } splitter +Cpanel::JSON::XS->new->allow_nonref->canonical, '"test"'; splitter +Cpanel::JSON::XS->new->allow_nonref->canonical, ' "5" '; diag "skip lvalue incr_text for 5.6" if $] < 5.008; exit if $] < 5.008; { my $text = '[5],{"":1} , [ 1,2, 3], {"3":null}'; my $coder = new Cpanel::JSON::XS; for (0 .. length $text) { my $a = substr $text, 0, $_; my $b = substr $text, $_; $coder->incr_parse ($a); $coder->incr_parse ($b); my $j1 = $coder->incr_parse; ok ($coder->incr_text =~ s/^\s*,//, "cskip1"); my $j2 = $coder->incr_parse; ok ($coder->incr_text =~ s/^\s*,//, "cskip2"); my $j3 = $coder->incr_parse; ok ($coder->incr_text =~ s/^\s*,//, "cskip3"); my $j4 = $coder->incr_parse; ok ($coder->incr_text !~ s/^\s*,//, "cskip4"); my $j5 = $coder->incr_parse; ok ($coder->incr_text !~ s/^\s*,//, "cskip5"); ok ('[5]' eq encode_json $j1, "cjson1"); ok ('{"":1}' eq encode_json $j2, "cjson2"); ok ('[1,2,3]' eq encode_json $j3, "cjson3"); ok ('{"3":null}' eq encode_json $j4, "cjson4"); ok (!defined $j5, "cjson5"); } } { my $text = '[x][5]'; my $coder = new Cpanel::JSON::XS; $coder->incr_parse ($text); ok (!eval { $coder->incr_parse }, "sparse1"); ok (!eval { $coder->incr_parse }, "sparse2"); $coder->incr_skip; ok ('[5]' eq $coder->encode (scalar $coder->incr_parse), "sparse3"); } { my $coder = Cpanel::JSON::XS->new->max_size (5); ok (!$coder->incr_parse ("[ "), "incsize1"); eval { !$coder->incr_parse ("] ") }; ok ($@ =~ /6 bytes/, "incsize2 $@"); } { my $coder = Cpanel::JSON::XS->new->max_depth (3); ok (!$coder->incr_parse ("[[["), "incdepth1"); eval { !$coder->incr_parse (" [] ") }; ok ($@ =~ /maximum nesting/, "incdepth2 $@"); } # contributed by yuval kogman, reformatted to fit style { my $coder = Cpanel::JSON::XS->new; my $res = eval { $coder->incr_parse("]") }; my $e = $@; # test more clobbers $@, we need it twice ok (!$res, "unbalanced bracket"); ok ($e, "got error"); like ($e, qr/malformed/, "malformed json string error"); $coder->incr_skip; is_deeply (eval { $coder->incr_parse("[42]") }, [42], "valid data after incr_skip"); } Cpanel-JSON-XS-3.0210/t/20_faihu.t0000644000076500001200000000165712463231643015300 0ustar rurbanadmin#! perl # adapted from a test by Aristotle Pagaltzis (http://intertwingly.net/blog/2007/11/15/Astral-Plane-Characters-in-Json) use strict; use warnings; use Cpanel::JSON::XS; use Test::More $] < 5.008 ? (skip_all => "5.6") : (tests => 3); use Encode qw(encode decode); my ($faihu, $faihu_json, $roundtrip, $js) = "\x{10346}"; $js = Cpanel::JSON::XS->new->allow_nonref->ascii; $faihu_json = $js->encode($faihu); $roundtrip = $js->decode($faihu_json); is ($roundtrip, $faihu, 'JSON in ASCII roundtrips correctly'); $js = Cpanel::JSON::XS->new->allow_nonref->utf8; $faihu_json = $js->encode ($faihu); $roundtrip = $js->decode ($faihu_json); is ($roundtrip, $faihu, 'JSON in UTF-8 roundtrips correctly'); $js = Cpanel::JSON::XS->new->allow_nonref; $faihu_json = encode 'UTF-16BE', $js->encode ($faihu); $roundtrip = $js->decode( decode 'UTF-16BE', $faihu_json); is ($roundtrip, $faihu, 'JSON with external recoding roundtrips correctly' ); Cpanel-JSON-XS-3.0210/t/20_unknown.t0000644000076500001200000000612212627615650015701 0ustar rurbanadmin#!/usr/bin/perl -w use strict; use Test::More; BEGIN { eval 'require JSON;' or plan skip_all => 'JSON required for cross testing'; $ENV{PERL_JSON_BACKEND} = 'JSON::PP'; } plan tests => 32; use JSON (); use Cpanel::JSON::XS (); my $pp = JSON->new; my $json = Cpanel::JSON::XS->new; eval q| $json->encode( [ sub {} ] ) |; ok( $@ =~ /encountered CODE/, $@ ); eval q| $json->encode( [ \-1 ] ) |; ok( $@ =~ /cannot encode reference to scalar/, $@ ); eval q| $json->encode( [ \undef ] ) |; ok( $@ =~ /cannot encode reference to scalar/, $@ ); eval q| $json->encode( [ \{} ] ) |; ok( $@ =~ /cannot encode reference to scalar/, $@ ); # 46 eval q| $json->encode( {false => \""} ) |; ok( $@ =~ /cannot encode reference to scalar/, $@ ); eval q| $json->encode( {false => \!!""} ) |; ok( $@ =~ /cannot encode reference to scalar/, $@ ); eval q| $pp->encode( {false => \""} ) |; ok( $@ =~ /cannot encode reference to scalar/, $@ ); eval q| $pp->encode( {false => \!!""} ) |; ok( $@ =~ /cannot encode reference to scalar/, $@ ); $json->allow_unknown; $pp->allow_unknown; is( $json->encode( [ sub {} ] ), '[null]' ); is( $json->encode( [ \-1 ] ), '[null]' ); is( $json->encode( [ \undef ] ), '[null]' ); is( $json->encode( [ \{} ] ), '[null]' ); # 46 is( $pp->encode( {null => \"some"} ), '{"null":null}', 'pp unknown' ); is( $pp->encode( {null => \""} ), '{"null":null}', 'pp unknown' ); # valid special yes/no values even without nonref my $e = $pp->encode( {true => !!1} ); # pp is a bit inconsistent ok( ($e eq '{"true":"1"}') || ($e eq '{"true":1}'), 'pp sv_yes' ); is( $pp->encode( {false => !!0} ), '{"false":""}', 'pp sv_no' ); is( $pp->encode( {false => !!""} ), '{"false":""}', 'pp sv_no' ); is( $pp->encode( {true => \!!1} ), '{"true":true}', 'pp \sv_yes'); is( $pp->encode( {false => \!!0} ), '{"false":null}', 'pp \sv_no' ); is( $pp->encode( {false => \!!""} ), '{"false":null}', 'pp \sv_no' ); is( $json->encode( {null => \"some"} ), '{"null":null}', 'js unknown' ); is( $json->encode( {null => \""} ), '{"null":null}', 'js unknown' ); is( $json->encode( {true => !!1} ), '{"true":1}', 'js sv_yes' ); is( $json->encode( {false => !!0} ), '{"false":""}', 'js sv_no' ); is( $json->encode( {false => !!""} ), '{"false":""}', 'js sv_no' ); is( $json->encode( {true => \!!1} ), '{"true":true}', 'js \sv_yes' ); is( $json->encode( {false => \!!0} ), '{"false":null}', 'js \sv_no' ); is( $json->encode( {false => \!!""} ), '{"false":null}', 'js \sv_no' ); SKIP: { skip "this test is for Perl 5.8 or later", 4 if $] < 5.008; $pp->allow_unknown(0); $json->allow_unknown(0); my $fh; open( $fh, '>hoge.txt' ) or die $!; END { unlink('hoge.txt'); } eval q| $pp->encode( [ $fh ] ) |; # upstream changed due to this JSON::XS bug ok( $@ =~ /(encountered GLOB|cannot encode reference to scalar)/, "pp ".$@ ); eval q| $json->encode( [ $fh ] ) |; ok( $@ =~ /encountered GLOB/, "js ".$@ ); $pp->allow_unknown(1); $json->allow_unknown(1); is( $pp->encode ( [ $fh ] ), '[null]' ); is( $json->encode( [ $fh ] ), '[null]' ); close $fh; } # skip 5.6 Cpanel-JSON-XS-3.0210/t/21_evans.t0000644000076500001200000000071512463231643015313 0ustar rurbanadmin#! perl # adapted from a test by Martin Evans use strict; use warnings; use Cpanel::JSON::XS; use Test::More $] < 5.008 ? (skip_all => "5.6") : (tests => 1); my $data = ["\x{53f0}\x{6240}\x{306e}\x{6d41}\x{3057}", "\x{6c60}\x{306e}\x{30ab}\x{30a8}\x{30eb}"]; my $js = Cpanel::JSON::XS->new->encode ($data); my $j = new Cpanel::JSON::XS; my $object = $j->incr_parse ($js); die "no object" if !$object; eval { $j->incr_text }; ok (!$@, "$@"); Cpanel-JSON-XS-3.0210/t/22_comment_at_eof.t0000644000076500001200000000251212463231643017154 0ustar rurbanadmin# provided by IKEGAMI@cpan.org use strict; use warnings; use Test::More tests => 13; use Cpanel::JSON::XS; use Data::Dumper qw( Dumper ); sub decoder { my ($str) = @_; my $json = Cpanel::JSON::XS->new->relaxed; $json->incr_parse($_[0]); my $rv; if (!eval { $rv = $json->incr_parse(); 1 }) { $rv = "died with $@"; } local $Data::Dumper::Useqq = 1; local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 0; return Dumper($rv); } is( decoder( "[]" ), '[]', 'array baseline' ); is( decoder( " []" ), '[]', 'space ignored before array' ); is( decoder( "\n[]" ), '[]', 'newline ignored before array' ); is( decoder( "# foo\n[]" ), '[]', 'comment ignored before array' ); is( decoder( "# fo[o\n[]"), '[]', 'comment ignored before array' ); is( decoder( "# fo]o\n[]"), '[]', 'comment ignored before array' ); is( decoder( "[# fo]o\n]"), '[]', 'comment ignored inside array' ); is( decoder( "" ), 'undef', 'eof baseline' ); is( decoder( " " ), 'undef', 'space ignored before eof' ); is( decoder( "\n" ), 'undef', 'newline ignored before eof' ); is( decoder( "#,foo\n" ), 'undef', 'comment ignored before eof' ); is( decoder( "# []o\n" ), 'undef', 'comment ignored before eof' ); is( decoder(qq/#\n[#foo\n"#\\n"#\n]/), '["#\n"]', 'array and string in multiple lines' ); Cpanel-JSON-XS-3.0210/t/23_array_ctx.t0000644000076500001200000000111412463231643016167 0ustar rurbanadminprint "1..5\n"; use Cpanel::JSON::XS; sub FREEZE { ( 123, 456 ); } @foo = Cpanel::JSON::XS->new->allow_tags->encode(bless {}, 'main'); print "ok 1\n"; @foo = Cpanel::JSON::XS->new->filter_json_object(sub {12})->decode('[{}]'); print "ok 2\n"; @foo = Cpanel::JSON::XS->new->filter_json_object(sub {return shift, 1})->decode('[{}, {}]'); print "ok 3\n"; @foo = Cpanel::JSON::XS->new->filter_json_single_key_object(1 => sub { [] })->decode('{"1":0}'); print "ok 4\n"; @foo = Cpanel::JSON::XS->new->filter_json_single_key_object(1 => sub { [], [] })->decode('{"1":0}'); print "ok 5\n"; Cpanel-JSON-XS-3.0210/t/24_freeze_recursion.t0000644000076500001200000000071412463234141017546 0ustar rurbanadminuse Cpanel::JSON::XS; use strict; print "1..1\n"; my @foo_params = map {( "foo$_" => 1 )} 1..61; my $foo = Foo->new(@foo_params); my $encoded = Cpanel::JSON::XS->new()->allow_tags(1)->encode( Foo->new( foo => Foo->new(@foo_params), bar => Foo->new(foo => $foo), ) ); print defined($encoded) ? "ok 1\n" : "nok 1\n"; package Foo; sub new { my $class = shift; return bless {@_}, $class; } sub FREEZE { return %{ $_[0] }; } Cpanel-JSON-XS-3.0210/t/25_boolean.t0000644000076500001200000000332412627672223015626 0ustar rurbanadminuse strict; use Test::More tests => 17; use Cpanel::JSON::XS (); my $booltrue = q({"is_true":true}); my $boolfalse = q({"is_false":false}); # since 5.16 yes/no is !0/!1, but for earlier perls we need to use a BoolSV my $a = 0; my $yes = do{$a==0}; # < 5.16 !0 is not sv_yes my $no = do{$a==1}; # < 5.16 !1 is not sv_no my $yesno = [ $yes, $no ]; # native yes/no. YAML::XS compatible my $truefalse = "[true,false]"; my $cjson = Cpanel::JSON::XS->new; my $true = Cpanel::JSON::XS::true; my $false = Cpanel::JSON::XS::false; # from JSON::MaybeXS my $data = $cjson->decode('{"foo": true, "bar": false, "baz": 1}'); ok($cjson->is_bool($data->{foo}), 'true decodes to a bool') or diag 'true is: ', explain $data->{foo}; ok($cjson->is_bool($data->{bar}), 'false decodes to a bool') or diag 'false is: ', explain $data->{bar}; ok(!$cjson->is_bool($data->{baz}), 'int does not decode to a bool') or diag 'int is: ', explain $data->{baz}; my $js = $cjson->decode( $booltrue ); is( $cjson->encode( $js ), $booltrue); ok( $js->{is_true} == $true ); ok( Cpanel::JSON::XS::is_bool($js->{is_true}) ); $js = $cjson->decode( $boolfalse ); is( $cjson->encode( $js ), $boolfalse ); ok( $js->{is_false} == $false ); ok( Cpanel::JSON::XS::is_bool($js->{is_false}) ); is( $cjson->encode( [\1,\0] ), $truefalse ); is( $cjson->encode( [ $true, $false] ), $truefalse ); TODO: { local $TODO = 'GH #39'; is( $cjson->encode( $yesno ), $truefalse, "map yes/no to [true,false]"); } $js = $cjson->decode( $truefalse ); ok ($js->[0] == $true, "decode true to yes"); ok ($js->[1] == $false, "decode false to no"); ok( Cpanel::JSON::XS::is_bool($js->[0]) ); ok( Cpanel::JSON::XS::is_bool($js->[1]) ); # GH #53 ok( !Cpanel::JSON::XS::is_bool( [] ) ); Cpanel-JSON-XS-3.0210/t/52_object.t0000644000076500001200000000263312463231643015452 0ustar rurbanadminBEGIN { $| = 1; print "1..20\n"; } BEGIN { $^W = 0 } # hate use Cpanel::JSON::XS; $json = Cpanel::JSON::XS->new->convert_blessed->allow_tags->allow_nonref; print "ok 1\n"; sub Cpanel::JSON::XS::tojson::TO_JSON { print @_ == 1 ? "" : "not ", "ok 3\n"; print Cpanel::JSON::XS::tojson:: eq ref $_[0] ? "" : "not ", "ok 4\n"; print $_[0]{k} == 1 ? "" : "not ", "ok 5\n"; 7 } $obj = bless { k => 1 }, Cpanel::JSON::XS::tojson::; print "ok 2\n"; $enc = $json->encode ($obj); print $enc eq 7 ? "" : "not ", "ok 6 # $enc\n"; print "ok 7\n"; sub Cpanel::JSON::XS::freeze::FREEZE { print @_ == 2 ? "" : "not ", "ok 8\n"; print $_[1] eq "JSON" ? "" : "not ", "ok 9\n"; print Cpanel::JSON::XS::freeze:: eq ref $_[0] ? "" : "not ", "ok 10\n"; print $_[0]{k} == 1 ? "" : "not ", "ok 11\n"; (3, 1, 2) } sub Cpanel::JSON::XS::freeze::THAW { print @_ == 5 ? "" : "not ", "ok 13\n"; print Cpanel::JSON::XS::freeze:: eq $_[0] ? "" : "not ", "ok 14\n"; print $_[1] eq "JSON" ? "" : "not ", "ok 15\n"; print $_[2] == 3 ? "" : "not ", "ok 16\n"; print $_[3] == 1 ? "" : "not ", "ok 17\n"; print $_[4] == 2 ? "" : "not ", "ok 18\n"; 777 } $obj = bless { k => 1 }, Cpanel::JSON::XS::freeze::; $enc = $json->encode ($obj); print $enc eq '("Cpanel::JSON::XS::freeze")[3,1,2]' ? "" : "not ", "ok 12 # $enc\n"; $dec = $json->decode ($enc); print $dec eq 777 ? "" : "not ", "ok 19\n"; print "ok 20\n"; Cpanel-JSON-XS-3.0210/t/53_readonly.t0000644000076500001200000000062512612373433016021 0ustar rurbanadmin#!perl use strict; use warnings; use Test::More $] < 5.008 ? (skip_all => "5.6") : (tests => 1); use Cpanel::JSON::XS; my $json = Cpanel::JSON::XS->new->convert_blessed; sub Foo::TO_JSON { return 1; } my $string = "something"; my $object = \$string; bless $object,'Foo'; Internals::SvREADONLY($string,1); my $hash = {obj=>$object}; my $enc = $json->encode ($hash); ok $enc eq '{"obj":1}', "$enc"; Cpanel-JSON-XS-3.0210/t/54_stringify.t0000644000076500001200000000501512627615650016227 0ustar rurbanadmin#!perl use strict; use warnings; use Test::More; BEGIN { eval "require Time::Piece;"; if ($@) { plan skip_all => "Time::Piece required"; exit 0; } eval 'require JSON;' or plan skip_all => 'JSON required for cross testing'; $ENV{PERL_JSON_BACKEND} = 'JSON::PP'; } use Time::Piece; plan $] < 5.008 ? (skip_all => "5.6 no AMG yet") : (tests => 17); use JSON (); use Cpanel::JSON::XS; my $time = localtime; my $json = Cpanel::JSON::XS->new->convert_blessed; if ($Cpanel::JSON::XS::VERSION lt '3.0202') { diag 'simulate convert_blessed via TO_JSON'; eval 'sub Foo::TO_JSON { "Foo <". shift->[0] . ">" }'; eval 'sub main::TO_JSON { "main=REF(". $$_[0] . ")" }'; eval 'sub Time::Piece::TO_JSON { "$time" }'; } package Foo; use overload '""' => sub { "Foo <". shift->[0] . ">"}; package main; my $object = bless ["foo"], 'Foo'; my $enc = $json->encode( { obj => $object } ); is( $enc, '{"obj":"Foo "}', "mg object stringified" ) or diag($enc); $enc = $json->encode( { time => $time } ); isa_ok($time, "Time::Piece"); # my $dec = $json->decode($enc); is( $enc, qq({"time":"$time"}), 'mg Time::Piece object was stringified' ); $object = bless [], 'main'; $json->allow_stringify; $enc = $json->encode( \$object ); # fails in 5.6 like( $enc, qr/main=ARRAY\(0x[A-Fa-f0-9]+\)/, "nomg blessed array stringified" ) or diag($enc); $enc = $json->encode( \\$object ); like( $enc, qr/REF\(0x[A-Fa-f0-9]+\)/, "nomg ref stringified" ) or diag($enc); # 46, 49 my $pp = JSON->new->allow_unknown->allow_blessed; $json = Cpanel::JSON::XS->new->allow_stringify; is( $pp->encode ( {false => \"some"} ), '{"false":null}', 'pp \"some"'); is( $json->encode( {false => \"some"} ), '{"false":"some"}','js \"some"'); is( $pp->encode ( {false => \""} ), '{"false":null}', 'pp \""'); is( $json->encode( {false => \""} ), '{"false":null}', 'js \""'); is( $pp->encode ( {false => \!!""} ), '{"false":null}', 'pp \!!""'); is( $json->encode( {false => \!!""} ), '{"false":null}', 'js \!!""'); $json->allow_unknown->allow_stringify; $pp->allow_unknown->allow_blessed->convert_blessed; my $e = $pp->encode( {false => \"some"} ); # pp is a bit inconsistent ok( ($e eq '{"false":null}') || ($e eq '{"false":some}'), 'pp stringref' ); is( $pp->encode ( {false => \""} ), '{"false":null}' ); is( $pp->encode ( {false => \!!""} ), '{"false":null}' ); is( $json->encode( {false => \"some"} ), '{"false":"some"}' ); is( $json->encode( {false => \""} ), '{"false":null}' ); is( $json->encode( {false => \!!""} ), '{"false":null}' ); Cpanel-JSON-XS-3.0210/t/55_modifiable.t0000644000076500001200000000157312627073204016303 0ustar rurbanadmin#!perl use strict; use warnings; use Test::More tests => 15; use Cpanel::JSON::XS; my $js = Cpanel::JSON::XS->new; my @data = ('null', 'true', 'false', "1", "\"test\""); my %map = ( 'null' => undef, true => 1, false => 0, '1' => 1, '"test"' => "test" ); for my $k (@data) { my $data = $js->decode("{\"foo\":$k}"); my $res = $data->{foo} || $k; ok exists $data->{foo}, "foo hvalue exists"; if ($k eq 'true' and $res eq 'true') { # https://github.com/rurban/Cpanel-JSON-XS/issues/45#issuecomment-160602267 # Older Test::More <5.12 cannot compare 1 to true. # We only care about the next test, modifiability, # not the representation of true and its eq overload. is $data->{foo}, $res, "foo hvalue $res (special case)"; } else { is $data->{foo}, $map{$k}, "foo hvalue $res"; } ok $data->{foo} = "bar", "foo can be set from $res to 'bar'"; } Cpanel-JSON-XS-3.0210/t/96_interop.t0000644000076500001200000000253212627615606015701 0ustar rurbanadminuse Test::More; BEGIN { eval "require JSON && require JSON::XS;"; if ($@) { plan skip_all => "JSON::XS and JSON required for testing interop"; exit 0; } else { plan tests => 4; } $ENV{PERL_JSON_BACKEND} = 0; } use JSON (); # limitation: for interop with JSON load JSON before Cpanel::JSON::XS use Cpanel::JSON::XS (); my $boolstring = q({"is_true":true}); my $js; { require JSON::XS; my $json = JSON::XS->new; $js = $json->decode( $boolstring ); # bless { is_true => 1 }, "JSON::PP::Boolean" } my $cjson = Cpanel::JSON::XS->new->allow_blessed; is($cjson->encode( $js ), $boolstring) or diag "\$JSON::XS::VERSION=$JSON::XS::VERSION"; { local $ENV{PERL_JSON_BACKEND} = 'JSON::PP'; my $json = JSON->new; $js = $json->decode( $boolstring ); # bless { is_true => 1 }, "JSON::PP::Boolean" } is ($cjson->encode( $js ), $boolstring) or diag "\$JSON::VERSION=$JSON::VERSION"; { local $ENV{PERL_JSON_BACKEND} = 'JSON::XS'; my $json = JSON->new; $js = $json->decode( $boolstring ); # bless { is_true => 1}, "Types::Serialiser" } is($cjson->encode( $js ), $boolstring) or diag "\$JSON::VERSION=$JSON::VERSION"; # issue18: support Types::Serialiser without allow_blessed (if JSON-XS-3.x is loaded) $js = $cjson->decode( $boolstring ); is ($cjson->encode( $js ), $boolstring) or diag(ref $js->{is_true}); Cpanel-JSON-XS-3.0210/t/96_mojo.t0000644000076500001200000000242412625405341015154 0ustar rurbanadminuse Test::More; BEGIN { eval "require Mojo::JSON;"; if ($@) { plan skip_all => "Mojo::JSON required for testing interop"; exit 0; } if (!defined &Mojo::JSON::decode_json) { plan skip_all => "Mojo::JSON::decode_json required for testing interop"; exit 0; } plan tests => 9; } use Mojo::JSON (); use Cpanel::JSON::XS (); my $booltrue = q({"is_true":true}); my $boolfalse = q({"is_false":false}); my $yesno = [ !1, !0 ]; my $js = Mojo::JSON::decode_json( $booltrue ); is( $js->{is_true}, 1, 'true == 1' ); ok( $js->{is_true}, 'ok true'); my $cjson = Cpanel::JSON::XS->new; is($cjson->encode( $js ), $booltrue, 'can encode Mojo true') or diag "\$Mojolicious::VERSION=$Mojolicious::VERSION,". " \$Cpanel::JSON::XS::VERSION=$Cpanel::JSON::XS::VERSION"; $js = Mojo::JSON::decode_json( $boolfalse ); is( $cjson->encode( $js ), $boolfalse, 'can encode Mojo false' ); is( $js->{is_false}, 0 ,'false == 0'); ok( !$js->{is_false}, 'ok !false'); my $mj = Mojo::JSON::encode_json( $yesno ); $js = $cjson->decode( $mj ); is( $js->[0], '', 'can decode Mojo false' ); is( $js->[1], 1, 'can decode Mojo true' ); # Note this is fragile. it depends on the internal representation of booleans. is_deeply( $js, ['', 1], 'can decode Mojo booleans (fragile)' ) or diag( $mj, $js ); Cpanel-JSON-XS-3.0210/t/97_unshare_hek.t0000644000076500001200000000043012463231643016502 0ustar rurbanadmin# shared hek destruction. with debugging perls or valgrind only # https://github.com/rurban/Cpanel-JSON-XS/issues/10 print "1..1\n"; use Cpanel::JSON::XS qw; my %h = ('{"foo":"bar"}' => 1); while (my ($k) = each %h) { my $obj = decode_json($k); } print "ok 1\n"; Cpanel-JSON-XS-3.0210/t/98_56only.t0000644000076500001200000000164712463231643015356 0ustar rurbanadminuse Test::More tests => 4; # $] < 5.008 ? (tests => 4) : (skip_all => "5.6 only"); use Cpanel::JSON::XS; { my $formref = { 'cpanel_apiversion' => 1, 'utf8' => 'אאאאאאאխ"', 'func' => 'phpmyadminlink', 'module' => 'Cgi', "включен" => "日本語" }; ok( decode_json( encode_json($formref) ), "Cpanel::JSON::XS :: round trip untied utf8 with int" ); } { my $formref = { 'cpanel_apiversion' => 1, 'utf8' => 'română', 'func' => 'phpmyadminlink', 'module' => 'Cgi', "включен" => "日本語" }; ok( decode_json( encode_json($formref) ), "JSON::XS :: round trip utf8 complex" ); } my $json = Cpanel::JSON::XS->new; $js = q|[-12.34]|; $obj = $json->decode($js); is($obj->[0], -12.34, 'digit -12.34'); $js = $json->encode($obj); is($js,'[-12.34]', 'digit -12.34'); Cpanel-JSON-XS-3.0210/t/99_binary.t0000644000076500001200000000226412630026757015507 0ustar rurbanadminuse Test::More tests => 300; use Cpanel::JSON::XS; use B (); my $as = Cpanel::JSON::XS->new->ascii->shrink; my $us = Cpanel::JSON::XS->new->utf8->shrink; my $bs = Cpanel::JSON::XS->new->binary; sub test($) { my $c = $_[0]; my $js = $as->encode([$c]); is ($c, ((decode_json $js)->[0]), "ascii ".B::cstring($c)); $js = $us->encode([$c]); is ($c, ($us->decode($js))->[0], "utf8 ".B::cstring($c)); } sub test_bin($) { my $c = $_[0]; my $js = $bs->encode([$c]); is ($js, $bs->encode($bs->decode($js)), "binary ".B::cstring($c)); } srand 0; # doesn't help too much, but it's at least more deterministic for (1..25) { test join "", map chr ($_ & 255), 0..$_; test_bin join "", map chr ($_ & 255), 0..$_; SKIP: { skip "skipped uf8 w/o binary: 5.6", 6 if $] < 5.008; test join "", map chr rand 255, 0..$_; test join "", map chr ($_ * 97 & ~0x4000), 0..$_; test join "", map chr (rand (2**20) & ~0x800), 0..$_; } test_bin join "", map chr rand 255, 0..$_; SKIP: { skip "skipped uf8 w binary: 5.6", 2 if $] < 5.008; test_bin join "", map chr ($_ * 97 & ~0x4000), 0..$_; test_bin join "", map chr (rand (2**20) & ~0x800), 0..$_; } } Cpanel-JSON-XS-3.0210/t/_unicode_handling.pm0000644000076500001200000000104712627571526017507 0ustar rurbanadmin#package utf8; package _unicode_handling; # this is a dummy pragma for 5.005. if ($] < 5.006) { $INC{'utf8.pm'} = './utf8.pm'; eval q| sub utf8::import { } sub utf8::unimport { } |; $JSON::can_handle_UTF16_and_utf8 = 0; } else { $JSON::can_handle_UTF16_and_utf8 = 1; if ($] < 5.007) { $JSON::can_handle_UTF16_and_utf8 = 0; } # if ($] > 5.007 and $] < 5.008003) { # $JSON::can_handle_UTF16_and_utf8 = 0; # } } 1; Cpanel-JSON-XS-3.0210/t/z_kwalitee.t0000644000076500001200000000142212625405341016025 0ustar rurbanadmin# -*- perl -*- use strict; use warnings; use Test::More; use Config; plan skip_all => 'requires Test::More 0.88' if Test::More->VERSION < 0.88; plan skip_all => 'This test is only run for the module author' unless -d '.git' || $ENV{AUTHOR_TESTING}; # Missing XS dependencies are usually not caught by EUMM # And they are usually only XS-loaded by the importer, not require. for (qw( Class::XSAccessor Text::CSV_XS List::MoreUtils )) { eval "use $_;"; plan skip_all => "$_ required for Test::Kwalitee" if $@; } eval "require Test::Kwalitee;"; plan skip_all => "Test::Kwalitee required" if $@; plan skip_all => 'Test::Kwalitee fails with clang -faddress-sanitizer' if $Config{ccflags} =~ /-faddress-sanitizer/; Test::Kwalitee->import( tests => [ qw( -use_strict ) ] ); Cpanel-JSON-XS-3.0210/t/z_leaktrace.t0000644000076500001200000000126712463231643016164 0ustar rurbanadmin#!perl -w # note that does not catch the leaking XS context cxt->sv_json #19 # even valgrind does not catch it use strict; use constant HAS_LEAKTRACE => eval{ require Test::LeakTrace }; use Test::More HAS_LEAKTRACE ? (tests => 1) : (skip_all => 'require Test::LeakTrace'); use Test::LeakTrace; use Cpanel::JSON::XS; leaks_cmp_ok{ my $js = Cpanel::JSON::XS->new->convert_blessed->allow_tags->allow_nonref; $js->decode('"\ud801\udc02' . "\x{10204}\""); $js->decode('"\"\n\\\\\r\t\f\b"'); $js->ascii->utf8->encode(chr 0x8000); sub Temp::TO_JSON { 7 } $js->encode ( bless { k => 1 }, Temp:: ); sub Temp1::FREEZE { (3,1,2) } $js->encode ( bless { k => 1 }, Temp1:: ); } '<', 1; Cpanel-JSON-XS-3.0210/t/z_meta.t0000644000076500001200000000147512626545462015170 0ustar rurbanadmin# -*- perl -*- # Test that our META.yml file matches the current specification. use strict; BEGIN { $| = 1; $^W = 1; } my $MODULE = 'Test::CPAN::Meta 0.12'; # Don't run tests for installs use Test::More; use Config; plan skip_all => 'This test is only run for the module author' unless -d '.git' || $ENV{AUTHOR_TESTING}; plan skip_all => 'Test::CPAN::Meta fails with clang -faddress-sanitizer' if $Config{ccflags} =~ /-faddress-sanitizer/; # META is only generated by make dist if (! -f 'META.yml' and -f 'MYMETA.yml') { system "$Config{cp} MYMETA.yml META.yml"; } # Load the testing module eval "use $MODULE;"; if ( $@ ) { plan( skip_all => "$MODULE not available for testing" ); die "Failed to load required release-testing module $MODULE 0.12" if -d '.git' || $ENV{AUTHOR_TESTING}; } meta_yaml_ok(); Cpanel-JSON-XS-3.0210/t/z_perl_minimum_version.t0000644000076500001200000000133212612373433020464 0ustar rurbanadmin# -*- perl -*- # Test that our declared minimum Perl version matches our syntax use strict; BEGIN { $| = 1; $^W = 1; } my @MODULES = ( 'Perl::MinimumVersion 1.20', 'Test::MinimumVersion 0.008', ); # Don't run tests during end-user installs use Test::More; unless (-d '.git' || $ENV{AUTHOR_TESTING}) { plan( skip_all => "Author tests not required for installation" ); } # Load the testing modules foreach my $MODULE ( @MODULES ) { eval "use $MODULE"; if ( $@ ) { plan( skip_all => "$MODULE not available for testing" ); die "Failed to load required release-testing module $MODULE" if -d '.git' || $ENV{AUTHOR_TESTING}; } } all_minimum_version_ok("5.008"); # but 5.6.2 is allowed dynamically 1; Cpanel-JSON-XS-3.0210/t/z_pod-coverage.t0000644000076500001200000000071412612373433016600 0ustar rurbanadmin# -*- perl -*- use strict; use warnings; use Test::More; plan skip_all => 'done_testing requires Test::More 0.88' if Test::More->VERSION < 0.88; plan skip_all => 'This test is only run for the module author' unless -d '.git' || $ENV{AUTHOR_TESTING}; eval "use Test::Pod::Coverage 1.04"; plan skip_all => "Test::Pod::Coverage 1.04 required for testing POD coverage" if $@; for (all_modules()) { pod_coverage_ok($_) unless /XXX/; } done_testing(); Cpanel-JSON-XS-3.0210/t/z_pod-spell-mistakes.t0000644000076500001200000000106012630026757017741 0ustar rurbanadmin# -*- perl -*- use strict; use Test::More; plan skip_all => 'This test is only run for the module author' unless -d '.git' || $ENV{AUTHOR_TESTING}; eval "use Pod::Spell::CommonMistakes;"; plan skip_all => "Pod::Spell::CommonMistakes required" if $@; plan tests => 3; for my $f (qw(XS.pm XS/Boolean.pm bin/cpanel_json_xs)) { my $r = Pod::Spell::CommonMistakes::check_pod($f); if ( keys %$r == 0 ) { ok(1, "$f"); } else { ok(0, "$f"); foreach my $k ( keys %$r ) { diag " Found: '$k' - Possible spelling: '$r->{$k}'?"; } } } Cpanel-JSON-XS-3.0210/t/z_pod-spelling.t0000644000076500001200000000142412630026756016624 0ustar rurbanadmin# -*- perl -*- use strict; use Test::More; plan skip_all => 'This test is only run for the module author' unless -d '.git' || $ENV{AUTHOR_TESTING}; eval "use Test::Spelling;"; plan skip_all => "Test::Spelling required" if $@; add_stopwords(); all_pod_files_spelling_ok(); __DATA__ interop nonref Lehmann bencode clzf commandline fromformat le toformat yaml BMP BSON CVE Crockford ECMAscript GPL Iceweasel KOI Lehmann MLEHMANN Mojo MovableType Reini SixApart Storable TCP XSS amd ascii autodetection backported backrefs cPanel codeset codesets conformant datastructure deserializer ithread ithreads latin nan ness numifying onwards optimizations parsable postprocessing ppport queryable recursing resizes roundtripping sanify src superset testsuite th typeless un unicode xs Cpanel-JSON-XS-3.0210/t/z_pod.t0000644000076500001200000000022012463231643014777 0ustar rurbanadmin# -*- perl -*- use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); Cpanel-JSON-XS-3.0210/t/zero-mojibake.t0000644000076500001200000000137412627073204016434 0ustar rurbanadmin#!/usr/bin/perl use strict; use Test::More tests => 5; use Cpanel::JSON::XS; my $json = Cpanel::JSON::XS->new; my $input = q[ { "dynamic_config" : 0, "x_contributors" : [ "大沢 和宏", "Ævar Arnfjörð" ] } ]; eval { $json->decode($input) }; is $@, '', 'decodes default mojibake without error'; $json->utf8; eval { $json->decode($input) }; is $@, '', 'decodes utf8 mojibake without error'; $json->utf8(0)->ascii; eval { $json->decode($input) }; is $@, '', 'decodes ascii mojibake without error'; $json->ascii(0)->latin1; eval { $json->decode($input) }; is $@, '', 'decodes latin1 mojibake without error'; $json->latin1(0)->binary; eval { $json->decode($input) }; is $@, '', 'decodes binary mojibake without error'; Cpanel-JSON-XS-3.0210/typemap0000644000076500001200000000053412463231643014646 0ustar rurbanadminJSON * T_JSON INPUT T_JSON dMY_CXT; if (!( SvROK ($arg) && SvOBJECT (SvRV ($arg)) && (SvSTASH (SvRV ($arg)) == JSON_STASH || sv_derived_from ($arg, \"Cpanel::JSON::XS\")) )) croak (\"object is not of type Cpanel::JSON::XS\"); /**/ $var = (JSON *)SvPVX (SvRV ($arg)); Cpanel-JSON-XS-3.0210/XS/0000755000076500001200000000000012630027156013572 5ustar rurbanadminCpanel-JSON-XS-3.0210/XS/Boolean.pm0000644000076500001200000000070012463231643015506 0ustar rurbanadmin=head1 NAME Cpanel::JSON::XS::Boolean - dummy module providing JSON::XS::Boolean =head1 SYNOPSIS # do not "use" yourself =head1 DESCRIPTION This module exists only to provide overload resolution for Storable and similar modules and interop with L booleans. See L for more info about this class. =cut use Cpanel::JSON::XS (); 1; =head1 AUTHOR Marc Lehmann http://home.schmorp.de/ =cut Cpanel-JSON-XS-3.0210/XS.pm0000644000076500001200000022327112630026757014145 0ustar rurbanadminpackage Cpanel::JSON::XS; our $VERSION = '3.0210'; =pod =head1 NAME Cpanel::JSON::XS - cPanel fork of JSON::XS, fast and correct serializing =head1 SYNOPSIS use Cpanel::JSON::XS; # exported functions, they croak on error # and expect/generate UTF-8 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref; $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text; # OO-interface $coder = Cpanel::JSON::XS->new->ascii->pretty->allow_nonref; $pretty_printed_unencoded = $coder->encode ($perl_scalar); $perl_scalar = $coder->decode ($unicode_json_text); # Note that 5.6 misses most smart utf8 and encoding functionalities # of newer releases. # Note that L will automatically use Cpanel::JSON::XS # if available, at virtually no speed overhead either, so you should # be able to just: use JSON::MaybeXS; # and do the same things, except that you have a pure-perl fallback now. =head1 DESCRIPTION This module converts Perl data structures to JSON and vice versa. Its primary goal is to be I and its secondary goal is to be I. To reach the latter goal it was written in C. As this is the n-th-something JSON module on CPAN, what was the reason to write yet another JSON module? While it seems there are many JSON modules, none of them correctly handle all corner cases, and in most cases their maintainers are unresponsive, gone missing, or not listening to bug reports for other reasons. See below for the cPanel fork. See MAPPING, below, on how Cpanel::JSON::XS maps perl values to JSON values and vice versa. =head2 FEATURES =over 4 =item * correct Unicode handling This module knows how to handle Unicode with Perl version higher than 5.8.5, documents how and when it does so, and even documents what "correct" means. =item * round-trip integrity When you serialize a perl data structure using only data types supported by JSON and Perl, the deserialized data structure is identical on the Perl level. (e.g. the string "2.0" doesn't suddenly become "2" just because it looks like a number). There I minor exceptions to this, read the MAPPING section below to learn about those. =item * strict checking of JSON correctness There is no guessing, no generating of illegal JSON texts by default, and only JSON is accepted as input by default (the latter is a security feature). =item * fast Compared to other JSON modules and other serializers such as Storable, this module usually compares favourably in terms of speed, too. =item * simple to use This module has both a simple functional interface as well as an object oriented interface. =item * reasonably versatile output formats You can choose between the most compact guaranteed-single-line format possible (nice for simple line-based protocols), a pure-ASCII format (for when your transport is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed format (for when you want to read that stuff). Or you can combine those features in whatever way you like. =back =head2 cPanel fork Since the original author MLEHMANN has no public bugtracker, this cPanel fork sits now on github. src repo: L original: L RT: L or L B - stricter decode_json() as documented. non-refs are disallowed. added a 2nd optional argument. decode() honors now allow_nonref. - fixed encode of numbers for dual-vars. Different string representations are preserved, but numbers with temporary strings which represent the same number are here treated as numbers, not strings. Cpanel::JSON::XS is a bit slower, but preserves numeric types better. - different handling of inf/nan. Default now to null, optionally with -DSTRINGIFY_INFNAN to "inf"/"nan". [#28, #32] - added C extension, non-JSON and non JSON parsable, allows C<\xNN> and C<\NNN> sequences. - 5.6.2 support; sacrificing some utf8 features (assuming bytes all-over), no multi-byte unicode characters. - interop for true/false overloading. JSON::XS, JSON::PP and Mojo::JSON representations for booleans are accepted and JSON::XS accepts Cpanel::JSON::XS booleans [#13, #37] Fixed overloading of booleans. Cpanel::JSON::XS::true stringifies now to true, not 1. - native boolean mapping of yes and no to true and false, as in YAML::XS. In perl C is yes, C is no. The JSON value true maps to 1, false maps to 0. [#39] - support arbitrary stringification with encode, with convert_blessed and allow_blessed. - ithread support. Cpanel::JSON::XS is thread-safe, JSON::XS not - is_bool can be called as method, JSON::XS::is_bool not. - Performance Optimizations for threaded Perls - additional fixes for: - [cpan #88061] AIX atof without USE_LONG_DOUBLE - #10 unshare_hek crash - #7, #29 avoid re-blessing where possible. It fails in JSON::XS for READONLY values, i.e. restricted hashes. - #41 overloading of booleans, use the object not the reference. - public maintenance and bugtracker - use ppport.h, sanify XS.xs comment styles, harness C coding style - common::sense is optional. When available it is not used in the published production module, just during development and testing. - extended testsuite - support many more options and methods from JSON::PP =cut our @ISA = qw(Exporter); our @EXPORT = qw(encode_json decode_json to_json from_json); sub to_json($@) { if ($] >= 5.008) { require Carp; Carp::croak ("Cpanel::JSON::XS::to_json has been renamed to encode_json, either downgrade to pre-2.0 versions of Cpanel::JSON::XS or rename the call"); } else { _to_json(@_); } } sub from_json($@) { if ($] >= 5.008) { require Carp; Carp::croak ("Cpanel::JSON::XS::from_json has been renamed to decode_json, either downgrade to pre-2.0 versions of Cpanel::JSON::XS or rename the call"); } else { _from_json(@_); } } use Exporter; use XSLoader; =head1 FUNCTIONAL INTERFACE The following convenience methods are provided by this module. They are exported by default: =over 4 =item $json_text = encode_json $perl_scalar Converts the given Perl data structure to a UTF-8 encoded, binary string (that is, the string contains octets only). Croaks on error. This function call is functionally identical to: $json_text = Cpanel::JSON::XS->new->utf8->encode ($perl_scalar) Except being faster. =item $perl_scalar = decode_json $json_text [, $allow_nonref ] The opposite of C: expects an UTF-8 (binary) string of an json reference and tries to parse that as an UTF-8 encoded JSON text, returning the resulting reference. Croaks on error. This function call is functionally identical to: $perl_scalar = Cpanel::JSON::XS->new->utf8->decode ($json_text) except being faster. Note that older decode_json versions in Cpanel::JSON::XS older than 3.0116 and JSON::XS did not set allow_nonref but allowed them due to a bug in the decoder. If the new optional $allow_nonref argument is set and not false, the allow_nonref option will be set and the function will act is described as in the relaxed RFC 7159 allowing all values such as objects, arrays, strings, numbers, "null", "true", and "false". =item $is_boolean = Cpanel::JSON::XS::is_bool $scalar Returns true if the passed scalar represents either C or C, two constants that act like C<1> and C<0>, respectively and are used to represent JSON C and C values in Perl. See MAPPING, below, for more information on how JSON values are mapped to Perl. =back =head1 DEPRECATED FUNCTIONS =over =item from_json from_json has been renamed to decode_json =item to_json to_json has been renamed to encode_json =back =head1 A FEW NOTES ON UNICODE AND PERL Since this often leads to confusion, here are a few very clear words on how Unicode works in Perl, modulo bugs. =over 4 =item 1. Perl strings can store characters with ordinal values > 255. This enables you to store Unicode characters as single characters in a Perl string - very natural. =item 2. Perl does I associate an encoding with your strings. ... until you force it to, e.g. when matching it against a regex, or printing the scalar to a file, in which case Perl either interprets your string as locale-encoded text, octets/binary, or as Unicode, depending on various settings. In no case is an encoding stored together with your data, it is I that decides encoding, not any magical meta data. =item 3. The internal utf-8 flag has no meaning with regards to the encoding of your string. =item 4. A "Unicode String" is simply a string where each character can be validly interpreted as a Unicode code point. If you have UTF-8 encoded data, it is no longer a Unicode string, but a Unicode string encoded in UTF-8, giving you a binary string. =item 5. A string containing "high" (> 255) character values is I a UTF-8 string. =back I hope this helps :) =head1 OBJECT-ORIENTED INTERFACE The object oriented interface lets you configure your own encoding or decoding style, within the limits of supported formats. =over 4 =item $json = new Cpanel::JSON::XS Creates a new JSON object that can be used to de/encode JSON strings. All boolean flags described below are by default I. The mutators for flags all return the JSON object again and thus calls can be chained: my $json = Cpanel::JSON::XS->new->utf8->space_after->encode ({a => [1,2]}) => {"a": [1, 2]} =item $json = $json->ascii ([$enable]) =item $enabled = $json->get_ascii If C<$enable> is true (or missing), then the C method will not generate characters outside the code range C<0..127> (which is ASCII). Any Unicode characters outside that range will be escaped using either a single C<\uXXXX> (BMP characters) or a double C<\uHHHH\uLLLLL> escape sequence, as per RFC4627. The resulting encoded JSON text can be treated as a native Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string, or any other superset of ASCII. If C<$enable> is false, then the C method will not escape Unicode characters unless required by the JSON syntax or other flags. This results in a faster and more compact format. See also the section I later in this document. The main use for this flag is to produce JSON texts that can be transmitted over a 7-bit channel, as the encoded JSON texts will not contain any 8 bit characters. Cpanel::JSON::XS->new->ascii (1)->encode ([chr 0x10401]) => ["\ud801\udc01"] =item $json = $json->latin1 ([$enable]) =item $enabled = $json->get_latin1 If C<$enable> is true (or missing), then the C method will encode the resulting JSON text as latin1 (or ISO-8859-1), escaping any characters outside the code range C<0..255>. The resulting string can be treated as a latin1-encoded JSON text or a native Unicode string. The C method will not be affected in any way by this flag, as C by default expects Unicode, which is a strict superset of latin1. If C<$enable> is false, then the C method will not escape Unicode characters unless required by the JSON syntax or other flags. See also the section I later in this document. The main use for this flag is efficiently encoding binary data as JSON text, as most octets will not be escaped, resulting in a smaller encoded size. The disadvantage is that the resulting JSON text is encoded in latin1 (and must correctly be treated as such when storing and transferring), a rare encoding for JSON. It is therefore most useful when you want to store data structures known to contain binary data efficiently in files or databases, not when talking to other JSON encoders/decoders. Cpanel::JSON::XS->new->latin1->encode (["\x{89}\x{abc}"] => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) =item $json = $json->binary ([$enable]) =item $enabled = $json = $json->get_binary If the C<$enable> argument is true (or missing), then the C method will not try to detect an UTF-8 encoding in any JSON string, it will strictly interpret it as byte sequence. The result might contain new C<\xNN> sequences, which is B. The C method forbids C<\uNNNN> sequences and accepts C<\xNN> and octal C<\NNN> sequences. There is also a special logic for perl 5.6 and utf8. 5.6 encodes any string to utf-8 automatically when seeing a codepoint >= C<0x80> and < C<0x100>. With the binary flag enabled decode the perl utf8 encoded string to the original byte encoding and encode this with C<\xNN> escapes. This will result to the same encodings as with newer perls. But note that binary multi-byte codepoints with 5.6 will result in C errors, unlike with newer perls. If C<$enable> is false, then the C method will smartly try to detect Unicode characters unless required by the JSON syntax or other flags and hex and octal sequences are forbidden. See also the section I later in this document. The main use for this flag is to avoid the smart unicode detection and possible double encoding. The disadvantage is that the resulting JSON text is encoded in new C<\xNN> and in latin1 characters and must correctly be treated as such when storing and transferring, a rare encoding for JSON. It will produce non-readable JSON strings in the browser. It is therefore most useful when you want to store data structures known to contain binary data efficiently in files or databases, not when talking to other JSON encoders/decoders. The binary decoding method can also be used when an encoder produced a non-JSON conformant hex or octal encoding C<\xNN> or C<\NNN>. Cpanel::JSON::XS->new->binary->encode (["\x{89}\x{abc}"]) 5.6: Error: malformed or illegal unicode character in binary string >=5.8: ['\x89\xe0\xaa\xbc'] Cpanel::JSON::XS->new->binary->encode (["\x{89}\x{bc}"]) => ["\x89\xbc"] Cpanel::JSON::XS->new->binary->decode (["\x89\ua001"]) Error: malformed or illegal unicode character in binary string Cpanel::JSON::XS->new->decode (["\x89"]) Error: illegal hex character in non-binary string =item $json = $json->utf8 ([$enable]) =item $enabled = $json->get_utf8 If C<$enable> is true (or missing), then the C method will encode the JSON result into UTF-8, as required by many protocols, while the C method expects to be handled an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any characters outside the range C<0..255>, they are thus useful for bytewise/binary I/O. In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32 encoding families, as described in RFC4627. If C<$enable> is false, then the C method will return the JSON string as a (non-encoded) Unicode string, while C expects thus a Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module. See also the section I later in this document. Example, output UTF-16BE-encoded JSON: use Encode; $jsontext = encode "UTF-16BE", Cpanel::JSON::XS->new->encode ($object); Example, decode UTF-32LE-encoded JSON: use Encode; $object = Cpanel::JSON::XS->new->decode (decode "UTF-32LE", $jsontext); =item $json = $json->pretty ([$enable]) This enables (or disables) all of the C, C and C (and in the future possibly more) flags in one call to generate the most readable (or most compact) form possible. Example, pretty-print some simple structure: my $json = Cpanel::JSON::XS->new->pretty(1)->encode ({a => [1,2]}) => { "a" : [ 1, 2 ] } =item $json = $json->indent ([$enable]) =item $enabled = $json->get_indent If C<$enable> is true (or missing), then the C method will use a multiline format as output, putting every array member or object/hash key-value pair into its own line, indenting them properly. If C<$enable> is false, no newlines or indenting will be produced, and the resulting JSON text is guaranteed not to contain any C. This setting has no effect when decoding JSON texts. =item $json = $json->space_before ([$enable]) =item $enabled = $json->get_space_before If C<$enable> is true (or missing), then the C method will add an extra optional space before the C<:> separating keys from values in JSON objects. If C<$enable> is false, then the C method will not add any extra space at those places. This setting has no effect when decoding JSON texts. You will also most likely combine this setting with C. Example, space_before enabled, space_after and indent disabled: {"key" :"value"} =item $json = $json->space_after ([$enable]) =item $enabled = $json->get_space_after If C<$enable> is true (or missing), then the C method will add an extra optional space after the C<:> separating keys from values in JSON objects and extra whitespace after the C<,> separating key-value pairs and array members. If C<$enable> is false, then the C method will not add any extra space at those places. This setting has no effect when decoding JSON texts. Example, space_before and indent disabled, space_after enabled: {"key": "value"} =item $json = $json->relaxed ([$enable]) =item $enabled = $json->get_relaxed If C<$enable> is true (or missing), then C will accept some extensions to normal JSON syntax (see below). C will not be affected in anyway. I. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.) If C<$enable> is false (the default), then C will only accept valid JSON texts. Currently accepted extensions are: =over 4 =item * list items can have an end-comma JSON I array elements and key-value pairs with commas. This can be annoying if you write JSON texts manually and want to be able to quickly append elements, so this extension accepts comma at the end of such items not just between them: [ 1, 2, <- this comma not normally allowed ] { "k1": "v1", "k2": "v2", <- this comma not normally allowed } =item * shell-style '#'-comments Whenever JSON allows whitespace, shell-style comments are additionally allowed. They are terminated by the first carriage-return or line-feed character, after which more white-space and comments are allowed. [ 1, # this comment not allowed in JSON # neither this one... ] =item * literal ASCII TAB characters in strings Literal ASCII TAB characters are now allowed in strings (and treated as C<\t>) in relaxed mode. Despite JSON mandates, that TAB character is substituted for "\t" sequence. [ "Hello\tWorld", "HelloWorld", # literal would not normally be allowed ] =item * allow_singlequote Single quotes are accepted instead of double quotes. See the L option. { "foo":'bar' } { 'foo':"bar" } { 'foo':'bar' } =item * allow_barekey Accept unquoted object keys instead of with mandatory double quotes. See the L option. { foo:"bar" } =back =item $json = $json->canonical ([$enable]) =item $enabled = $json->get_canonical If C<$enable> is true (or missing), then the C method will output JSON objects by sorting their keys. This is adding a comparatively high overhead. If C<$enable> is false, then the C method will output key-value pairs in the order Perl stores them (which will likely change between runs of the same script, and can change even within the same run from 5.18 onwards). This option is useful if you want the same data structure to be encoded as the same JSON text (given the same overall settings). If it is disabled, the same hash might be encoded differently even if contains the same data, as key-value pairs have no inherent ordering in Perl. This setting has no effect when decoding JSON texts. This setting has currently no effect on tied hashes. =item $json = $json->sort_by (undef, 0, 1 or a block) This currently only (un)sets the C option, and ignores custom sort blocks. This setting has no effect when decoding JSON texts. This setting has currently no effect on tied hashes. =item $json = $json->escape_slash ([$enable]) =item $enabled = $json->get_escape_slash According to the JSON Grammar, the I character (U+002F) C<"/"> need to be escaped. But by default strings are encoded without escaping slashes in all perl JSON encoders. If C<$enable> is true (or missing), then C will escape slashes, C<"\/">. This setting has no effect when decoding JSON texts. =item $json = $json->allow_singlequote ([$enable]) =item $enabled = $json->get_allow_singlequote $json = $json->allow_singlequote([$enable]) If C<$enable> is true (or missing), then C will accept JSON strings quoted by single quotations that are invalid JSON format. $json->allow_singlequote->decode({"foo":'bar'}); $json->allow_singlequote->decode({'foo':"bar"}); $json->allow_singlequote->decode({'foo':'bar'}); This is also enabled with C. As same as the C option, this option may be used to parse application-specific files written by humans. =item $json = $json->allow_barekey ([$enable]) =item $enabled = $json->get_allow_barekey $json = $json->allow_barekey([$enable]) If C<$enable> is true (or missing), then C will accept bare keys of JSON object that are invalid JSON format. Same as with the C option, this option may be used to parse application-specific files written by humans. $json->allow_barekey->decode('{foo:"bar"}'); =item $json = $json->allow_bignum ([$enable]) =item $enabled = $json->get_allow_bignum $json = $json->allow_bignum([$enable]) If C<$enable> is true (or missing), then C will convert the big integer Perl cannot handle as integer into a L object and convert a floating number (any) into a L. On the contrary, C converts C objects and C objects into JSON numbers with C enable. $json->allow_nonref->allow_blessed->allow_bignum; $bigfloat = $json->decode('2.000000000000000000000000001'); print $json->encode($bigfloat); # => 2.000000000000000000000000001 See L about the normal conversion of JSON number. =item $json = $json->allow_bigint ([$enable]) This option is obsolete and replaced by allow_bignum. =item $json = $json->allow_nonref ([$enable]) =item $enabled = $json->get_allow_nonref If C<$enable> is true (or missing), then the C method can convert a non-reference into its corresponding string, number or null JSON value, which is an extension to RFC4627. Likewise, C will accept those JSON values instead of croaking. If C<$enable> is false, then the C method will croak if it isn't passed an arrayref or hashref, as JSON texts must either be an object or array. Likewise, C will croak if given something that is not a JSON object or array. Example, encode a Perl scalar as JSON value with enabled C, resulting in an invalid JSON text: Cpanel::JSON::XS->new->allow_nonref->encode ("Hello, World!") => "Hello, World!" =item $json = $json->allow_unknown ([$enable]) =item $enabled = $json->get_allow_unknown If C<$enable> is true (or missing), then C will I throw an exception when it encounters values it cannot represent in JSON (for example, filehandles) but instead will encode a JSON C value. Note that blessed objects are not included here and are handled separately by c. If C<$enable> is false (the default), then C will throw an exception when it encounters anything it cannot encode as JSON. This option does not affect C in any way, and it is recommended to leave it off unless you know your communications partner. =item $json = $json->allow_stringify ([$enable]) =item $enabled = $json->get_allow_stringify If C<$enable> is true (or missing), then C will stringify the non-object perl value or reference. Note that blessed objects are not included here and are handled separately by C and C. String references are stringified to the string value, other references as in perl. This option does not affect C in any way. This option is special to this module, it is not supported by other encoders. So it is not recommended to use it. =item $json = $json->allow_blessed ([$enable]) =item $enabled = $json->get_allow_blessed If C<$enable> is true (or missing), then the C method will not barf when it encounters a blessed reference. Instead, the value of the B option will decide whether C (C disabled or no C method found) or a representation of the object (C enabled and C method found) is being encoded. Has no effect on C. If C<$enable> is false (the default), then C will throw an exception when it encounters a blessed object. This setting has no effect on C. =item $json = $json->convert_blessed ([$enable]) =item $enabled = $json->get_convert_blessed If C<$enable> is true (or missing), then C, upon encountering a blessed object, will check for the availability of the C method on the object's class. If found, it will be called in scalar context and the resulting scalar will be encoded instead of the object. If no C method is found, a stringification overload method is tried next. If both are not found, the value of C will decide what to do. The C method may safely call die if it wants. If C returns other blessed objects, those will be handled in the same way. C must take care of not causing an endless recursion cycle (== crash) in this case. The name of C was chosen because other methods called by the Perl core (== not by the user of the object) are usually in upper case letters and to avoid collisions with any C function or method. If C<$enable> is false (the default), then C will not consider this type of conversion. This setting has no effect on C. =item $json = $json->allow_tags ([$enable]) =item $enabled = $json->get_allow_tags See L for details. If C<$enable> is true (or missing), then C, upon encountering a blessed object, will check for the availability of the C method on the object's class. If found, it will be used to serialize the object into a nonstandard tagged JSON value (that JSON decoders cannot decode). It also causes C to parse such tagged JSON values and deserialize them via a call to the C method. If C<$enable> is false (the default), then C will not consider this type of conversion, and tagged JSON values will cause a parse error in C, as if tags were not part of the grammar. =item $json = $json->filter_json_object ([$coderef->($hashref)]) When C<$coderef> is specified, it will be called from C each time it decodes a JSON object. The only argument is a reference to the newly-created hash. If the code references returns a single scalar (which need not be a reference), this value (i.e. a copy of that scalar to avoid aliasing) is inserted into the deserialized data structure. If it returns an empty list (NOTE: I C, which is a valid scalar), the original deserialized hash will be inserted. This setting can slow down decoding considerably. When C<$coderef> is omitted or undefined, any existing callback will be removed and C will not change the deserialized hash in any way. Example, convert all JSON objects into the integer 5: my $js = Cpanel::JSON::XS->new->filter_json_object (sub { 5 }); # returns [5] $js->decode ('[{}]') # throw an exception because allow_nonref is not enabled # so a lone 5 is not allowed. $js->decode ('{"a":1, "b":2}'); =item $json = $json->filter_json_single_key_object ($key [=> $coderef->($value)]) Works remotely similar to C, but is only called for JSON objects having a single key named C<$key>. This C<$coderef> is called before the one specified via C, if any. It gets passed the single value in the JSON object. If it returns a single value, it will be inserted into the data structure. If it returns nothing (not even C but the empty list), the callback from C will be called next, as if no single-key callback were specified. If C<$coderef> is omitted or undefined, the corresponding callback will be disabled. There can only ever be one callback for a given key. As this callback gets called less often then the C one, decoding speed will not usually suffer as much. Therefore, single-key objects make excellent targets to serialize Perl objects into, especially as single-key JSON objects are as close to the type-tagged value concept as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not support this in any way, so you need to make sure your data never looks like a serialized Perl hash. Typical names for the single object key are C<__class_whatever__>, or C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even things like C<__class_md5sum(classname)__>, to reduce the risk of clashing with real hashes. Example, decode JSON objects of the form C<< { "__widget__" => } >> into the corresponding C<< $WIDGET{} >> object: # return whatever is in $WIDGET{5}: Cpanel::JSON::XS ->new ->filter_json_single_key_object (__widget__ => sub { $WIDGET{ $_[0] } }) ->decode ('{"__widget__": 5') # this can be used with a TO_JSON method in some "widget" class # for serialization to json: sub WidgetBase::TO_JSON { my ($self) = @_; unless ($self->{id}) { $self->{id} = ..get..some..id..; $WIDGET{$self->{id}} = $self; } { __widget__ => $self->{id} } } =item $json = $json->shrink ([$enable]) =item $enabled = $json->get_shrink Perl usually over-allocates memory a bit when allocating space for strings. This flag optionally resizes strings generated by either C or C to their minimum size possible. This can save memory when your JSON texts are either very very long or you have many short strings. It will also try to downgrade any strings to octet-form if possible: perl stores strings internally either in an encoding called UTF-X or in octet-form. The latter cannot store everything but uses less space in general (and some buggy Perl or C code might even rely on that internal representation being used). The actual definition of what shrink does might change in future versions, but it will always try to save space at the expense of time. If C<$enable> is true (or missing), the string returned by C will be shrunk-to-fit, while all strings generated by C will also be shrunk-to-fit. If C<$enable> is false, then the normal perl allocation algorithms are used. If you work with your data, then this is likely to be faster. In the future, this setting might control other things, such as converting strings that look like integers or floats into integers or floats internally (there is no difference on the Perl level), saving space. =item $json = $json->max_depth ([$maximum_nesting_depth]) =item $max_depth = $json->get_max_depth Sets the maximum nesting level (default C<512>) accepted while encoding or decoding. If a higher nesting level is detected in JSON text or a Perl data structure, then the encoder and decoder will stop and croak at that point. Nesting level is defined by number of hash- or arrayrefs that the encoder needs to traverse to reach a given point or the number of C<{> or C<[> characters without their matching closing parenthesis crossed to reach a given character in a string. Setting the maximum depth to one disallows any nesting, so that ensures that the object is only a single hash/object or array. If no argument is given, the highest possible setting will be used, which is rarely useful. Note that nesting is implemented by recursion in C. The default value has been chosen to be as large as typical operating systems allow without crashing. See SECURITY CONSIDERATIONS, below, for more info on why this is useful. =item $json = $json->max_size ([$maximum_string_size]) =item $max_size = $json->get_max_size Set the maximum length a JSON text may have (in bytes) where decoding is being attempted. The default is C<0>, meaning no limit. When C is called on a string that is longer then this many bytes, it will not attempt to decode the string but throw an exception. This setting has no effect on C (yet). If no argument is given, the limit check will be deactivated (same as when C<0> is specified). See SECURITY CONSIDERATIONS, below, for more info on why this is useful. =item $json->stringify_infnan ([$infnan_mode = 1]) =item $infnan_mode = $json->get_stringify_infnan Get or set how Cpanel::JSON::XS encodes C or C for numeric values. C: infnan_mode = 0. Similar to most JSON modules in other languages. stringified: infnan_mode = 1. As in Mojo::JSON. inf/nan: infnan_mode = 2. As in JSON::XS, and older releases. Produces invalid JSON. =item $json_text = $json->encode ($perl_scalar) Converts the given Perl data structure (a simple scalar or a reference to a hash or array) to its JSON representation. Simple scalars will be converted into JSON string or number sequences, while references to arrays become JSON arrays and references to hashes become JSON objects. Undefined Perl values (e.g. C) become JSON C values. Neither C nor C values will be generated. =item $perl_scalar = $json->decode ($json_text) The opposite of C: expects a JSON text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error. JSON numbers and strings become simple Perl scalars. JSON arrays become Perl arrayrefs and JSON objects become Perl hashrefs. C becomes C<1>, C becomes C<0> and C becomes C. =item ($perl_scalar, $characters) = $json->decode_prefix ($json_text) This works like the C method, but instead of raising an exception when there is trailing garbage after the first JSON object, it will silently stop parsing there and return the number of characters consumed so far. This is useful if your JSON texts are not delimited by an outer protocol and you need to know where the JSON text ends. Cpanel::JSON::XS->new->decode_prefix ("[1] the tail") => ([], 3) =item $json->to_json ($perl_hash_or_arrayref) Deprecated method for perl 5.8 and newer. Use L instead. =item $json->from_json ($utf8_encoded_json_text) Deprecated method for perl 5.8 and newer. Use L instead. =back =head1 INCREMENTAL PARSING In some cases, there is the need for incremental parsing of JSON texts. While this module always has to keep both JSON text and resulting Perl data structure in memory at one time, it does allow you to parse a JSON stream incrementally. It does so by accumulating text until it has a full JSON object, which it then can decode. This process is similar to using C to see if a full JSON object is available, but is much more efficient (and can be implemented with a minimum of method calls). Cpanel::JSON::XS will only attempt to parse the JSON text once it is sure it has enough text to get a decisive result, using a very simple but truly incremental parser. This means that it sometimes won't stop as early as the full parser, for example, it doesn't detect mismatched parentheses. The only thing it guarantees is that it starts decoding as soon as a syntactically valid JSON text has been seen. This means you need to set resource limits (e.g. C) to ensure the parser will stop parsing in the presence if syntax errors. The following methods implement this incremental parser. =over 4 =item [void, scalar or list context] = $json->incr_parse ([$string]) This is the central parsing function. It can both append new text and extract objects from the stream accumulated so far (both of these functions are optional). If C<$string> is given, then this string is appended to the already existing JSON fragment stored in the C<$json> object. After that, if the function is called in void context, it will simply return without doing anything further. This can be used to add more text in as many chunks as you want. If the method is called in scalar context, then it will try to extract exactly I JSON object. If that is successful, it will return this object, otherwise it will return C. If there is a parse error, this method will croak just as C would do (one can then use C to skip the erroneous part). This is the most common way of using the method. And finally, in list context, it will try to extract as many objects from the stream as it can find and return them, or the empty list otherwise. For this to work, there must be no separators between the JSON objects or arrays, instead they must be concatenated back-to-back. If an error occurs, an exception will be raised as in the scalar context case. Note that in this case, any previously-parsed JSON texts will be lost. Example: Parse some JSON arrays/objects in a given string and return them. my @objs = Cpanel::JSON::XS->new->incr_parse ("[5][7][1,2]"); =item $lvalue_string = $json->incr_text (>5.8 only) This method returns the currently stored JSON fragment as an lvalue, that is, you can manipulate it. This I works when a preceding call to C in I successfully returned an object, and 2. only with Perl >= 5.8 Under all other circumstances you must not call this function (I mean it. although in simple tests it might actually work, it I fail under real world conditions). As a special exception, you can also call this method before having parsed anything. This function is useful in two cases: a) finding the trailing text after a JSON object or b) parsing multiple JSON objects separated by non-JSON text (such as commas). =item $json->incr_skip This will reset the state of the incremental parser and will remove the parsed text from the input buffer so far. This is useful after C died, in which case the input buffer and incremental parser state is left unchanged, to skip the text parsed so far and to reset the parse state. The difference to C is that only text until the parse error occurred is removed. =item $json->incr_reset This completely resets the incremental parser, that is, after this call, it will be as if the parser had never parsed anything. This is useful if you want to repeatedly parse JSON objects and want to ignore any trailing data, which means you have to reset the parser after each successful decode. =back =head2 LIMITATIONS All options that affect decoding are supported, except C. The reason for this is that it cannot be made to work sensibly: JSON objects and arrays are self-delimited, i.e. you can concatenate them back to back and still decode them perfectly. This does not hold true for JSON numbers, however. For example, is the string C<1> a single JSON number, or is it simply the start of C<12>? Or is C<12> a single JSON number, or the concatenation of C<1> and C<2>? In neither case you can tell, and this is why Cpanel::JSON::XS takes the conservative route and disallows this case. =head2 EXAMPLES Some examples will make all this clearer. First, a simple example that works similarly to C: We want to decode the JSON object at the start of a string and identify the portion after the JSON object: my $text = "[1,2,3] hello"; my $json = new Cpanel::JSON::XS; my $obj = $json->incr_parse ($text) or die "expected JSON object or array at beginning of string"; my $tail = $json->incr_text; # $tail now contains " hello" Easy, isn't it? Now for a more complicated example: Imagine a hypothetical protocol where you read some requests from a TCP stream, and each request is a JSON array, without any separation between them (in fact, it is often useful to use newlines as "separators", as these get interpreted as whitespace at the start of the JSON text, which makes it possible to test said protocol with C...). Here is how you'd do it (it is trivial to write this in an event-based manner): my $json = new Cpanel::JSON::XS; # read some data from the socket while (sysread $socket, my $buf, 4096) { # split and decode as many requests as possible for my $request ($json->incr_parse ($buf)) { # act on the $request } } Another complicated example: Assume you have a string with JSON objects or arrays, all separated by (optional) comma characters (e.g. C<[1],[2], [3]>). To parse them, we have to skip the commas between the JSON texts, and here is where the lvalue-ness of C comes in useful: my $text = "[1],[2], [3]"; my $json = new Cpanel::JSON::XS; # void context, so no parsing done $json->incr_parse ($text); # now extract as many objects as possible. note the # use of scalar context so incr_text can be called. while (my $obj = $json->incr_parse) { # do something with $obj # now skip the optional comma $json->incr_text =~ s/^ \s* , //x; } Now lets go for a very complex example: Assume that you have a gigantic JSON array-of-objects, many gigabytes in size, and you want to parse it, but you cannot load it into memory fully (this has actually happened in the real world :). Well, you lost, you have to implement your own JSON parser. But Cpanel::JSON::XS can still help you: You implement a (very simple) array parser and let JSON decode the array elements, which are all full JSON objects on their own (this wouldn't work if the array elements could be JSON numbers, for example): my $json = new Cpanel::JSON::XS; # open the monster open my $fh, "incr_parse ($buf); # void context, so no parsing # Exit the loop once we found and removed(!) the initial "[". # In essence, we are (ab-)using the $json object as a simple scalar # we append data to. last if $json->incr_text =~ s/^ \s* \[ //x; } # now we have the skipped the initial "[", so continue # parsing all the elements. for (;;) { # in this loop we read data until we got a single JSON object for (;;) { if (my $obj = $json->incr_parse) { # do something with $obj last; } # add more data sysread $fh, my $buf, 65536 or die "read error: $!"; $json->incr_parse ($buf); # void context, so no parsing } # in this loop we read data until we either found and parsed the # separating "," between elements, or the final "]" for (;;) { # first skip whitespace $json->incr_text =~ s/^\s*//; # if we find "]", we are done if ($json->incr_text =~ s/^\]//) { print "finished.\n"; exit; } # if we find ",", we can continue with the next element if ($json->incr_text =~ s/^,//) { last; } # if we find anything else, we have a parse error! if (length $json->incr_text) { die "parse error near ", $json->incr_text; } # else add more data sysread $fh, my $buf, 65536 or die "read error: $!"; $json->incr_parse ($buf); # void context, so no parsing } This is a complex example, but most of the complexity comes from the fact that we are trying to be correct (bear with me if I am wrong, I never ran the above example :). =head1 MAPPING This section describes how Cpanel::JSON::XS maps Perl values to JSON values and vice versa. These mappings are designed to "do the right thing" in most circumstances automatically, preserving round-tripping characteristics (what you put in comes out as something equivalent). For the more enlightened: note that in the following descriptions, lowercase I refers to the Perl interpreter, while uppercase I refers to the abstract Perl language itself. =head2 JSON -> PERL =over 4 =item object A JSON object becomes a reference to a hash in Perl. No ordering of object keys is preserved (JSON does not preserve object key ordering itself). =item array A JSON array becomes a reference to an array in Perl. =item string A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON are represented by the same codepoints in the Perl string, so no manual decoding is necessary. =item number A JSON number becomes either an integer, numeric (floating point) or string scalar in perl, depending on its range and any fractional parts. On the Perl level, there is no difference between those as Perl handles all the conversion details, but an integer may take slightly less memory and might represent more values exactly than floating point numbers. If the number consists of digits only, Cpanel::JSON::XS will try to represent it as an integer value. If that fails, it will try to represent it as a numeric (floating point) value if that is possible without loss of precision. Otherwise it will preserve the number as a string value (in which case you lose roundtripping ability, as the JSON number will be re-encoded to a JSON string). Numbers containing a fractional or exponential part will always be represented as numeric (floating point) values, possibly at a loss of precision (in which case you might lose perfect roundtripping ability, but the JSON number will still be re-encoded as a JSON number). Note that precision is not accuracy - binary floating point values cannot represent most decimal fractions exactly, and when converting from and to floating point, C only guarantees precision up to but not including the least significant bit. =item true, false These JSON atoms become C and C, respectively. They are C objects and are overloaded to act almost exactly like the numbers C<1> and C<0>. You can check whether a scalar is a JSON boolean by using the C function. The other round, from perl to JSON, C which is represented as C becomes C, and C which is represented as C becomes C. =item null A JSON null atom becomes C in Perl. =item shell-style comments (C<< # I >>) As a nonstandard extension to the JSON syntax that is enabled by the C setting, shell-style comments are allowed. They can start anywhere outside strings and go till the end of the line. =item tagged values (C<< (I)I >>). Another nonstandard extension to the JSON syntax, enabled with the C setting, are tagged values. In this implementation, the I must be a perl package/class name encoded as a JSON string, and the I must be a JSON array encoding optional constructor arguments. See L, below, for details. =back =head2 PERL -> JSON The mapping from Perl to JSON is slightly more difficult, as Perl is a truly typeless language, so we can only guess which JSON type is meant by a Perl value. =over 4 =item hash references Perl hash references become JSON objects. As there is no inherent ordering in hash keys (or JSON objects), they will usually be encoded in a pseudo-random order that can change between runs of the same program but stays generally the same within a single run of a program. Cpanel::JSON::XS can optionally sort the hash keys (determined by the I flag), so the same datastructure will serialize to the same JSON text (given same settings and version of Cpanel::JSON::XS), but this incurs a runtime overhead and is only rarely useful, e.g. when you want to compare some JSON text against another for equality. =item array references Perl array references become JSON arrays. =item other references Other unblessed references are generally not allowed and will cause an exception to be thrown, except for references to the integers C<0> and C<1>, which get turned into C and C atoms in JSON. With the option C, you can ignore the exception and return the stringification of the perl value. With the option C, you can ignore the exception and return C instead. encode_json [\"x"] # => cannot encode reference to scalar 'SCALAR(0x..)' # unless the scalar is 0 or 1 encode_json [\0, \1] # yields [false,true] allow_stringify->encode_json [\"x"] # yields "x" unlike JSON::PP allow_unknown->encode_json [\"x"] # yields null as in JSON::PP =item Cpanel::JSON::XS::true, Cpanel::JSON::XS::false These special values become JSON true and JSON false values, respectively. You can also use C<\1> and C<\0> or C and C directly if you want. encode_json [Cpanel::JSON::XS::true, Cpanel::JSON::XS::true] # yields [false,true] encode_json [!1, !0] # yields [false,true] =item blessed objects Blessed objects are not directly representable in JSON, but C allows various optional ways of handling objects. See L, below, for details. See the C and C methods on various options on how to deal with this: basically, you can choose between throwing an exception, encoding the reference as if it weren't blessed, use the objects overloaded stringification method or provide your own serializer method. =item simple scalars Simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode: Cpanel::JSON::XS will encode undefined scalars or inf/nan as JSON C values, scalars that have last been used in a string context before encoding as JSON strings, and anything else as number value: # dump as number encode_json [2] # yields [2] encode_json [-3.0e17] # yields [-3e+17] my $value = 5; encode_json [$value] # yields [5] # used as string, but the two representations are for the same number print $value; encode_json [$value] # yields [5] # used as different string (non-matching dual-var) my $str = '0 but true'; my $num = 1 + $str; encode_json [$num, $str] # yields [1,"0 but true"] # undef becomes null encode_json [undef] # yields [null] # inf or nan becomes null, unless you answered # "Do you want to handle inf/nan as strings" with yes encode_json [9**9**9] # yields [null] You can force the type to be a JSON string by stringifying it: my $x = 3.1; # some variable containing a number "$x"; # stringified $x .= ""; # another, more awkward way to stringify print $x; # perl does it for you, too, quite often You can force the type to be a JSON number by numifying it: my $x = "3"; # some variable containing a string $x += 0; # numify it, ensuring it will be dumped as a number $x *= 1; # same thing, the choice is yours. Note that numerical precision has the same meaning as under Perl (so binary to decimal conversion follows the same rules as in Perl, which can differ to other languages). Also, your perl interpreter might expose extensions to the floating point numbers of your platform, such as infinities or NaN's - these cannot be represented in JSON, and thus null is returned instead. Optionally you can configure it to stringify inf and nan values. =back =head2 OBJECT SERIALIZATION As JSON cannot directly represent Perl objects, you have to choose between a pure JSON representation (without the ability to deserialize the object automatically again), and a nonstandard extension to the JSON syntax, tagged values. =head3 SERIALIZATION What happens when C encounters a Perl object depends on the C, C and C settings, which are used in this order: =over 4 =item 1. C is enabled and the object has a C method. In this case, C uses the L object serialization protocol to create a tagged JSON value, using a nonstandard extension to the JSON syntax. This works by invoking the C method on the object, with the first argument being the object to serialize, and the second argument being the constant string C to distinguish it from other serializers. The C method can return any number of values (i.e. zero or more). These values and the paclkage/classname of the object will then be encoded as a tagged JSON value in the following format: ("classname")[FREEZE return values...] e.g.: ("URI")["http://www.google.com/"] ("MyDate")[2013,10,29] ("ImageData::JPEG")["Z3...VlCg=="] For example, the hypothetical C C method might use the objects C and C members to encode the object: sub My::Object::FREEZE { my ($self, $serializer) = @_; ($self->{type}, $self->{id}) } =item 2. C is enabled and the object has a C method. In this case, the C method of the object is invoked in scalar context. It must return a single scalar that can be directly encoded into JSON. This scalar replaces the object in the JSON text. For example, the following C method will convert all L objects to JSON strings when serialized. The fact that these values originally were L objects is lost. sub URI::TO_JSON { my ($uri) = @_; $uri->as_string } =item 2. C is enabled and the object has a stringification overload. In this case, the overloaded C<""> method of the object is invoked in scalar context. It must return a single scalar that can be directly encoded into JSON. This scalar replaces the object in the JSON text. For example, the following C<""> method will convert all L objects to JSON strings when serialized. The fact that these values originally were L objects is lost. package URI; use overload '""' => sub { shift->as_string }; =item 3. C is enabled. The object will be serialized as a JSON null value. =item 4. none of the above If none of the settings are enabled or the respective methods are missing, C throws an exception. =back =head3 DESERIALIZATION For deserialization there are only two cases to consider: either nonstandard tagging was used, in which case C decides, or objects cannot be automatically be deserialized, in which case you can use postprocessing or the C or C callbacks to get some real objects our of your JSON. This section only considers the tagged value case: I a tagged JSON object is encountered during decoding and C is disabled, a parse error will result (as if tagged values were not part of the grammar). If C is enabled, C will look up the C method of the package/classname used during serialization (it will not attempt to load the package as a Perl module). If there is no such method, the decoding will fail with an error. Otherwise, the C method is invoked with the classname as first argument, the constant string C as second argument, and all the values from the JSON array (the values originally returned by the C method) as remaining arguments. The method must then return the object. While technically you can return any Perl scalar, you might have to enable the C setting to make that work in all cases, so better return an actual blessed reference. As an example, let's implement a C function that regenerates the C from the C example earlier: sub My::Object::THAW { my ($class, $serializer, $type, $id) = @_; $class->new (type => $type, id => $id) } See the L section below. Allowing external json objects being deserialized to perl objects is usually a very bad idea. =head1 ENCODING/CODESET FLAG NOTES The interested reader might have seen a number of flags that signify encodings or codesets - C, C, C and C. There seems to be some confusion on what these do, so here is a short comparison: C controls whether the JSON text created by C (and expected by C) is UTF-8 encoded or not, while C and C only control whether C escapes character values outside their respective codeset range. Neither of these flags conflict with each other, although some combinations make less sense than others. Care has been taken to make all flags symmetrical with respect to C and C, that is, texts encoded with any combination of these flag values will be correctly decoded when the same flags are used - in general, if you use different flag settings while encoding vs. when decoding you likely have a bug somewhere. Below comes a verbose discussion of these flags. Note that a "codeset" is simply an abstract set of character-codepoint pairs, while an encoding takes those codepoint numbers and I them, in our case into octets. Unicode is (among other things) a codeset, UTF-8 is an encoding, and ISO-8859-1 (= latin 1) and ASCII are both codesets I encodings at the same time, which can be confusing. =over 4 =item C flag disabled When C is disabled (the default), then C/C generate and expect Unicode strings, that is, characters with high ordinal Unicode values (> 255) will be encoded as such characters, and likewise such characters are decoded as-is, no changes to them will be done, except "(re-)interpreting" them as Unicode codepoints or Unicode characters, respectively (to Perl, these are the same thing in strings unless you do funny/weird/dumb stuff). This is useful when you want to do the encoding yourself (e.g. when you want to have UTF-16 encoded JSON texts) or when some other layer does the encoding for you (for example, when printing to a terminal using a filehandle that transparently encodes to UTF-8 you certainly do NOT want to UTF-8 encode your data first and have Perl encode it another time). =item C flag enabled If the C-flag is enabled, C/C will encode all characters using the corresponding UTF-8 multi-byte sequence, and will expect your input strings to be encoded as UTF-8, that is, no "character" of the input string must have any value > 255, as UTF-8 does not allow that. The C flag therefore switches between two modes: disabled means you will get a Unicode string in Perl, enabled means you get an UTF-8 encoded octet/binary string in Perl. =item C, C or C flags enabled With C (or C) enabled, C will escape characters with ordinal values > 255 (> 127 with C) and encode the remaining characters as specified by the C flag. With C enabled, ordinal values > 255 are illegal. If C is disabled, then the result is also correctly encoded in those character sets (as both are proper subsets of Unicode, meaning that a Unicode string with all character values < 256 is the same thing as a ISO-8859-1 string, and a Unicode string with all character values < 128 is the same thing as an ASCII string in Perl). If C is enabled, you still get a correct UTF-8-encoded string, regardless of these flags, just some more characters will be escaped using C<\uXXXX> then before. Note that ISO-8859-1-I strings are not compatible with UTF-8 encoding, while ASCII-encoded strings are. That is because the ISO-8859-1 encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 I being a subset of Unicode), while ASCII is. Surprisingly, C will ignore these flags and so treat all input values as governed by the C flag. If it is disabled, this allows you to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings. So neither C, C nor C are incompatible with the C flag - they only govern when the JSON output engine escapes a character or not. The main use for C or C is to relatively efficiently store binary data as JSON, at the expense of breaking compatibility with most JSON decoders. The main use for C is to force the output to not contain characters with values > 127, which means you can interpret the resulting string as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and 8-bit-encoding, and still get the same data structure back. This is useful when your channel for JSON transfer is not 8-bit clean or the encoding might be mangled in between (e.g. in mail), and works because ASCII is a proper subset of most 8-bit and multibyte encodings in use in the world. =back =head2 JSON and ECMAscript JSON syntax is based on how literals are represented in javascript (the not-standardized predecessor of ECMAscript) which is presumably why it is called "JavaScript Object Notation". However, JSON is not a subset (and also not a superset of course) of ECMAscript (the standard) or javascript (whatever browsers actually implement). If you want to use javascript's C function to "parse" JSON, you might run into parse errors for valid JSON texts, or the resulting data structure might not be queryable: One of the problems is that U+2028 and U+2029 are valid characters inside JSON strings, but are not allowed in ECMAscript string literals, so the following Perl fragment will not output something that can be guaranteed to be parsable by javascript's C: use Cpanel::JSON::XS; print encode_json [chr 0x2028]; The right fix for this is to use a proper JSON parser in your javascript programs, and not rely on C (see for example Douglas Crockford's F parser). If this is not an option, you can, as a stop-gap measure, simply encode to ASCII-only JSON: use Cpanel::JSON::XS; print Cpanel::JSON::XS->new->ascii->encode ([chr 0x2028]); Note that this will enlarge the resulting JSON text quite a bit if you have many non-ASCII characters. You might be tempted to run some regexes to only escape U+2028 and U+2029, e.g.: # DO NOT USE THIS! my $json = Cpanel::JSON::XS->new->utf8->encode ([chr 0x2028]); $json =~ s/\xe2\x80\xa8/\\u2028/g; # escape U+2028 $json =~ s/\xe2\x80\xa9/\\u2029/g; # escape U+2029 print $json; Note that I: the above only works for U+2028 and U+2029 and thus only for fully ECMAscript-compliant parsers. Many existing javascript implementations, however, have issues with other characters as well - using C naively simply I cause problems. Another problem is that some javascript implementations reserve some property names for their own purposes (which probably makes them non-ECMAscript-compliant). For example, Iceweasel reserves the C<__proto__> property name for its own purposes. If that is a problem, you could parse try to filter the resulting JSON output for these property strings, e.g.: $json =~ s/"__proto__"\s*:/"__proto__renamed":/g; This works because C<__proto__> is not valid outside of strings, so every occurrence of C<"__proto__"\s*:> must be a string used as property name. If you know of other incompatibilities, please let me know. =head2 JSON and YAML You often hear that JSON is a subset of YAML. I that works in all cases. If you really must use Cpanel::JSON::XS to generate YAML, you should use this algorithm (subject to change in future versions): my $to_yaml = Cpanel::JSON::XS->new->utf8->space_after (1); my $yaml = $to_yaml->encode ($ref) . "\n"; This will I generate JSON texts that also parse as valid YAML. =head2 SPEED It seems that JSON::XS is surprisingly fast, as shown in the following tables. They have been generated with the help of the C program in the JSON::XS distribution, to make it easy to compare on your own system. JSON::XS is with L and L one of the fastest serializers, because JSON and JSON::XS do not support backrefs (no graph structures), only trees. Storable supports backrefs, i.e. graphs. Data::MessagePack encodes its data binary (as Storable) and supports only very simple subset of JSON. First comes a comparison between various modules using a very short single-line JSON string (also available at L). {"method": "handleMessage", "params": ["user1", "we were just talking"], "id": null, "array":[1,11,234,-5,1e5,1e7, 1, 0]} It shows the number of encodes/decodes per second (JSON::XS uses the functional interface, while Cpanel::JSON::XS/2 uses the OO interface with pretty-printing and hash key sorting enabled, Cpanel::JSON::XS/3 enables shrink. JSON::DWIW/DS uses the deserialize function, while JSON::DWIW::FJ uses the from_json method). Higher is better: module | encode | decode | --------------|------------|------------| JSON::DWIW/DS | 86302.551 | 102300.098 | JSON::DWIW/FJ | 86302.551 | 75983.768 | JSON::PP | 15827.562 | 6638.658 | JSON::Syck | 63358.066 | 47662.545 | JSON::XS | 511500.488 | 511500.488 | JSON::XS/2 | 291271.111 | 388361.481 | JSON::XS/3 | 361577.931 | 361577.931 | Storable | 66788.280 | 265462.278 | --------------+------------+------------+ That is, JSON::XS is almost six times faster than JSON::DWIW on encoding, about five times faster on decoding, and over thirty to seventy times faster than JSON's pure perl implementation. It also compares favourably to Storable for small amounts of data. Using a longer test string (roughly 18KB, generated from Yahoo! Locals search API (L). module | encode | decode | --------------|------------|------------| JSON::DWIW/DS | 1647.927 | 2673.916 | JSON::DWIW/FJ | 1630.249 | 2596.128 | JSON::PP | 400.640 | 62.311 | JSON::Syck | 1481.040 | 1524.869 | JSON::XS | 20661.596 | 9541.183 | JSON::XS/2 | 10683.403 | 9416.938 | JSON::XS/3 | 20661.596 | 9400.054 | Storable | 19765.806 | 10000.725 | --------------+------------+------------+ Again, JSON::XS leads by far (except for Storable which non-surprisingly decodes a bit faster). On large strings containing lots of high Unicode characters, some modules (such as JSON::PC) seem to decode faster than JSON::XS, but the result will be broken due to missing (or wrong) Unicode handling. Others refuse to decode or encode properly, so it was impossible to prepare a fair comparison table for that case. For updated graphs see L =head1 INTEROP with JSON and JSON::XS and other JSON modules JSON-XS-3.01 broke interoperability with JSON-2.90 with booleans. See L. Cpanel::JSON::XS needs to know the JSON and JSON::XS versions to be able work with those objects, especially when encoding a booleans like C<{"is_true":true}>. So you need to load these modules before. true/false overloading and boolean representations are supported. JSON::XS and JSON::PP representations are accepted and older JSON::XS accepts Cpanel::JSON::XS booleans. All JSON modules JSON, JSON, PP, JSON::XS, Cpanel::JSON::XS produce JSON::PP::Boolean objects, just Mojo and JSON::YAJL not. Mojo produces Mojo::JSON::_Bool and JSON::YAJL::Parser just an unblessed IV. Cpanel::JSON::XS accepts JSON::PP::Boolean and Mojo::JSON::_Bool objects as booleans. I cannot think of any reason to still use JSON::XS anymore. =head1 SECURITY CONSIDERATIONS JSON::XS is not only fast, JSON is generally the most secure serializing format, because it is the only one besides Data::MessagePack, which does not deserialize objects per default. For all languages, not just perl. The binary variant BSON (MongoDB) does more but is unsafe. It is trivial for any attacker to create such serialized objects in JSON and trick perl into expanding them, thereby triggering certain methods. Watch L for an exploit demo for "CVE-2015-1592 SixApart MovableType Storable Perl Code Execution" for a deserializer which expands objects. Deserializing even coderefs (methods, functions) or external data would be considered the most dangerous. Security relevant overview of serializers regarding deserializing objects by default: Objects Coderefs External Data Data::Dumper YES YES YES Storable YES NO (def) NO Sereal YES NO NO YAML YES NO NO B::C YES YES YES B::Bytecode YES YES YES BSON YES YES NO JSON::SL YES NO YES JSON NO (def) NO NO Data::MessagePack NO NO NO XML NO NO YES Pickle YES YES YES PHP Deserialize YES NO NO When you are using JSON in a protocol, talking to untrusted potentially hostile creatures requires relatively few measures. First of all, your JSON decoder should be secure, that is, should not have any buffer overflows. Obviously, this module should ensure that. Second, you need to avoid resource-starving attacks. That means you should limit the size of JSON texts you accept, or make sure then when your resources run out, that's just fine (e.g. by using a separate process that can crash safely). The size of a JSON text in octets or characters is usually a good indication of the size of the resources required to decode it into a Perl structure. While JSON::XS can check the size of the JSON text, it might be too late when you already have it in memory, so you might want to check the size before you accept the string. Third, Cpanel::JSON::XS recurses using the C stack when decoding objects and arrays. The C stack is a limited resource: for instance, on my amd64 machine with 8MB of stack size I can decode around 180k nested arrays but only 14k nested JSON objects (due to perl itself recursing deeply on croak to free the temporary). If that is exceeded, the program crashes. To be conservative, the default nesting limit is set to 512. If your process has a smaller stack, you should adjust this setting accordingly with the C method. Also keep in mind that Cpanel::JSON::XS might leak contents of your Perl data structures in its error messages, so when you serialize sensitive information you might want to make sure that exceptions thrown by JSON::XS will not end up in front of untrusted eyes. If you are using Cpanel::JSON::XS to return packets to consumption by JavaScript scripts in a browser you should have a look at L to see whether you are vulnerable to some common attack vectors (which really are browser design bugs, but it is still you who will have to deal with it, as major browser developers care only for features, not about getting security right). You might also want to also look at L special escape rules to prevent from XSS attacks. =head1 THREADS Cpanel::JSON::XS has proper ithreads support, unlike JSON::XS. If you encounter any bugs with thread support please report them. =head1 BUGS While the goal of the Cpanel::JSON::XS module is to be correct, that unfortunately does not mean it's bug-free, only that the author thinks its design is bug-free. If you keep reporting bugs and tests they will be fixed swiftly, though. Since the JSON::XS author refuses to use a public bugtracker and prefers private emails, we've setup a tracker at RT, so you might want to report any issues twice. Once in private to MLEHMANN to be fixed in JSON::XS and one to our the public tracker. Issues fixed by JSON::XS with a new release will also be backported to Cpanel::JSON::XS and 5.6.2, as long as cPanel relies on 5.6.2 and Cpanel::JSON::XS as our serializer of choice. L =head1 LICENSE This module is available under the same licences as perl, the Artistic license and the GPL. =cut sub allow_bigint { Carp::carp("allow_bigint() is obsoleted. use allow_bignum() instead."); } our ($true, $false); BEGIN { if ($INC{'JSON/XS.pm'} and $INC{'Types/Serialiser.pm'} and $JSON::XS::VERSION ge "3.00") { $true = $Types::Serialiser::true; # readonly if loaded by JSON::XS $false = $Types::Serialiser::false; } else { $true = do { bless \(my $dummy = 1), "JSON::PP::Boolean" }; $false = do { bless \(my $dummy = 0), "JSON::PP::Boolean" }; } } sub true() { $true } sub false() { $false } sub is_bool($) { shift if @_ == 2; # as method call (ref($_[0]) and UNIVERSAL::isa( $_[0], JSON::PP::Boolean::)) or (exists $INC{'Types/Serializer.pm'} and Types::Serialiser::is_bool($_[0])) } XSLoader::load 'Cpanel::JSON::XS', $VERSION; package JSON::PP::Boolean; use overload "0+" => sub { ${$_[0]} }, "++" => sub { $_[0] = ${$_[0]} + 1 }, "--" => sub { $_[0] = ${$_[0]} - 1 }, '""' => sub { ${$_[0]} == 1 ? 'true' : '0' }, # GH 29 'eq' => sub { my ($obj, $op) = ref ($_[0]) ? ($_[0], $_[1]) : ($_[1], $_[0]); if ($op eq 'true' or $op eq 'false') { return "$obj" eq 'true' ? 'true' eq $op : 'false' eq $op; } else { return $obj ? 1 == $op : 0 == $op; } }, fallback => 1; 1; =head1 SEE ALSO The F command line utility for quick experiments. L, L, L, L, L, L, L, L, L, L, L, L L L =head1 AUTHOR Marc Lehmann , http://home.schmorp.de/ Reini Urban , http://cpanel.net/ =head1 MAINTAINER Reini Urban =cut Cpanel-JSON-XS-3.0210/XS.xs0000644000076500001200000033531712630007326014157 0ustar rurbanadmin#define PERL_NO_GET_CONTEXT #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #define NEED_PL_parser #define NEED_grok_number #define NEED_grok_numeric_radix #define NEED_newRV_noinc #define NEED_sv_2pv_flags #include "ppport.h" #include #include #include #include #include #include #if defined(__BORLANDC__) || defined(_MSC_VER) # define snprintf _snprintf // C compilers have this in stdio.h #endif #if defined(_AIX) && (!defined(HAS_LONG_DOUBLE) || AIX_WORKAROUND) #define HAVE_NO_POWL #endif /* Freebsd 10: It has powl, but it is too bad. strtold is good. RT #101265 */ #if defined(__FreeBSD__) && defined(__clang__) && defined(USE_LONG_DOUBLE) #define HAVE_BAD_POWL #endif #if defined(_WIN32) #define STR_INF "1.#INF" #define STR_NAN "1.#IND" #define STR_QNAN "1.#QNAN" #else #if defined(sun) || defined(__sun) #define STR_INF "Infinity" #define STR_NAN "NaN" #else #define STR_INF "inf" #define STR_NAN "nan" #endif #endif /* some old perls do not have this, try to make it work, no */ /* guarantees, though. if it breaks, you get to keep the pieces. */ #ifndef UTF8_MAXBYTES # define UTF8_MAXBYTES 13 #endif /* 5.6: */ #ifndef IS_NUMBER_IN_UV #define IS_NUMBER_IN_UV 0x01 /* number within UV range (maybe not int). value returned in pointed- to UV */ #define IS_NUMBER_GREATER_THAN_UV_MAX 0x02 /* pointed to UV undefined */ #define IS_NUMBER_NOT_INT 0x04 /* saw . or E notation */ #define IS_NUMBER_NEG 0x08 /* leading minus sign */ #define IS_NUMBER_INFINITY 0x10 /* this is big */ #define IS_NUMBER_NAN 0x20 /* this is not */ #endif #ifndef UNI_DISPLAY_QQ #define UNI_DISPLAY_ISPRINT 0x0001 #define UNI_DISPLAY_BACKSLASH 0x0002 #define UNI_DISPLAY_QQ (UNI_DISPLAY_ISPRINT|UNI_DISPLAY_BACKSLASH) #define UNI_DISPLAY_REGEX (UNI_DISPLAY_ISPRINT|UNI_DISPLAY_BACKSLASH) #endif /* with 5.6 hek can only be non-utf8 */ #ifndef HeKUTF8 #define HeKUTF8(he) 0 #endif /* since 5.8.1 */ #ifndef SvIsCOW_shared_hash #define SvIsCOW_shared_hash(pv) 0 #endif /* compatibility with perl <5.14 */ #ifndef HvNAMELEN_get # define HvNAMELEN_get(hv) strlen (HvNAME (hv)) #endif #ifndef HvNAMELEN # define HvNAMELEN(hv) HvNAMELEN_get (hv) #endif #ifndef HvNAMEUTF8 # define HvNAMEUTF8(hv) 0 #endif /* three extra for rounding, sign, and end of string */ #define IVUV_MAXCHARS (sizeof (UV) * CHAR_BIT * 28 / 93 + 3) #define F_ASCII 0x00000001UL #define F_LATIN1 0x00000002UL #define F_UTF8 0x00000004UL #define F_INDENT 0x00000008UL #define F_CANONICAL 0x00000010UL #define F_SPACE_BEFORE 0x00000020UL #define F_SPACE_AFTER 0x00000040UL #define F_ALLOW_NONREF 0x00000100UL #define F_SHRINK 0x00000200UL #define F_ALLOW_BLESSED 0x00000400UL #define F_CONV_BLESSED 0x00000800UL #define F_RELAXED 0x00001000UL #define F_ALLOW_UNKNOWN 0x00002000UL #define F_ALLOW_TAGS 0x00004000UL #define F_BINARY 0x00008000UL #define F_ALLOW_BAREKEY 0x00010000UL #define F_ALLOW_SQUOTE 0x00020000UL #define F_ALLOW_BIGNUM 0x00040000UL #define F_ESCAPE_SLASH 0x00080000UL #define F_SORT_BY 0x00100000UL #define F_ALLOW_STRINGIFY 0x00200000UL #define F_HOOK 0x80000000UL // some hooks exist, so slow-path processing #define F_PRETTY F_INDENT | F_SPACE_BEFORE | F_SPACE_AFTER #define SET_RELAXED (F_RELAXED | F_ALLOW_BAREKEY | F_ALLOW_SQUOTE) #define INIT_SIZE 32 // initial scalar size to be allocated #define INDENT_STEP 3 // spaces per indentation level #define SHORT_STRING_LEN 16384 // special-case strings of up to this size #if PERL_VERSION >= 8 #define DECODE_WANTS_OCTETS(json) ((json)->flags & F_UTF8) #else #define DECODE_WANTS_OCTETS(json) (0) #endif #define SB do { #define SE } while (0) #if __GNUC__ >= 3 # define _expect(expr,value) __builtin_expect ((expr), (value)) # define INLINE static inline #else # define _expect(expr,value) (expr) # define INLINE static #endif #define expect_false(expr) _expect ((expr) != 0, 0) #define expect_true(expr) _expect ((expr) != 0, 1) #define IN_RANGE_INC(type,val,beg,end) \ ((unsigned type)((unsigned type)(val) - (unsigned type)(beg)) \ <= (unsigned type)((unsigned type)(end) - (unsigned type)(beg))) #define ERR_NESTING_EXCEEDED "json text or perl structure exceeds maximum nesting level (max_depth set too low?)" # define JSON_STASH MY_CXT.json_stash #define MY_CXT_KEY "Cpanel::JSON::XS::_guts" typedef struct { HV *json_stash; /* Cpanel::JSON::XS:: */ HV *json_boolean_stash; /* JSON::PP::Boolean:: */ HV *jsonold_boolean_stash; /* JSON::XS::Boolean:: if empty will be (HV*)1 */ HV *mojo_boolean_stash; /* Mojo::JSON::_Bool:: if empty will be (HV*)1 */ SV *json_true, *json_false; SV *sv_json; } my_cxt_t; // the amount of HEs to allocate on the stack, when sorting keys #define STACK_HES 64 START_MY_CXT INLINE SV * get_bool (pTHX_ const char *name); enum { INCR_M_WS = 0, /* initial whitespace skipping, must be 0 */ INCR_M_STR, /* inside string */ INCR_M_BS, /* inside backslash */ INCR_M_C0, /* inside comment in initial whitespace sequence */ INCR_M_C1, /* inside comment in other places */ INCR_M_JSON /* outside anything, count nesting */ }; #define INCR_DONE(json) ((json)->incr_nest <= 0 && (json)->incr_mode == INCR_M_JSON) typedef struct { U32 flags; U32 max_depth; STRLEN max_size; SV *cb_object; HV *cb_sk_object; SV *cb_sort_by; /* for the incremental parser */ SV *incr_text; /* the source text so far */ STRLEN incr_pos; /* the current offset into the text */ int incr_nest; /* {[]}-nesting level */ unsigned char incr_mode; unsigned char infnan_mode; } JSON; INLINE void json_init (JSON *json) { Zero (json, 1, JSON); json->max_depth = 512; } /* dTHX/threads TODO*/ /* END dtor call not needed, all of these *s refcnts are owned by the stash treem not C code */ static void init_MY_CXT(pTHX_ my_cxt_t * cxt) { cxt->json_stash = gv_stashpvn ("Cpanel::JSON::XS", sizeof("Cpanel::JSON::XS")-1, 1); cxt->json_boolean_stash = gv_stashpvn ("JSON::PP::Boolean", sizeof("JSON::PP::Boolean")-1, 1); cxt->jsonold_boolean_stash = gv_stashpvn ("JSON::XS::Boolean", sizeof("JSON::XS::Boolean")-1, 0); cxt->mojo_boolean_stash = gv_stashpvn ("Mojo::JSON::_Bool", sizeof("Mojo::JSON::_Bool")-1, 0); if ( !cxt->mojo_boolean_stash ) cxt->mojo_boolean_stash = (HV*)1; /* invalid ptr to compare against, better than a NULL stash */ if ( !cxt->jsonold_boolean_stash ) cxt->jsonold_boolean_stash = (HV*)1; cxt->json_true = get_bool (aTHX_ "Cpanel::JSON::XS::true"); cxt->json_false = get_bool (aTHX_ "Cpanel::JSON::XS::false"); cxt->sv_json = newSVpv ("JSON", 0); SvREADONLY_on (cxt->sv_json); } /*/////////////////////////////////////////////////////////////////////////// */ /* utility functions */ /* Unpacks the 2 boolean objects from the global references */ INLINE SV * get_bool (pTHX_ const char *name) { dMY_CXT; SV *sv = get_sv (name, 1); SV* rv = SvRV(sv); if (!SvOBJECT(sv) || !SvSTASH(sv)) { SvREADONLY_off (sv); SvREADONLY_off (rv); (void)sv_bless(sv, MY_CXT.json_boolean_stash); /* bless the ref */ } SvREADONLY_on (rv); SvREADONLY_on (sv); return sv; } INLINE void shrink (pTHX_ SV *sv) { sv_utf8_downgrade (sv, 1); if (SvLEN (sv) > SvCUR (sv) + 1) { #ifdef SvPV_shrink_to_cur SvPV_shrink_to_cur (sv); #elif defined (SvPV_renew) SvPV_renew (sv, SvCUR (sv) + 1); #endif } } /* decode an utf-8 character and return it, or (UV)-1 in */ /* case of an error. */ /* we special-case "safe" characters from U+80 .. U+7FF, */ /* but use the very good perl function to parse anything else. */ /* note that we never call this function for a ascii codepoints */ INLINE UV decode_utf8 (pTHX_ unsigned char *s, STRLEN len, STRLEN *clen) { if (expect_true (len >= 2 && IN_RANGE_INC (char, s[0], 0xc2, 0xdf) && IN_RANGE_INC (char, s[1], 0x80, 0xbf))) { *clen = 2; return ((s[0] & 0x1f) << 6) | (s[1] & 0x3f); } else { #if PERL_VERSION >= 8 return utf8n_to_uvuni (s, len, clen, UTF8_CHECK_ONLY); #else /* for perl 5.6 */ return utf8_to_uv(s, len, clen, UTF8_CHECK_ONLY); #endif } } /* likewise for encoding, also never called for ascii codepoints */ /* this function takes advantage of this fact, although current gccs */ /* seem to optimise the check for >= 0x80 away anyways */ INLINE unsigned char * encode_utf8 (unsigned char *s, UV ch) { if (expect_false (ch < 0x000080)) *s++ = ch; else if (expect_true (ch < 0x000800)) *s++ = 0xc0 | ( ch >> 6), *s++ = 0x80 | ( ch & 0x3f); else if ( ch < 0x010000) *s++ = 0xe0 | ( ch >> 12), *s++ = 0x80 | ((ch >> 6) & 0x3f), *s++ = 0x80 | ( ch & 0x3f); else if ( ch < 0x110000) *s++ = 0xf0 | ( ch >> 18), *s++ = 0x80 | ((ch >> 12) & 0x3f), *s++ = 0x80 | ((ch >> 6) & 0x3f), *s++ = 0x80 | ( ch & 0x3f); return s; } /* convert offset pointer to character index, sv must be string */ static STRLEN ptr_to_index (pTHX_ SV *sv, const U8 *offset) { return SvUTF8 (sv) ? utf8_distance ((U8*)offset, (U8*)SvPVX (sv)) : offset - (U8*)SvPVX (sv); } /*/////////////////////////////////////////////////////////////////////////// */ /* fp hell */ #ifdef HAVE_NO_POWL /* Ulisse Monari: this is a patch for AIX 5.3, perl 5.8.8 without HAS_LONG_DOUBLE There Perl_pow maps to pow(...) - NOT TO powl(...), core dumps at Perl_pow(...) Base code is from http://bytes.com/topic/c/answers/748317-replacement-pow-function This is my change to fs_pow that goes into libc/libm for calling fmod/exp/log. NEED TO MODIFY Makefile, after perl Makefile.PL by adding "-lm" onto the LDDLFLAGS line */ static double fs_powEx(double x, double y) { double p = 0; if (0 > x && fmod(y, 1) == 0) { if (fmod(y, 2) == 0) { p = exp(log(-x) * y); } else { p = -exp(log(-x) * y); } } else { if (x != 0 || 0 >= y) { p = exp(log( x) * y); } } return p; } #endif /* scan a group of digits, and a trailing exponent */ static void json_atof_scan1 (const char *s, NV *accum, int *expo, int postdp, int maxdepth) { UV uaccum = 0; int eaccum = 0; #if defined(HAVE_BAD_POWL) *accum = strtold(s, NULL); #else /* if we recurse too deep, skip all remaining digits */ /* to avoid a stack overflow attack */ if (expect_false (--maxdepth <= 0)) while (((U8)*s - '0') < 10) ++s; for (;;) { U8 dig = (U8)*s - '0'; if (expect_false (dig >= 10)) { if (dig == (U8)((U8)'.' - (U8)'0')) { ++s; json_atof_scan1 (s, accum, expo, 1, maxdepth); } else if ((dig | ' ') == 'e' - '0') { int exp2 = 0; int neg = 0; ++s; if (*s == '-') { ++s; neg = 1; } else if (*s == '+') ++s; while ((dig = (U8)*s - '0') < 10) exp2 = exp2 * 10 + *s++ - '0'; *expo += neg ? -exp2 : exp2; } break; } ++s; uaccum = uaccum * 10 + dig; ++eaccum; /* if we have too many digits, then recurse for more */ /* we actually do this for rather few digits */ if (uaccum >= (UV_MAX - 9) / 10) { if (postdp) *expo -= eaccum; json_atof_scan1 (s, accum, expo, postdp, maxdepth); if (postdp) *expo += eaccum; break; } } /* this relies greatly on the quality of the pow () */ /* implementation of the platform, but a good */ /* implementation is hard to beat. */ /* (IEEE 754 conformant ones are required to be exact) */ if (postdp) *expo -= eaccum; #ifdef HAVE_NO_POWL /* powf() unfortunately is not accurate enough */ *accum += uaccum * fs_powEx(10., *expo ); #else *accum += uaccum * Perl_pow (10., *expo); #endif *expo += eaccum; #endif } static NV json_atof (const char *s) { NV accum = 0.; int expo = 0; int neg = 0; if (*s == '-') { ++s; neg = 1; } /* a recursion depth of ten gives us >>500 bits */ json_atof_scan1 (s, &accum, &expo, 0, 10); return neg ? -accum : accum; } /*/////////////////////////////////////////////////////////////////////////// */ /* encoder */ /* structure used for encoding JSON */ typedef struct { char *cur; /* SvPVX (sv) + current output position */ char *end; /* SvEND (sv) */ SV *sv; /* result scalar */ JSON json; U32 indent; /* indentation level */ UV limit; /* escape character values >= this value when encoding */ } enc_t; INLINE void need (pTHX_ enc_t *enc, STRLEN len) { if (expect_false (enc->cur + len >= enc->end)) { STRLEN cur = enc->cur - (char *)SvPVX (enc->sv); SvGROW (enc->sv, cur + (len < (cur >> 2) ? cur >> 2 : len) + 1); enc->cur = SvPVX (enc->sv) + cur; enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1; } } INLINE void encode_ch (pTHX_ enc_t *enc, char ch) { need (aTHX_ enc, 1); *enc->cur++ = ch; } static void encode_str (pTHX_ enc_t *enc, char *str, STRLEN len, int is_utf8) { char *end = str + len; #if PERL_VERSION < 8 /* perl5.6 encodes to utf8 automatically, reverse it */ if (is_utf8 && (enc->json.flags & F_BINARY)) { str = (char *)utf8_to_bytes((U8*)str, &len); if (!str) croak ("illegal unicode character in binary string", str); end = str + len; } #endif need (aTHX_ enc, len); while (str < end) { unsigned char ch = *(unsigned char *)str; if (expect_true (ch >= 0x20 && ch < 0x80)) /* most common case */ { if (expect_false (ch == '"')) /* but with slow exceptions */ { need (aTHX_ enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = '"'; } else if (expect_false (ch == '\\')) { need (aTHX_ enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = '\\'; } else if (expect_false (ch == '/' && (enc->json.flags & F_ESCAPE_SLASH))) { need (aTHX_ enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = '/'; } else *enc->cur++ = ch; ++str; } else { switch (ch) { case '\010': need (aTHX_ enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'b'; ++str; break; case '\011': need (aTHX_ enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 't'; ++str; break; case '\012': need (aTHX_ enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'n'; ++str; break; case '\014': need (aTHX_ enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'f'; ++str; break; case '\015': need (aTHX_ enc, len += 1); *enc->cur++ = '\\'; *enc->cur++ = 'r'; ++str; break; default: { STRLEN clen; UV uch; if (is_utf8 && !(enc->json.flags & F_BINARY)) { uch = decode_utf8 (aTHX_ (unsigned char *)str, end - str, &clen); if (clen == (STRLEN)-1) croak ("malformed or illegal unicode character in string [%.11s], cannot convert to JSON", str); } else { uch = ch; clen = 1; } if (uch < 0x80/*0x20*/ || uch >= enc->limit) { if (enc->json.flags & F_BINARY) { /* MB cannot arrive here */ need (aTHX_ enc, len += 3); *enc->cur++ = '\\'; *enc->cur++ = 'x'; *enc->cur++ = PL_hexdigit [(uch >> 4) & 15]; *enc->cur++ = PL_hexdigit [ uch & 15]; } else if (uch >= 0x10000UL) { if (uch >= 0x110000UL) croak ("out of range codepoint (0x%lx) encountered, unrepresentable in JSON", (unsigned long)uch); need (aTHX_ enc, len += 11); sprintf (enc->cur, "\\u%04x\\u%04x", (int)((uch - 0x10000) / 0x400 + 0xD800), (int)((uch - 0x10000) % 0x400 + 0xDC00)); enc->cur += 12; } else { need (aTHX_ enc, len += 5); *enc->cur++ = '\\'; *enc->cur++ = 'u'; *enc->cur++ = PL_hexdigit [ uch >> 12 ]; *enc->cur++ = PL_hexdigit [(uch >> 8) & 15]; *enc->cur++ = PL_hexdigit [(uch >> 4) & 15]; *enc->cur++ = PL_hexdigit [ uch & 15]; } str += clen; } else if (enc->json.flags & F_LATIN1) { *enc->cur++ = uch; str += clen; } else if (enc->json.flags & F_BINARY) { *enc->cur++ = uch; str += clen; } else if (is_utf8) { need (aTHX_ enc, len += clen); do { *enc->cur++ = *str++; } while (--clen); } else { need (aTHX_ enc, len += UTF8_MAXBYTES - 1); /* never more than 11 bytes needed */ enc->cur = (char*)encode_utf8 ((U8*)enc->cur, uch); ++str; } } } } --len; } } INLINE void encode_indent (pTHX_ enc_t *enc) { if (enc->json.flags & F_INDENT) { int spaces = enc->indent * INDENT_STEP; need (aTHX_ enc, spaces); memset (enc->cur, ' ', spaces); enc->cur += spaces; } } INLINE void encode_space (pTHX_ enc_t *enc) { need (aTHX_ enc, 1); encode_ch (aTHX_ enc, ' '); } INLINE void encode_nl (pTHX_ enc_t *enc) { if (enc->json.flags & F_INDENT) { need (aTHX_ enc, 1); encode_ch (aTHX_ enc, '\n'); } } INLINE void encode_comma (pTHX_ enc_t *enc) { encode_ch (aTHX_ enc, ','); if (enc->json.flags & F_INDENT) encode_nl (aTHX_ enc); else if (enc->json.flags & F_SPACE_AFTER) encode_space (aTHX_ enc); } static void encode_sv (pTHX_ enc_t *enc, SV *sv); static void encode_av (pTHX_ enc_t *enc, AV *av) { int i, len = av_len (av); if (enc->indent >= enc->json.max_depth) croak (ERR_NESTING_EXCEEDED); encode_ch (aTHX_ enc, '['); if (len >= 0) { encode_nl (aTHX_ enc); ++enc->indent; for (i = 0; i <= len; ++i) { SV **svp = av_fetch (av, i, 0); encode_indent (aTHX_ enc); if (svp) encode_sv (aTHX_ enc, *svp); else encode_str (aTHX_ enc, "null", 4, 0); if (i < len) encode_comma (aTHX_ enc); } encode_nl (aTHX_ enc); --enc->indent; encode_indent (aTHX_ enc); } encode_ch (aTHX_ enc, ']'); } static void encode_hk (pTHX_ enc_t *enc, HE *he) { encode_ch (aTHX_ enc, '"'); if (HeKLEN (he) == HEf_SVKEY) { SV *sv = HeSVKEY (he); STRLEN len; char *str; SvGETMAGIC (sv); str = SvPV (sv, len); encode_str (aTHX_ enc, str, len, SvUTF8 (sv)); } else encode_str (aTHX_ enc, HeKEY (he), HeKLEN (he), HeKUTF8 (he)); encode_ch (aTHX_ enc, '"'); if (enc->json.flags & F_SPACE_BEFORE) encode_space (aTHX_ enc); encode_ch (aTHX_ enc, ':'); if (enc->json.flags & F_SPACE_AFTER ) encode_space (aTHX_ enc); } /* compare hash entries, used when all keys are bytestrings */ static int he_cmp_fast (const void *a_, const void *b_) { int cmp; HE *a = *(HE **)a_; HE *b = *(HE **)b_; STRLEN la = HeKLEN (a); STRLEN lb = HeKLEN (b); if (!(cmp = memcmp (HeKEY (b), HeKEY (a), lb < la ? lb : la))) cmp = lb - la; return cmp; } /* compare hash entries, used when some keys are sv's or utf-x */ static int he_cmp_slow (const void *a, const void *b) { dTHX; return sv_cmp (HeSVKEY_force (*(HE **)b), HeSVKEY_force (*(HE **)a)); } static void encode_hv (pTHX_ enc_t *enc, HV *hv) { HE *he; if (enc->indent >= enc->json.max_depth) croak (ERR_NESTING_EXCEEDED); encode_ch (aTHX_ enc, '{'); /* for canonical output we have to sort by keys first */ /* caused by randomised hash orderings */ if (enc->json.flags & F_CANONICAL && !SvTIED_mg((SV*)hv, PERL_MAGIC_tied)) { int count = hv_iterinit (hv); if (SvMAGICAL (hv)) { /* need to count by iterating. could improve by dynamically building the vector below */ /* but I don't care for the speed of this special case. */ /* note also that we will run into undefined behaviour when the two iterations */ /* do not result in the same count, something I might care for in some later release. */ count = 0; while (hv_iternext (hv)) ++count; hv_iterinit (hv); } if (count) { int i, fast = 1; HE *hes_stack [STACK_HES]; HE **hes = hes_stack; // allocate larger arrays on the heap if (count > STACK_HES) { SV *sv = sv_2mortal (NEWSV (0, count * sizeof (*hes))); hes = (HE **)SvPVX (sv); } i = 0; while ((he = hv_iternext (hv))) { hes [i++] = he; if (HeKLEN (he) < 0 || HeKUTF8 (he)) fast = 0; } assert (i == count); if (fast) qsort (hes, count, sizeof (HE *), he_cmp_fast); else { /* hack to forcefully disable "use bytes" */ COP cop = *PL_curcop; cop.op_private = 0; ENTER; SAVETMPS; SAVEVPTR (PL_curcop); PL_curcop = &cop; qsort (hes, count, sizeof (HE *), he_cmp_slow); FREETMPS; LEAVE; } encode_nl (aTHX_ enc); ++enc->indent; while (count--) { encode_indent (aTHX_ enc); he = hes [count]; encode_hk (aTHX_ enc, he); encode_sv (aTHX_ enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he)); if (count) encode_comma (aTHX_ enc); } encode_nl (aTHX_ enc); --enc->indent; encode_indent (aTHX_ enc); } } else { if (hv_iterinit (hv) || SvMAGICAL (hv)) if ((he = hv_iternext (hv))) { encode_nl (aTHX_ enc); ++enc->indent; for (;;) { encode_indent (aTHX_ enc); encode_hk (aTHX_ enc, he); encode_sv (aTHX_ enc, expect_false (SvMAGICAL (hv)) ? hv_iterval (hv, he) : HeVAL (he)); if (!(he = hv_iternext (hv))) break; encode_comma (aTHX_ enc); } encode_nl (aTHX_ enc); --enc->indent; encode_indent (aTHX_ enc); } } encode_ch (aTHX_ enc, '}'); } /* implement convert_blessed, sv is already unref'ed here */ static void encode_stringify(pTHX_ enc_t *enc, SV *sv, int isref) { char *str = NULL; STRLEN len; SV *pv = NULL; svtype type = SvTYPE(sv); int amg = 0; #if PERL_VERSION <= 8 MAGIC *mg; #endif /* SvAMAGIC without the ref */ #if PERL_VERSION > 17 #define MyAMG(sv) (SvOBJECT(sv) && HvAMAGIC(SvSTASH(sv))) #else #if PERL_VERSION > 8 #define MyAMG(sv) (SvOBJECT(sv) && (SvFLAGS(sv) & SVf_AMAGIC)) #else #define MyAMG(sv) (SvOBJECT(sv) && ((SvFLAGS(sv) & SVf_AMAGIC) \ || ((mg = mg_find((SV*)SvSTASH(sv), PERL_MAGIC_overload_table)) \ && mg->mg_ptr && AMT_AMAGIC((AMT*)mg->mg_ptr)))) #endif #endif if (isref && SvAMAGIC(sv)) ; /* if no string overload found, check allow_stringify */ else if (!MyAMG(sv) && !(enc->json.flags & F_ALLOW_STRINGIFY)) { if (isref && !(enc->json.flags & F_ALLOW_UNKNOWN)) croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1", SvPV_nolen (sv_2mortal (newRV_inc (sv)))); encode_str (aTHX_ enc, "null", 4, 0); return; } /* sv_2pv_flags does not accept those types: */ if (type != SVt_PVAV && type != SVt_PVHV && type != SVt_PVFM) { /* the essential of pp_stringify */ #if PERL_VERSION > 7 pv = newSVpvs(""); sv_copypv(pv, sv); #else STRLEN len; char *s; pv = newSVpvs(""); s = SvPV(sv,len); sv_setpvn(pv,s,len); if (SvUTF8(sv)) SvUTF8_on(pv); else SvUTF8_off(pv); #endif SvSETMAGIC(pv); str = SvPVutf8_force(pv, len); if (!len) { encode_str (aTHX_ enc, "null", 4, 0); SvREFCNT_dec(pv); return; } } else { /* manually call all possible magic on AV, HV, FM */ if (SvGMAGICAL(sv)) mg_get(sv); if (MyAMG(sv)) { /* force a RV here */ SV* rv = newRV(SvREFCNT_inc(sv)); #if PERL_VERSION <= 8 HV *stash = SvSTASH(sv); if (!SvSTASH(rv) || !(SvFLAGS(sv) & SVf_AMAGIC)) { sv_bless(rv, stash); Gv_AMupdate(stash); SvFLAGS(sv) |= SVf_AMAGIC; } #endif #if PERL_VERSION > 13 pv = AMG_CALLunary(rv, string_amg); #else pv = AMG_CALLun(rv, string); #endif TAINT_IF(pv && SvTAINTED(pv)); if (pv && SvPOK(pv)) { str = SvPVutf8_force(pv, len); encode_ch (aTHX_ enc, '"'); encode_str (aTHX_ enc, str, len, 0); encode_ch (aTHX_ enc, '"'); SvREFCNT_dec(rv); return; } SvREFCNT_dec(rv); } } if (!str) encode_str (aTHX_ enc, "null", 4, 0); else { if (isref != 1) encode_ch (aTHX_ enc, '"'); encode_str (aTHX_ enc, str, len, 0); if (isref != 1) encode_ch (aTHX_ enc, '"'); } if (pv) SvREFCNT_dec(pv); #undef MyAMG } /* encode objects, arrays and special \0=false and \1=true values and other representations of booleans: JSON::PP::Boolean, Mojo::JSON::_Bool */ static void encode_rv (pTHX_ enc_t *enc, SV *rv) { svtype svt; GV *method; SV *sv = SvRV(rv); SvGETMAGIC (sv); svt = SvTYPE (sv); if (expect_false (SvOBJECT (sv))) { dMY_CXT; HV *bstash = MY_CXT.json_boolean_stash; /* JSON-XS-3.x interop (Types::Serialiser/JSON::PP::Boolean) */ HV *oldstash = MY_CXT.jsonold_boolean_stash; /* JSON-XS-2.x interop (JSON::XS::Boolean) */ HV *mstash = MY_CXT.mojo_boolean_stash; /* Mojo::JSON::_Bool interop */ HV *stash = SvSTASH (sv); if (stash == bstash || stash == mstash || stash == oldstash) { if (SvIV (sv)) encode_str (aTHX_ enc, "true", 4, 0); else encode_str (aTHX_ enc, "false", 5, 0); } else if ((enc->json.flags & F_ALLOW_TAGS) && (method = gv_fetchmethod_autoload (stash, "FREEZE", 0))) { dMY_CXT; dSP; int count, items; ENTER; SAVETMPS; PUSHMARK (SP); EXTEND (SP, 2); PUSHs (rv); PUSHs (MY_CXT.sv_json); PUTBACK; count = call_sv ((SV *)GvCV (method), G_ARRAY); items = count; SPAGAIN; /* catch this surprisingly common error */ if (SvROK (TOPs) && SvRV (TOPs) == sv) croak ("%s::FREEZE method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv))); encode_ch (aTHX_ enc, '('); encode_ch (aTHX_ enc, '"'); encode_str (aTHX_ enc, HvNAME (stash), HvNAMELEN (stash), HvNAMEUTF8 (stash)); encode_ch (aTHX_ enc, '"'); encode_ch (aTHX_ enc, ')'); encode_ch (aTHX_ enc, '['); while (count) { encode_sv (aTHX_ enc, SP[1 - count--]); SPAGAIN; if (count) encode_ch (aTHX_ enc, ','); } encode_ch (aTHX_ enc, ']'); SP -= items; PUTBACK; FREETMPS; LEAVE; } else if ((enc->json.flags & F_CONV_BLESSED) && (method = gv_fetchmethod_autoload (stash, "TO_JSON", 0))) { dSP; ENTER; SAVETMPS; PUSHMARK (SP); XPUSHs (rv); /* calling with G_SCALAR ensures that we always get a 1 return value */ PUTBACK; call_sv ((SV *)GvCV (method), G_SCALAR); SPAGAIN; /* catch this surprisingly common error */ if (SvROK (TOPs) && SvRV (TOPs) == sv) croak ("%s::TO_JSON method returned same object as was passed instead of a new one", HvNAME (SvSTASH (sv))); sv = POPs; PUTBACK; encode_sv (aTHX_ enc, sv); FREETMPS; LEAVE; } else if ((enc->json.flags & F_ALLOW_BIGNUM) && stash && ((stash == gv_stashpvn ("Math::BigInt", sizeof("Math::BigInt")-1, 0)) || (stash == gv_stashpvn ("Math::BigFloat", sizeof("Math::BigFloat")-1, 0)))) encode_stringify(aTHX_ enc, rv, 1); else if (enc->json.flags & F_CONV_BLESSED) encode_stringify(aTHX_ enc, sv, 0); else if (enc->json.flags & F_ALLOW_BLESSED) encode_str (aTHX_ enc, "null", 4, 0); else croak ("encountered object '%s', but neither allow_blessed, convert_blessed nor allow_tags settings are enabled (or TO_JSON/FREEZE method missing)", SvPV_nolen (sv_2mortal (newRV_inc (sv)))); } else if (svt == SVt_PVHV) encode_hv (aTHX_ enc, (HV *)sv); else if (svt == SVt_PVAV) encode_av (aTHX_ enc, (AV *)sv); else if (svt < SVt_PVAV && svt != SVt_PVGV) { STRLEN len = 0; char *pv = svt ? SvPV (sv, len) : 0; if (len == 1 && *pv == '1') encode_str (aTHX_ enc, "true", 4, 0); else if (len == 1 && *pv == '0') encode_str (aTHX_ enc, "false", 5, 0); else if (enc->json.flags & F_ALLOW_STRINGIFY) encode_stringify(aTHX_ enc, sv, SvROK(sv)); else if (enc->json.flags & F_ALLOW_UNKNOWN) encode_str (aTHX_ enc, "null", 4, 0); else croak ("cannot encode reference to scalar '%s' unless the scalar is 0 or 1", SvPV_nolen (sv_2mortal (newRV_inc (sv)))); } else if (enc->json.flags & F_ALLOW_UNKNOWN) encode_str (aTHX_ enc, "null", 4, 0); else croak ("encountered %s, but JSON can only represent references to arrays or hashes", SvPV_nolen (sv_2mortal (newRV_inc (sv)))); } static void encode_sv (pTHX_ enc_t *enc, SV *sv) { SvGETMAGIC (sv); if (expect_false(sv == &PL_sv_yes )) { encode_str (aTHX_ enc, "true", 4, 0); } else if (expect_false(sv == &PL_sv_no )) { encode_str (aTHX_ enc, "false", 5, 0); } else if (SvNOKp (sv)) { char *savecur, *saveend; /* trust that perl will do the right thing w.r.t. JSON syntax. */ need (aTHX_ enc, NV_DIG + 32); savecur = enc->cur; saveend = enc->end; (void)Gconvert (SvNVX (sv), NV_DIG, 0, enc->cur); if (strEQ(enc->cur, STR_INF) || strEQ(enc->cur, STR_NAN) #if defined(_WIN32) || strEQ(enc->cur, STR_QNAN) #endif || (*enc->cur == '-' && (strEQ(enc->cur+1, STR_INF) || strEQ(enc->cur+1, STR_NAN) #if defined(_WIN32) || strEQ(enc->cur+1, STR_QNAN) #endif ))) { if (enc->json.infnan_mode == 0) { strncpy(enc->cur, "null\0", 5); } else if (enc->json.infnan_mode == 1) { const int l = strlen(enc->cur); memmove(enc->cur+1, enc->cur, l); *enc->cur = '"'; *(enc->cur + l+1) = '"'; *(enc->cur + l+2) = 0; } else if (enc->json.infnan_mode != 2) { croak ("invalid stringify_infnan mode %c. Must be 0, 1 or 2", enc->json.infnan_mode); } } if (SvPOKp (sv) && !strEQ(enc->cur, SvPVX (sv))) { STRLEN len; char *str = SvPV (sv, len); enc->cur = savecur; enc->end = saveend; encode_ch (aTHX_ enc, '"'); encode_str (aTHX_ enc, str, len, SvUTF8 (sv)); encode_ch (aTHX_ enc, '"'); *enc->cur = 0; } else { enc->cur += strlen (enc->cur); } } else if (SvIOKp (sv)) { char *savecur, *saveend; /* we assume we can always read an IV as a UV and vice versa */ /* we assume two's complement */ /* we assume no aliasing issues in the union */ if (SvIsUV (sv) ? SvUVX (sv) <= 59000 : SvIVX (sv) <= 59000 && SvIVX (sv) >= -59000) { /* optimise the "small number case" */ /* code will likely be branchless and use only a single multiplication */ /* works for numbers up to 59074 */ I32 i = SvIVX (sv); U32 u; char digit, nz = 0; need (aTHX_ enc, 6); savecur = enc->cur; saveend = enc->end; *enc->cur = '-'; enc->cur += i < 0 ? 1 : 0; u = i < 0 ? -i : i; /* convert to 4.28 fixed-point representation */ u = u * ((0xfffffff + 10000) / 10000); /* 10**5, 5 fractional digits */ /* now output digit by digit, each time masking out the integer part */ /* and multiplying by 5 while moving the decimal point one to the right, */ /* resulting in a net multiplication by 10. */ /* we always write the digit to memory but conditionally increment */ /* the pointer, to enable the use of conditional move instructions. */ digit = u >> 28; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0xfffffffUL) * 5; digit = u >> 27; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x7ffffffUL) * 5; digit = u >> 26; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x3ffffffUL) * 5; digit = u >> 25; *enc->cur = digit + '0'; enc->cur += (nz = nz || digit); u = (u & 0x1ffffffUL) * 5; digit = u >> 24; *enc->cur = digit + '0'; enc->cur += 1; /* correctly generate '0' */ *enc->cur = 0; } else { /* large integer, use the (rather slow) snprintf way. */ need (aTHX_ enc, IVUV_MAXCHARS); savecur = enc->cur; saveend = enc->end; enc->cur += SvIsUV(sv) ? snprintf (enc->cur, IVUV_MAXCHARS, "%"UVuf, (UV)SvUVX (sv)) : snprintf (enc->cur, IVUV_MAXCHARS, "%"IVdf, (IV)SvIVX (sv)); } if (SvPOKp (sv) && !strEQ(savecur, SvPVX (sv))) { STRLEN len; char *str = SvPV (sv, len); enc->cur = savecur; enc->end = saveend; encode_ch (aTHX_ enc, '"'); encode_str (aTHX_ enc, str, len, SvUTF8 (sv)); encode_ch (aTHX_ enc, '"'); *enc->cur = 0; } } else if (SvPOKp (sv)) { STRLEN len; char *str = SvPV (sv, len); encode_ch (aTHX_ enc, '"'); encode_str (aTHX_ enc, str, len, SvUTF8 (sv)); encode_ch (aTHX_ enc, '"'); } else if (SvROK (sv)) encode_rv (aTHX_ enc, sv); else if (!SvOK (sv) || enc->json.flags & F_ALLOW_UNKNOWN) encode_str (aTHX_ enc, "null", 4, 0); else croak ("encountered perl type (%s,0x%x) that JSON cannot handle, check your input data", SvPV_nolen (sv), (unsigned int)SvFLAGS (sv)); } static SV * encode_json (pTHX_ SV *scalar, JSON *json) { enc_t enc; if (!(json->flags & F_ALLOW_NONREF) && !SvROK (scalar)) croak ("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)"); enc.json = *json; enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE)); enc.cur = SvPVX (enc.sv); enc.end = SvEND (enc.sv); enc.indent = 0; enc.limit = enc.json.flags & F_ASCII ? 0x000080UL : enc.json.flags & F_BINARY ? 0x000080UL : enc.json.flags & F_LATIN1 ? 0x000100UL : 0x110000UL; SvPOK_only (enc.sv); encode_sv (aTHX_ &enc, scalar); encode_nl (aTHX_ &enc); SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv)); *SvEND (enc.sv) = 0; /* many xs functions expect a trailing 0 for text strings */ if (!(enc.json.flags & (F_ASCII | F_LATIN1 | F_BINARY | F_UTF8))) SvUTF8_on (enc.sv); if (enc.json.flags & F_SHRINK) shrink (aTHX_ enc.sv); return enc.sv; } /*/////////////////////////////////////////////////////////////////////////// */ /* decoder */ /* structure used for decoding JSON */ typedef struct { char *cur; /* current parser pointer */ char *end; /* end of input string */ const char *err; /* parse error, if != 0 */ JSON json; U32 depth; /* recursion depth */ U32 maxdepth; /* recursion depth limit */ } dec_t; INLINE void decode_comment (dec_t *dec) { /* only '#'-style comments allowed a.t.m. */ while (*dec->cur && *dec->cur != 0x0a && *dec->cur != 0x0d) ++dec->cur; } INLINE void decode_ws (dec_t *dec) { for (;;) { char ch = *dec->cur; if (ch > 0x20) { if (expect_false (ch == '#')) { if (dec->json.flags & F_RELAXED) decode_comment (dec); else break; } else break; } else if (ch != 0x20 && ch != 0x0a && ch != 0x0d && ch != 0x09) break; /* parse error, but let higher level handle it, gives better error messages */ ++dec->cur; } } #define ERR(reason) SB dec->err = reason; goto fail; SE #define EXPECT_CH(ch) SB \ if (*dec->cur != ch) \ ERR (# ch " expected"); \ ++dec->cur; \ SE #define DEC_INC_DEPTH if (++dec->depth > dec->json.max_depth) ERR (ERR_NESTING_EXCEEDED) #define DEC_DEC_DEPTH --dec->depth static SV *decode_sv (pTHX_ dec_t *dec); /* #regen code my $i; for ($i = 0; $i < 256; ++$i){ print " $i >= '0' && $i <= '9' ? $i - '0' : $i >= 'a' && $i <= 'f' ? $i - 'a' + 10 : $i >= 'A' && $i <= 'F' ? $i - 'A' + 10 : -1 , "; } */ const static signed char decode_hexdigit[256] = { 0 >= '0' && 0 <= '9' ? 0 - '0' : 0 >= 'a' && 0 <= 'f' ? 0 - 'a' + 10 : 0 >= 'A' && 0 <= 'F' ? 0 - 'A' + 10 : -1 , 1 >= '0' && 1 <= '9' ? 1 - '0' : 1 >= 'a' && 1 <= 'f' ? 1 - 'a' + 10 : 1 >= 'A' && 1 <= 'F' ? 1 - 'A' + 10 : -1 , 2 >= '0' && 2 <= '9' ? 2 - '0' : 2 >= 'a' && 2 <= 'f' ? 2 - 'a' + 10 : 2 >= 'A' && 2 <= 'F' ? 2 - 'A' + 10 : -1 , 3 >= '0' && 3 <= '9' ? 3 - '0' : 3 >= 'a' && 3 <= 'f' ? 3 - 'a' + 10 : 3 >= 'A' && 3 <= 'F' ? 3 - 'A' + 10 : -1 , 4 >= '0' && 4 <= '9' ? 4 - '0' : 4 >= 'a' && 4 <= 'f' ? 4 - 'a' + 10 : 4 >= 'A' && 4 <= 'F' ? 4 - 'A' + 10 : -1 , 5 >= '0' && 5 <= '9' ? 5 - '0' : 5 >= 'a' && 5 <= 'f' ? 5 - 'a' + 10 : 5 >= 'A' && 5 <= 'F' ? 5 - 'A' + 10 : -1 , 6 >= '0' && 6 <= '9' ? 6 - '0' : 6 >= 'a' && 6 <= 'f' ? 6 - 'a' + 10 : 6 >= 'A' && 6 <= 'F' ? 6 - 'A' + 10 : -1 , 7 >= '0' && 7 <= '9' ? 7 - '0' : 7 >= 'a' && 7 <= 'f' ? 7 - 'a' + 10 : 7 >= 'A' && 7 <= 'F' ? 7 - 'A' + 10 : -1 , 8 >= '0' && 8 <= '9' ? 8 - '0' : 8 >= 'a' && 8 <= 'f' ? 8 - 'a' + 10 : 8 >= 'A' && 8 <= 'F' ? 8 - 'A' + 10 : -1 , 9 >= '0' && 9 <= '9' ? 9 - '0' : 9 >= 'a' && 9 <= 'f' ? 9 - 'a' + 10 : 9 >= 'A' && 9 <= 'F' ? 9 - 'A' + 10 : -1 , 10 >= '0' && 10 <= '9' ? 10 - '0' : 10 >= 'a' && 10 <= 'f' ? 10 - 'a' + 10 : 10 >= 'A' && 10 <= 'F' ? 10 - 'A' + 10 : -1 , 11 >= '0' && 11 <= '9' ? 11 - '0' : 11 >= 'a' && 11 <= 'f' ? 11 - 'a' + 10 : 11 >= 'A' && 11 <= 'F' ? 11 - 'A' + 10 : -1 , 12 >= '0' && 12 <= '9' ? 12 - '0' : 12 >= 'a' && 12 <= 'f' ? 12 - 'a' + 10 : 12 >= 'A' && 12 <= 'F' ? 12 - 'A' + 10 : -1 , 13 >= '0' && 13 <= '9' ? 13 - '0' : 13 >= 'a' && 13 <= 'f' ? 13 - 'a' + 10 : 13 >= 'A' && 13 <= 'F' ? 13 - 'A' + 10 : -1 , 14 >= '0' && 14 <= '9' ? 14 - '0' : 14 >= 'a' && 14 <= 'f' ? 14 - 'a' + 10 : 14 >= 'A' && 14 <= 'F' ? 14 - 'A' + 10 : -1 , 15 >= '0' && 15 <= '9' ? 15 - '0' : 15 >= 'a' && 15 <= 'f' ? 15 - 'a' + 10 : 15 >= 'A' && 15 <= 'F' ? 15 - 'A' + 10 : -1 , 16 >= '0' && 16 <= '9' ? 16 - '0' : 16 >= 'a' && 16 <= 'f' ? 16 - 'a' + 10 : 16 >= 'A' && 16 <= 'F' ? 16 - 'A' + 10 : -1 , 17 >= '0' && 17 <= '9' ? 17 - '0' : 17 >= 'a' && 17 <= 'f' ? 17 - 'a' + 10 : 17 >= 'A' && 17 <= 'F' ? 17 - 'A' + 10 : -1 , 18 >= '0' && 18 <= '9' ? 18 - '0' : 18 >= 'a' && 18 <= 'f' ? 18 - 'a' + 10 : 18 >= 'A' && 18 <= 'F' ? 18 - 'A' + 10 : -1 , 19 >= '0' && 19 <= '9' ? 19 - '0' : 19 >= 'a' && 19 <= 'f' ? 19 - 'a' + 10 : 19 >= 'A' && 19 <= 'F' ? 19 - 'A' + 10 : -1 , 20 >= '0' && 20 <= '9' ? 20 - '0' : 20 >= 'a' && 20 <= 'f' ? 20 - 'a' + 10 : 20 >= 'A' && 20 <= 'F' ? 20 - 'A' + 10 : -1 , 21 >= '0' && 21 <= '9' ? 21 - '0' : 21 >= 'a' && 21 <= 'f' ? 21 - 'a' + 10 : 21 >= 'A' && 21 <= 'F' ? 21 - 'A' + 10 : -1 , 22 >= '0' && 22 <= '9' ? 22 - '0' : 22 >= 'a' && 22 <= 'f' ? 22 - 'a' + 10 : 22 >= 'A' && 22 <= 'F' ? 22 - 'A' + 10 : -1 , 23 >= '0' && 23 <= '9' ? 23 - '0' : 23 >= 'a' && 23 <= 'f' ? 23 - 'a' + 10 : 23 >= 'A' && 23 <= 'F' ? 23 - 'A' + 10 : -1 , 24 >= '0' && 24 <= '9' ? 24 - '0' : 24 >= 'a' && 24 <= 'f' ? 24 - 'a' + 10 : 24 >= 'A' && 24 <= 'F' ? 24 - 'A' + 10 : -1 , 25 >= '0' && 25 <= '9' ? 25 - '0' : 25 >= 'a' && 25 <= 'f' ? 25 - 'a' + 10 : 25 >= 'A' && 25 <= 'F' ? 25 - 'A' + 10 : -1 , 26 >= '0' && 26 <= '9' ? 26 - '0' : 26 >= 'a' && 26 <= 'f' ? 26 - 'a' + 10 : 26 >= 'A' && 26 <= 'F' ? 26 - 'A' + 10 : -1 , 27 >= '0' && 27 <= '9' ? 27 - '0' : 27 >= 'a' && 27 <= 'f' ? 27 - 'a' + 10 : 27 >= 'A' && 27 <= 'F' ? 27 - 'A' + 10 : -1 , 28 >= '0' && 28 <= '9' ? 28 - '0' : 28 >= 'a' && 28 <= 'f' ? 28 - 'a' + 10 : 28 >= 'A' && 28 <= 'F' ? 28 - 'A' + 10 : -1 , 29 >= '0' && 29 <= '9' ? 29 - '0' : 29 >= 'a' && 29 <= 'f' ? 29 - 'a' + 10 : 29 >= 'A' && 29 <= 'F' ? 29 - 'A' + 10 : -1 , 30 >= '0' && 30 <= '9' ? 30 - '0' : 30 >= 'a' && 30 <= 'f' ? 30 - 'a' + 10 : 30 >= 'A' && 30 <= 'F' ? 30 - 'A' + 10 : -1 , 31 >= '0' && 31 <= '9' ? 31 - '0' : 31 >= 'a' && 31 <= 'f' ? 31 - 'a' + 10 : 31 >= 'A' && 31 <= 'F' ? 31 - 'A' + 10 : -1 , 32 >= '0' && 32 <= '9' ? 32 - '0' : 32 >= 'a' && 32 <= 'f' ? 32 - 'a' + 10 : 32 >= 'A' && 32 <= 'F' ? 32 - 'A' + 10 : -1 , 33 >= '0' && 33 <= '9' ? 33 - '0' : 33 >= 'a' && 33 <= 'f' ? 33 - 'a' + 10 : 33 >= 'A' && 33 <= 'F' ? 33 - 'A' + 10 : -1 , 34 >= '0' && 34 <= '9' ? 34 - '0' : 34 >= 'a' && 34 <= 'f' ? 34 - 'a' + 10 : 34 >= 'A' && 34 <= 'F' ? 34 - 'A' + 10 : -1 , 35 >= '0' && 35 <= '9' ? 35 - '0' : 35 >= 'a' && 35 <= 'f' ? 35 - 'a' + 10 : 35 >= 'A' && 35 <= 'F' ? 35 - 'A' + 10 : -1 , 36 >= '0' && 36 <= '9' ? 36 - '0' : 36 >= 'a' && 36 <= 'f' ? 36 - 'a' + 10 : 36 >= 'A' && 36 <= 'F' ? 36 - 'A' + 10 : -1 , 37 >= '0' && 37 <= '9' ? 37 - '0' : 37 >= 'a' && 37 <= 'f' ? 37 - 'a' + 10 : 37 >= 'A' && 37 <= 'F' ? 37 - 'A' + 10 : -1 , 38 >= '0' && 38 <= '9' ? 38 - '0' : 38 >= 'a' && 38 <= 'f' ? 38 - 'a' + 10 : 38 >= 'A' && 38 <= 'F' ? 38 - 'A' + 10 : -1 , 39 >= '0' && 39 <= '9' ? 39 - '0' : 39 >= 'a' && 39 <= 'f' ? 39 - 'a' + 10 : 39 >= 'A' && 39 <= 'F' ? 39 - 'A' + 10 : -1 , 40 >= '0' && 40 <= '9' ? 40 - '0' : 40 >= 'a' && 40 <= 'f' ? 40 - 'a' + 10 : 40 >= 'A' && 40 <= 'F' ? 40 - 'A' + 10 : -1 , 41 >= '0' && 41 <= '9' ? 41 - '0' : 41 >= 'a' && 41 <= 'f' ? 41 - 'a' + 10 : 41 >= 'A' && 41 <= 'F' ? 41 - 'A' + 10 : -1 , 42 >= '0' && 42 <= '9' ? 42 - '0' : 42 >= 'a' && 42 <= 'f' ? 42 - 'a' + 10 : 42 >= 'A' && 42 <= 'F' ? 42 - 'A' + 10 : -1 , 43 >= '0' && 43 <= '9' ? 43 - '0' : 43 >= 'a' && 43 <= 'f' ? 43 - 'a' + 10 : 43 >= 'A' && 43 <= 'F' ? 43 - 'A' + 10 : -1 , 44 >= '0' && 44 <= '9' ? 44 - '0' : 44 >= 'a' && 44 <= 'f' ? 44 - 'a' + 10 : 44 >= 'A' && 44 <= 'F' ? 44 - 'A' + 10 : -1 , 45 >= '0' && 45 <= '9' ? 45 - '0' : 45 >= 'a' && 45 <= 'f' ? 45 - 'a' + 10 : 45 >= 'A' && 45 <= 'F' ? 45 - 'A' + 10 : -1 , 46 >= '0' && 46 <= '9' ? 46 - '0' : 46 >= 'a' && 46 <= 'f' ? 46 - 'a' + 10 : 46 >= 'A' && 46 <= 'F' ? 46 - 'A' + 10 : -1 , 47 >= '0' && 47 <= '9' ? 47 - '0' : 47 >= 'a' && 47 <= 'f' ? 47 - 'a' + 10 : 47 >= 'A' && 47 <= 'F' ? 47 - 'A' + 10 : -1 , 48 >= '0' && 48 <= '9' ? 48 - '0' : 48 >= 'a' && 48 <= 'f' ? 48 - 'a' + 10 : 48 >= 'A' && 48 <= 'F' ? 48 - 'A' + 10 : -1 , 49 >= '0' && 49 <= '9' ? 49 - '0' : 49 >= 'a' && 49 <= 'f' ? 49 - 'a' + 10 : 49 >= 'A' && 49 <= 'F' ? 49 - 'A' + 10 : -1 , 50 >= '0' && 50 <= '9' ? 50 - '0' : 50 >= 'a' && 50 <= 'f' ? 50 - 'a' + 10 : 50 >= 'A' && 50 <= 'F' ? 50 - 'A' + 10 : -1 , 51 >= '0' && 51 <= '9' ? 51 - '0' : 51 >= 'a' && 51 <= 'f' ? 51 - 'a' + 10 : 51 >= 'A' && 51 <= 'F' ? 51 - 'A' + 10 : -1 , 52 >= '0' && 52 <= '9' ? 52 - '0' : 52 >= 'a' && 52 <= 'f' ? 52 - 'a' + 10 : 52 >= 'A' && 52 <= 'F' ? 52 - 'A' + 10 : -1 , 53 >= '0' && 53 <= '9' ? 53 - '0' : 53 >= 'a' && 53 <= 'f' ? 53 - 'a' + 10 : 53 >= 'A' && 53 <= 'F' ? 53 - 'A' + 10 : -1 , 54 >= '0' && 54 <= '9' ? 54 - '0' : 54 >= 'a' && 54 <= 'f' ? 54 - 'a' + 10 : 54 >= 'A' && 54 <= 'F' ? 54 - 'A' + 10 : -1 , 55 >= '0' && 55 <= '9' ? 55 - '0' : 55 >= 'a' && 55 <= 'f' ? 55 - 'a' + 10 : 55 >= 'A' && 55 <= 'F' ? 55 - 'A' + 10 : -1 , 56 >= '0' && 56 <= '9' ? 56 - '0' : 56 >= 'a' && 56 <= 'f' ? 56 - 'a' + 10 : 56 >= 'A' && 56 <= 'F' ? 56 - 'A' + 10 : -1 , 57 >= '0' && 57 <= '9' ? 57 - '0' : 57 >= 'a' && 57 <= 'f' ? 57 - 'a' + 10 : 57 >= 'A' && 57 <= 'F' ? 57 - 'A' + 10 : -1 , 58 >= '0' && 58 <= '9' ? 58 - '0' : 58 >= 'a' && 58 <= 'f' ? 58 - 'a' + 10 : 58 >= 'A' && 58 <= 'F' ? 58 - 'A' + 10 : -1 , 59 >= '0' && 59 <= '9' ? 59 - '0' : 59 >= 'a' && 59 <= 'f' ? 59 - 'a' + 10 : 59 >= 'A' && 59 <= 'F' ? 59 - 'A' + 10 : -1 , 60 >= '0' && 60 <= '9' ? 60 - '0' : 60 >= 'a' && 60 <= 'f' ? 60 - 'a' + 10 : 60 >= 'A' && 60 <= 'F' ? 60 - 'A' + 10 : -1 , 61 >= '0' && 61 <= '9' ? 61 - '0' : 61 >= 'a' && 61 <= 'f' ? 61 - 'a' + 10 : 61 >= 'A' && 61 <= 'F' ? 61 - 'A' + 10 : -1 , 62 >= '0' && 62 <= '9' ? 62 - '0' : 62 >= 'a' && 62 <= 'f' ? 62 - 'a' + 10 : 62 >= 'A' && 62 <= 'F' ? 62 - 'A' + 10 : -1 , 63 >= '0' && 63 <= '9' ? 63 - '0' : 63 >= 'a' && 63 <= 'f' ? 63 - 'a' + 10 : 63 >= 'A' && 63 <= 'F' ? 63 - 'A' + 10 : -1 , 64 >= '0' && 64 <= '9' ? 64 - '0' : 64 >= 'a' && 64 <= 'f' ? 64 - 'a' + 10 : 64 >= 'A' && 64 <= 'F' ? 64 - 'A' + 10 : -1 , 65 >= '0' && 65 <= '9' ? 65 - '0' : 65 >= 'a' && 65 <= 'f' ? 65 - 'a' + 10 : 65 >= 'A' && 65 <= 'F' ? 65 - 'A' + 10 : -1 , 66 >= '0' && 66 <= '9' ? 66 - '0' : 66 >= 'a' && 66 <= 'f' ? 66 - 'a' + 10 : 66 >= 'A' && 66 <= 'F' ? 66 - 'A' + 10 : -1 , 67 >= '0' && 67 <= '9' ? 67 - '0' : 67 >= 'a' && 67 <= 'f' ? 67 - 'a' + 10 : 67 >= 'A' && 67 <= 'F' ? 67 - 'A' + 10 : -1 , 68 >= '0' && 68 <= '9' ? 68 - '0' : 68 >= 'a' && 68 <= 'f' ? 68 - 'a' + 10 : 68 >= 'A' && 68 <= 'F' ? 68 - 'A' + 10 : -1 , 69 >= '0' && 69 <= '9' ? 69 - '0' : 69 >= 'a' && 69 <= 'f' ? 69 - 'a' + 10 : 69 >= 'A' && 69 <= 'F' ? 69 - 'A' + 10 : -1 , 70 >= '0' && 70 <= '9' ? 70 - '0' : 70 >= 'a' && 70 <= 'f' ? 70 - 'a' + 10 : 70 >= 'A' && 70 <= 'F' ? 70 - 'A' + 10 : -1 , 71 >= '0' && 71 <= '9' ? 71 - '0' : 71 >= 'a' && 71 <= 'f' ? 71 - 'a' + 10 : 71 >= 'A' && 71 <= 'F' ? 71 - 'A' + 10 : -1 , 72 >= '0' && 72 <= '9' ? 72 - '0' : 72 >= 'a' && 72 <= 'f' ? 72 - 'a' + 10 : 72 >= 'A' && 72 <= 'F' ? 72 - 'A' + 10 : -1 , 73 >= '0' && 73 <= '9' ? 73 - '0' : 73 >= 'a' && 73 <= 'f' ? 73 - 'a' + 10 : 73 >= 'A' && 73 <= 'F' ? 73 - 'A' + 10 : -1 , 74 >= '0' && 74 <= '9' ? 74 - '0' : 74 >= 'a' && 74 <= 'f' ? 74 - 'a' + 10 : 74 >= 'A' && 74 <= 'F' ? 74 - 'A' + 10 : -1 , 75 >= '0' && 75 <= '9' ? 75 - '0' : 75 >= 'a' && 75 <= 'f' ? 75 - 'a' + 10 : 75 >= 'A' && 75 <= 'F' ? 75 - 'A' + 10 : -1 , 76 >= '0' && 76 <= '9' ? 76 - '0' : 76 >= 'a' && 76 <= 'f' ? 76 - 'a' + 10 : 76 >= 'A' && 76 <= 'F' ? 76 - 'A' + 10 : -1 , 77 >= '0' && 77 <= '9' ? 77 - '0' : 77 >= 'a' && 77 <= 'f' ? 77 - 'a' + 10 : 77 >= 'A' && 77 <= 'F' ? 77 - 'A' + 10 : -1 , 78 >= '0' && 78 <= '9' ? 78 - '0' : 78 >= 'a' && 78 <= 'f' ? 78 - 'a' + 10 : 78 >= 'A' && 78 <= 'F' ? 78 - 'A' + 10 : -1 , 79 >= '0' && 79 <= '9' ? 79 - '0' : 79 >= 'a' && 79 <= 'f' ? 79 - 'a' + 10 : 79 >= 'A' && 79 <= 'F' ? 79 - 'A' + 10 : -1 , 80 >= '0' && 80 <= '9' ? 80 - '0' : 80 >= 'a' && 80 <= 'f' ? 80 - 'a' + 10 : 80 >= 'A' && 80 <= 'F' ? 80 - 'A' + 10 : -1 , 81 >= '0' && 81 <= '9' ? 81 - '0' : 81 >= 'a' && 81 <= 'f' ? 81 - 'a' + 10 : 81 >= 'A' && 81 <= 'F' ? 81 - 'A' + 10 : -1 , 82 >= '0' && 82 <= '9' ? 82 - '0' : 82 >= 'a' && 82 <= 'f' ? 82 - 'a' + 10 : 82 >= 'A' && 82 <= 'F' ? 82 - 'A' + 10 : -1 , 83 >= '0' && 83 <= '9' ? 83 - '0' : 83 >= 'a' && 83 <= 'f' ? 83 - 'a' + 10 : 83 >= 'A' && 83 <= 'F' ? 83 - 'A' + 10 : -1 , 84 >= '0' && 84 <= '9' ? 84 - '0' : 84 >= 'a' && 84 <= 'f' ? 84 - 'a' + 10 : 84 >= 'A' && 84 <= 'F' ? 84 - 'A' + 10 : -1 , 85 >= '0' && 85 <= '9' ? 85 - '0' : 85 >= 'a' && 85 <= 'f' ? 85 - 'a' + 10 : 85 >= 'A' && 85 <= 'F' ? 85 - 'A' + 10 : -1 , 86 >= '0' && 86 <= '9' ? 86 - '0' : 86 >= 'a' && 86 <= 'f' ? 86 - 'a' + 10 : 86 >= 'A' && 86 <= 'F' ? 86 - 'A' + 10 : -1 , 87 >= '0' && 87 <= '9' ? 87 - '0' : 87 >= 'a' && 87 <= 'f' ? 87 - 'a' + 10 : 87 >= 'A' && 87 <= 'F' ? 87 - 'A' + 10 : -1 , 88 >= '0' && 88 <= '9' ? 88 - '0' : 88 >= 'a' && 88 <= 'f' ? 88 - 'a' + 10 : 88 >= 'A' && 88 <= 'F' ? 88 - 'A' + 10 : -1 , 89 >= '0' && 89 <= '9' ? 89 - '0' : 89 >= 'a' && 89 <= 'f' ? 89 - 'a' + 10 : 89 >= 'A' && 89 <= 'F' ? 89 - 'A' + 10 : -1 , 90 >= '0' && 90 <= '9' ? 90 - '0' : 90 >= 'a' && 90 <= 'f' ? 90 - 'a' + 10 : 90 >= 'A' && 90 <= 'F' ? 90 - 'A' + 10 : -1 , 91 >= '0' && 91 <= '9' ? 91 - '0' : 91 >= 'a' && 91 <= 'f' ? 91 - 'a' + 10 : 91 >= 'A' && 91 <= 'F' ? 91 - 'A' + 10 : -1 , 92 >= '0' && 92 <= '9' ? 92 - '0' : 92 >= 'a' && 92 <= 'f' ? 92 - 'a' + 10 : 92 >= 'A' && 92 <= 'F' ? 92 - 'A' + 10 : -1 , 93 >= '0' && 93 <= '9' ? 93 - '0' : 93 >= 'a' && 93 <= 'f' ? 93 - 'a' + 10 : 93 >= 'A' && 93 <= 'F' ? 93 - 'A' + 10 : -1 , 94 >= '0' && 94 <= '9' ? 94 - '0' : 94 >= 'a' && 94 <= 'f' ? 94 - 'a' + 10 : 94 >= 'A' && 94 <= 'F' ? 94 - 'A' + 10 : -1 , 95 >= '0' && 95 <= '9' ? 95 - '0' : 95 >= 'a' && 95 <= 'f' ? 95 - 'a' + 10 : 95 >= 'A' && 95 <= 'F' ? 95 - 'A' + 10 : -1 , 96 >= '0' && 96 <= '9' ? 96 - '0' : 96 >= 'a' && 96 <= 'f' ? 96 - 'a' + 10 : 96 >= 'A' && 96 <= 'F' ? 96 - 'A' + 10 : -1 , 97 >= '0' && 97 <= '9' ? 97 - '0' : 97 >= 'a' && 97 <= 'f' ? 97 - 'a' + 10 : 97 >= 'A' && 97 <= 'F' ? 97 - 'A' + 10 : -1 , 98 >= '0' && 98 <= '9' ? 98 - '0' : 98 >= 'a' && 98 <= 'f' ? 98 - 'a' + 10 : 98 >= 'A' && 98 <= 'F' ? 98 - 'A' + 10 : -1 , 99 >= '0' && 99 <= '9' ? 99 - '0' : 99 >= 'a' && 99 <= 'f' ? 99 - 'a' + 10 : 99 >= 'A' && 99 <= 'F' ? 99 - 'A' + 10 : -1 , 100 >= '0' && 100 <= '9' ? 100 - '0' : 100 >= 'a' && 100 <= 'f' ? 100 - 'a' + 10 : 100 >= 'A' && 100 <= 'F' ? 100 - 'A' + 10 : -1 , 101 >= '0' && 101 <= '9' ? 101 - '0' : 101 >= 'a' && 101 <= 'f' ? 101 - 'a' + 10 : 101 >= 'A' && 101 <= 'F' ? 101 - 'A' + 10 : -1 , 102 >= '0' && 102 <= '9' ? 102 - '0' : 102 >= 'a' && 102 <= 'f' ? 102 - 'a' + 10 : 102 >= 'A' && 102 <= 'F' ? 102 - 'A' + 10 : -1 , 103 >= '0' && 103 <= '9' ? 103 - '0' : 103 >= 'a' && 103 <= 'f' ? 103 - 'a' + 10 : 103 >= 'A' && 103 <= 'F' ? 103 - 'A' + 10 : -1 , 104 >= '0' && 104 <= '9' ? 104 - '0' : 104 >= 'a' && 104 <= 'f' ? 104 - 'a' + 10 : 104 >= 'A' && 104 <= 'F' ? 104 - 'A' + 10 : -1 , 105 >= '0' && 105 <= '9' ? 105 - '0' : 105 >= 'a' && 105 <= 'f' ? 105 - 'a' + 10 : 105 >= 'A' && 105 <= 'F' ? 105 - 'A' + 10 : -1 , 106 >= '0' && 106 <= '9' ? 106 - '0' : 106 >= 'a' && 106 <= 'f' ? 106 - 'a' + 10 : 106 >= 'A' && 106 <= 'F' ? 106 - 'A' + 10 : -1 , 107 >= '0' && 107 <= '9' ? 107 - '0' : 107 >= 'a' && 107 <= 'f' ? 107 - 'a' + 10 : 107 >= 'A' && 107 <= 'F' ? 107 - 'A' + 10 : -1 , 108 >= '0' && 108 <= '9' ? 108 - '0' : 108 >= 'a' && 108 <= 'f' ? 108 - 'a' + 10 : 108 >= 'A' && 108 <= 'F' ? 108 - 'A' + 10 : -1 , 109 >= '0' && 109 <= '9' ? 109 - '0' : 109 >= 'a' && 109 <= 'f' ? 109 - 'a' + 10 : 109 >= 'A' && 109 <= 'F' ? 109 - 'A' + 10 : -1 , 110 >= '0' && 110 <= '9' ? 110 - '0' : 110 >= 'a' && 110 <= 'f' ? 110 - 'a' + 10 : 110 >= 'A' && 110 <= 'F' ? 110 - 'A' + 10 : -1 , 111 >= '0' && 111 <= '9' ? 111 - '0' : 111 >= 'a' && 111 <= 'f' ? 111 - 'a' + 10 : 111 >= 'A' && 111 <= 'F' ? 111 - 'A' + 10 : -1 , 112 >= '0' && 112 <= '9' ? 112 - '0' : 112 >= 'a' && 112 <= 'f' ? 112 - 'a' + 10 : 112 >= 'A' && 112 <= 'F' ? 112 - 'A' + 10 : -1 , 113 >= '0' && 113 <= '9' ? 113 - '0' : 113 >= 'a' && 113 <= 'f' ? 113 - 'a' + 10 : 113 >= 'A' && 113 <= 'F' ? 113 - 'A' + 10 : -1 , 114 >= '0' && 114 <= '9' ? 114 - '0' : 114 >= 'a' && 114 <= 'f' ? 114 - 'a' + 10 : 114 >= 'A' && 114 <= 'F' ? 114 - 'A' + 10 : -1 , 115 >= '0' && 115 <= '9' ? 115 - '0' : 115 >= 'a' && 115 <= 'f' ? 115 - 'a' + 10 : 115 >= 'A' && 115 <= 'F' ? 115 - 'A' + 10 : -1 , 116 >= '0' && 116 <= '9' ? 116 - '0' : 116 >= 'a' && 116 <= 'f' ? 116 - 'a' + 10 : 116 >= 'A' && 116 <= 'F' ? 116 - 'A' + 10 : -1 , 117 >= '0' && 117 <= '9' ? 117 - '0' : 117 >= 'a' && 117 <= 'f' ? 117 - 'a' + 10 : 117 >= 'A' && 117 <= 'F' ? 117 - 'A' + 10 : -1 , 118 >= '0' && 118 <= '9' ? 118 - '0' : 118 >= 'a' && 118 <= 'f' ? 118 - 'a' + 10 : 118 >= 'A' && 118 <= 'F' ? 118 - 'A' + 10 : -1 , 119 >= '0' && 119 <= '9' ? 119 - '0' : 119 >= 'a' && 119 <= 'f' ? 119 - 'a' + 10 : 119 >= 'A' && 119 <= 'F' ? 119 - 'A' + 10 : -1 , 120 >= '0' && 120 <= '9' ? 120 - '0' : 120 >= 'a' && 120 <= 'f' ? 120 - 'a' + 10 : 120 >= 'A' && 120 <= 'F' ? 120 - 'A' + 10 : -1 , 121 >= '0' && 121 <= '9' ? 121 - '0' : 121 >= 'a' && 121 <= 'f' ? 121 - 'a' + 10 : 121 >= 'A' && 121 <= 'F' ? 121 - 'A' + 10 : -1 , 122 >= '0' && 122 <= '9' ? 122 - '0' : 122 >= 'a' && 122 <= 'f' ? 122 - 'a' + 10 : 122 >= 'A' && 122 <= 'F' ? 122 - 'A' + 10 : -1 , 123 >= '0' && 123 <= '9' ? 123 - '0' : 123 >= 'a' && 123 <= 'f' ? 123 - 'a' + 10 : 123 >= 'A' && 123 <= 'F' ? 123 - 'A' + 10 : -1 , 124 >= '0' && 124 <= '9' ? 124 - '0' : 124 >= 'a' && 124 <= 'f' ? 124 - 'a' + 10 : 124 >= 'A' && 124 <= 'F' ? 124 - 'A' + 10 : -1 , 125 >= '0' && 125 <= '9' ? 125 - '0' : 125 >= 'a' && 125 <= 'f' ? 125 - 'a' + 10 : 125 >= 'A' && 125 <= 'F' ? 125 - 'A' + 10 : -1 , 126 >= '0' && 126 <= '9' ? 126 - '0' : 126 >= 'a' && 126 <= 'f' ? 126 - 'a' + 10 : 126 >= 'A' && 126 <= 'F' ? 126 - 'A' + 10 : -1 , 127 >= '0' && 127 <= '9' ? 127 - '0' : 127 >= 'a' && 127 <= 'f' ? 127 - 'a' + 10 : 127 >= 'A' && 127 <= 'F' ? 127 - 'A' + 10 : -1 , 128 >= '0' && 128 <= '9' ? 128 - '0' : 128 >= 'a' && 128 <= 'f' ? 128 - 'a' + 10 : 128 >= 'A' && 128 <= 'F' ? 128 - 'A' + 10 : -1 , 129 >= '0' && 129 <= '9' ? 129 - '0' : 129 >= 'a' && 129 <= 'f' ? 129 - 'a' + 10 : 129 >= 'A' && 129 <= 'F' ? 129 - 'A' + 10 : -1 , 130 >= '0' && 130 <= '9' ? 130 - '0' : 130 >= 'a' && 130 <= 'f' ? 130 - 'a' + 10 : 130 >= 'A' && 130 <= 'F' ? 130 - 'A' + 10 : -1 , 131 >= '0' && 131 <= '9' ? 131 - '0' : 131 >= 'a' && 131 <= 'f' ? 131 - 'a' + 10 : 131 >= 'A' && 131 <= 'F' ? 131 - 'A' + 10 : -1 , 132 >= '0' && 132 <= '9' ? 132 - '0' : 132 >= 'a' && 132 <= 'f' ? 132 - 'a' + 10 : 132 >= 'A' && 132 <= 'F' ? 132 - 'A' + 10 : -1 , 133 >= '0' && 133 <= '9' ? 133 - '0' : 133 >= 'a' && 133 <= 'f' ? 133 - 'a' + 10 : 133 >= 'A' && 133 <= 'F' ? 133 - 'A' + 10 : -1 , 134 >= '0' && 134 <= '9' ? 134 - '0' : 134 >= 'a' && 134 <= 'f' ? 134 - 'a' + 10 : 134 >= 'A' && 134 <= 'F' ? 134 - 'A' + 10 : -1 , 135 >= '0' && 135 <= '9' ? 135 - '0' : 135 >= 'a' && 135 <= 'f' ? 135 - 'a' + 10 : 135 >= 'A' && 135 <= 'F' ? 135 - 'A' + 10 : -1 , 136 >= '0' && 136 <= '9' ? 136 - '0' : 136 >= 'a' && 136 <= 'f' ? 136 - 'a' + 10 : 136 >= 'A' && 136 <= 'F' ? 136 - 'A' + 10 : -1 , 137 >= '0' && 137 <= '9' ? 137 - '0' : 137 >= 'a' && 137 <= 'f' ? 137 - 'a' + 10 : 137 >= 'A' && 137 <= 'F' ? 137 - 'A' + 10 : -1 , 138 >= '0' && 138 <= '9' ? 138 - '0' : 138 >= 'a' && 138 <= 'f' ? 138 - 'a' + 10 : 138 >= 'A' && 138 <= 'F' ? 138 - 'A' + 10 : -1 , 139 >= '0' && 139 <= '9' ? 139 - '0' : 139 >= 'a' && 139 <= 'f' ? 139 - 'a' + 10 : 139 >= 'A' && 139 <= 'F' ? 139 - 'A' + 10 : -1 , 140 >= '0' && 140 <= '9' ? 140 - '0' : 140 >= 'a' && 140 <= 'f' ? 140 - 'a' + 10 : 140 >= 'A' && 140 <= 'F' ? 140 - 'A' + 10 : -1 , 141 >= '0' && 141 <= '9' ? 141 - '0' : 141 >= 'a' && 141 <= 'f' ? 141 - 'a' + 10 : 141 >= 'A' && 141 <= 'F' ? 141 - 'A' + 10 : -1 , 142 >= '0' && 142 <= '9' ? 142 - '0' : 142 >= 'a' && 142 <= 'f' ? 142 - 'a' + 10 : 142 >= 'A' && 142 <= 'F' ? 142 - 'A' + 10 : -1 , 143 >= '0' && 143 <= '9' ? 143 - '0' : 143 >= 'a' && 143 <= 'f' ? 143 - 'a' + 10 : 143 >= 'A' && 143 <= 'F' ? 143 - 'A' + 10 : -1 , 144 >= '0' && 144 <= '9' ? 144 - '0' : 144 >= 'a' && 144 <= 'f' ? 144 - 'a' + 10 : 144 >= 'A' && 144 <= 'F' ? 144 - 'A' + 10 : -1 , 145 >= '0' && 145 <= '9' ? 145 - '0' : 145 >= 'a' && 145 <= 'f' ? 145 - 'a' + 10 : 145 >= 'A' && 145 <= 'F' ? 145 - 'A' + 10 : -1 , 146 >= '0' && 146 <= '9' ? 146 - '0' : 146 >= 'a' && 146 <= 'f' ? 146 - 'a' + 10 : 146 >= 'A' && 146 <= 'F' ? 146 - 'A' + 10 : -1 , 147 >= '0' && 147 <= '9' ? 147 - '0' : 147 >= 'a' && 147 <= 'f' ? 147 - 'a' + 10 : 147 >= 'A' && 147 <= 'F' ? 147 - 'A' + 10 : -1 , 148 >= '0' && 148 <= '9' ? 148 - '0' : 148 >= 'a' && 148 <= 'f' ? 148 - 'a' + 10 : 148 >= 'A' && 148 <= 'F' ? 148 - 'A' + 10 : -1 , 149 >= '0' && 149 <= '9' ? 149 - '0' : 149 >= 'a' && 149 <= 'f' ? 149 - 'a' + 10 : 149 >= 'A' && 149 <= 'F' ? 149 - 'A' + 10 : -1 , 150 >= '0' && 150 <= '9' ? 150 - '0' : 150 >= 'a' && 150 <= 'f' ? 150 - 'a' + 10 : 150 >= 'A' && 150 <= 'F' ? 150 - 'A' + 10 : -1 , 151 >= '0' && 151 <= '9' ? 151 - '0' : 151 >= 'a' && 151 <= 'f' ? 151 - 'a' + 10 : 151 >= 'A' && 151 <= 'F' ? 151 - 'A' + 10 : -1 , 152 >= '0' && 152 <= '9' ? 152 - '0' : 152 >= 'a' && 152 <= 'f' ? 152 - 'a' + 10 : 152 >= 'A' && 152 <= 'F' ? 152 - 'A' + 10 : -1 , 153 >= '0' && 153 <= '9' ? 153 - '0' : 153 >= 'a' && 153 <= 'f' ? 153 - 'a' + 10 : 153 >= 'A' && 153 <= 'F' ? 153 - 'A' + 10 : -1 , 154 >= '0' && 154 <= '9' ? 154 - '0' : 154 >= 'a' && 154 <= 'f' ? 154 - 'a' + 10 : 154 >= 'A' && 154 <= 'F' ? 154 - 'A' + 10 : -1 , 155 >= '0' && 155 <= '9' ? 155 - '0' : 155 >= 'a' && 155 <= 'f' ? 155 - 'a' + 10 : 155 >= 'A' && 155 <= 'F' ? 155 - 'A' + 10 : -1 , 156 >= '0' && 156 <= '9' ? 156 - '0' : 156 >= 'a' && 156 <= 'f' ? 156 - 'a' + 10 : 156 >= 'A' && 156 <= 'F' ? 156 - 'A' + 10 : -1 , 157 >= '0' && 157 <= '9' ? 157 - '0' : 157 >= 'a' && 157 <= 'f' ? 157 - 'a' + 10 : 157 >= 'A' && 157 <= 'F' ? 157 - 'A' + 10 : -1 , 158 >= '0' && 158 <= '9' ? 158 - '0' : 158 >= 'a' && 158 <= 'f' ? 158 - 'a' + 10 : 158 >= 'A' && 158 <= 'F' ? 158 - 'A' + 10 : -1 , 159 >= '0' && 159 <= '9' ? 159 - '0' : 159 >= 'a' && 159 <= 'f' ? 159 - 'a' + 10 : 159 >= 'A' && 159 <= 'F' ? 159 - 'A' + 10 : -1 , 160 >= '0' && 160 <= '9' ? 160 - '0' : 160 >= 'a' && 160 <= 'f' ? 160 - 'a' + 10 : 160 >= 'A' && 160 <= 'F' ? 160 - 'A' + 10 : -1 , 161 >= '0' && 161 <= '9' ? 161 - '0' : 161 >= 'a' && 161 <= 'f' ? 161 - 'a' + 10 : 161 >= 'A' && 161 <= 'F' ? 161 - 'A' + 10 : -1 , 162 >= '0' && 162 <= '9' ? 162 - '0' : 162 >= 'a' && 162 <= 'f' ? 162 - 'a' + 10 : 162 >= 'A' && 162 <= 'F' ? 162 - 'A' + 10 : -1 , 163 >= '0' && 163 <= '9' ? 163 - '0' : 163 >= 'a' && 163 <= 'f' ? 163 - 'a' + 10 : 163 >= 'A' && 163 <= 'F' ? 163 - 'A' + 10 : -1 , 164 >= '0' && 164 <= '9' ? 164 - '0' : 164 >= 'a' && 164 <= 'f' ? 164 - 'a' + 10 : 164 >= 'A' && 164 <= 'F' ? 164 - 'A' + 10 : -1 , 165 >= '0' && 165 <= '9' ? 165 - '0' : 165 >= 'a' && 165 <= 'f' ? 165 - 'a' + 10 : 165 >= 'A' && 165 <= 'F' ? 165 - 'A' + 10 : -1 , 166 >= '0' && 166 <= '9' ? 166 - '0' : 166 >= 'a' && 166 <= 'f' ? 166 - 'a' + 10 : 166 >= 'A' && 166 <= 'F' ? 166 - 'A' + 10 : -1 , 167 >= '0' && 167 <= '9' ? 167 - '0' : 167 >= 'a' && 167 <= 'f' ? 167 - 'a' + 10 : 167 >= 'A' && 167 <= 'F' ? 167 - 'A' + 10 : -1 , 168 >= '0' && 168 <= '9' ? 168 - '0' : 168 >= 'a' && 168 <= 'f' ? 168 - 'a' + 10 : 168 >= 'A' && 168 <= 'F' ? 168 - 'A' + 10 : -1 , 169 >= '0' && 169 <= '9' ? 169 - '0' : 169 >= 'a' && 169 <= 'f' ? 169 - 'a' + 10 : 169 >= 'A' && 169 <= 'F' ? 169 - 'A' + 10 : -1 , 170 >= '0' && 170 <= '9' ? 170 - '0' : 170 >= 'a' && 170 <= 'f' ? 170 - 'a' + 10 : 170 >= 'A' && 170 <= 'F' ? 170 - 'A' + 10 : -1 , 171 >= '0' && 171 <= '9' ? 171 - '0' : 171 >= 'a' && 171 <= 'f' ? 171 - 'a' + 10 : 171 >= 'A' && 171 <= 'F' ? 171 - 'A' + 10 : -1 , 172 >= '0' && 172 <= '9' ? 172 - '0' : 172 >= 'a' && 172 <= 'f' ? 172 - 'a' + 10 : 172 >= 'A' && 172 <= 'F' ? 172 - 'A' + 10 : -1 , 173 >= '0' && 173 <= '9' ? 173 - '0' : 173 >= 'a' && 173 <= 'f' ? 173 - 'a' + 10 : 173 >= 'A' && 173 <= 'F' ? 173 - 'A' + 10 : -1 , 174 >= '0' && 174 <= '9' ? 174 - '0' : 174 >= 'a' && 174 <= 'f' ? 174 - 'a' + 10 : 174 >= 'A' && 174 <= 'F' ? 174 - 'A' + 10 : -1 , 175 >= '0' && 175 <= '9' ? 175 - '0' : 175 >= 'a' && 175 <= 'f' ? 175 - 'a' + 10 : 175 >= 'A' && 175 <= 'F' ? 175 - 'A' + 10 : -1 , 176 >= '0' && 176 <= '9' ? 176 - '0' : 176 >= 'a' && 176 <= 'f' ? 176 - 'a' + 10 : 176 >= 'A' && 176 <= 'F' ? 176 - 'A' + 10 : -1 , 177 >= '0' && 177 <= '9' ? 177 - '0' : 177 >= 'a' && 177 <= 'f' ? 177 - 'a' + 10 : 177 >= 'A' && 177 <= 'F' ? 177 - 'A' + 10 : -1 , 178 >= '0' && 178 <= '9' ? 178 - '0' : 178 >= 'a' && 178 <= 'f' ? 178 - 'a' + 10 : 178 >= 'A' && 178 <= 'F' ? 178 - 'A' + 10 : -1 , 179 >= '0' && 179 <= '9' ? 179 - '0' : 179 >= 'a' && 179 <= 'f' ? 179 - 'a' + 10 : 179 >= 'A' && 179 <= 'F' ? 179 - 'A' + 10 : -1 , 180 >= '0' && 180 <= '9' ? 180 - '0' : 180 >= 'a' && 180 <= 'f' ? 180 - 'a' + 10 : 180 >= 'A' && 180 <= 'F' ? 180 - 'A' + 10 : -1 , 181 >= '0' && 181 <= '9' ? 181 - '0' : 181 >= 'a' && 181 <= 'f' ? 181 - 'a' + 10 : 181 >= 'A' && 181 <= 'F' ? 181 - 'A' + 10 : -1 , 182 >= '0' && 182 <= '9' ? 182 - '0' : 182 >= 'a' && 182 <= 'f' ? 182 - 'a' + 10 : 182 >= 'A' && 182 <= 'F' ? 182 - 'A' + 10 : -1 , 183 >= '0' && 183 <= '9' ? 183 - '0' : 183 >= 'a' && 183 <= 'f' ? 183 - 'a' + 10 : 183 >= 'A' && 183 <= 'F' ? 183 - 'A' + 10 : -1 , 184 >= '0' && 184 <= '9' ? 184 - '0' : 184 >= 'a' && 184 <= 'f' ? 184 - 'a' + 10 : 184 >= 'A' && 184 <= 'F' ? 184 - 'A' + 10 : -1 , 185 >= '0' && 185 <= '9' ? 185 - '0' : 185 >= 'a' && 185 <= 'f' ? 185 - 'a' + 10 : 185 >= 'A' && 185 <= 'F' ? 185 - 'A' + 10 : -1 , 186 >= '0' && 186 <= '9' ? 186 - '0' : 186 >= 'a' && 186 <= 'f' ? 186 - 'a' + 10 : 186 >= 'A' && 186 <= 'F' ? 186 - 'A' + 10 : -1 , 187 >= '0' && 187 <= '9' ? 187 - '0' : 187 >= 'a' && 187 <= 'f' ? 187 - 'a' + 10 : 187 >= 'A' && 187 <= 'F' ? 187 - 'A' + 10 : -1 , 188 >= '0' && 188 <= '9' ? 188 - '0' : 188 >= 'a' && 188 <= 'f' ? 188 - 'a' + 10 : 188 >= 'A' && 188 <= 'F' ? 188 - 'A' + 10 : -1 , 189 >= '0' && 189 <= '9' ? 189 - '0' : 189 >= 'a' && 189 <= 'f' ? 189 - 'a' + 10 : 189 >= 'A' && 189 <= 'F' ? 189 - 'A' + 10 : -1 , 190 >= '0' && 190 <= '9' ? 190 - '0' : 190 >= 'a' && 190 <= 'f' ? 190 - 'a' + 10 : 190 >= 'A' && 190 <= 'F' ? 190 - 'A' + 10 : -1 , 191 >= '0' && 191 <= '9' ? 191 - '0' : 191 >= 'a' && 191 <= 'f' ? 191 - 'a' + 10 : 191 >= 'A' && 191 <= 'F' ? 191 - 'A' + 10 : -1 , 192 >= '0' && 192 <= '9' ? 192 - '0' : 192 >= 'a' && 192 <= 'f' ? 192 - 'a' + 10 : 192 >= 'A' && 192 <= 'F' ? 192 - 'A' + 10 : -1 , 193 >= '0' && 193 <= '9' ? 193 - '0' : 193 >= 'a' && 193 <= 'f' ? 193 - 'a' + 10 : 193 >= 'A' && 193 <= 'F' ? 193 - 'A' + 10 : -1 , 194 >= '0' && 194 <= '9' ? 194 - '0' : 194 >= 'a' && 194 <= 'f' ? 194 - 'a' + 10 : 194 >= 'A' && 194 <= 'F' ? 194 - 'A' + 10 : -1 , 195 >= '0' && 195 <= '9' ? 195 - '0' : 195 >= 'a' && 195 <= 'f' ? 195 - 'a' + 10 : 195 >= 'A' && 195 <= 'F' ? 195 - 'A' + 10 : -1 , 196 >= '0' && 196 <= '9' ? 196 - '0' : 196 >= 'a' && 196 <= 'f' ? 196 - 'a' + 10 : 196 >= 'A' && 196 <= 'F' ? 196 - 'A' + 10 : -1 , 197 >= '0' && 197 <= '9' ? 197 - '0' : 197 >= 'a' && 197 <= 'f' ? 197 - 'a' + 10 : 197 >= 'A' && 197 <= 'F' ? 197 - 'A' + 10 : -1 , 198 >= '0' && 198 <= '9' ? 198 - '0' : 198 >= 'a' && 198 <= 'f' ? 198 - 'a' + 10 : 198 >= 'A' && 198 <= 'F' ? 198 - 'A' + 10 : -1 , 199 >= '0' && 199 <= '9' ? 199 - '0' : 199 >= 'a' && 199 <= 'f' ? 199 - 'a' + 10 : 199 >= 'A' && 199 <= 'F' ? 199 - 'A' + 10 : -1 , 200 >= '0' && 200 <= '9' ? 200 - '0' : 200 >= 'a' && 200 <= 'f' ? 200 - 'a' + 10 : 200 >= 'A' && 200 <= 'F' ? 200 - 'A' + 10 : -1 , 201 >= '0' && 201 <= '9' ? 201 - '0' : 201 >= 'a' && 201 <= 'f' ? 201 - 'a' + 10 : 201 >= 'A' && 201 <= 'F' ? 201 - 'A' + 10 : -1 , 202 >= '0' && 202 <= '9' ? 202 - '0' : 202 >= 'a' && 202 <= 'f' ? 202 - 'a' + 10 : 202 >= 'A' && 202 <= 'F' ? 202 - 'A' + 10 : -1 , 203 >= '0' && 203 <= '9' ? 203 - '0' : 203 >= 'a' && 203 <= 'f' ? 203 - 'a' + 10 : 203 >= 'A' && 203 <= 'F' ? 203 - 'A' + 10 : -1 , 204 >= '0' && 204 <= '9' ? 204 - '0' : 204 >= 'a' && 204 <= 'f' ? 204 - 'a' + 10 : 204 >= 'A' && 204 <= 'F' ? 204 - 'A' + 10 : -1 , 205 >= '0' && 205 <= '9' ? 205 - '0' : 205 >= 'a' && 205 <= 'f' ? 205 - 'a' + 10 : 205 >= 'A' && 205 <= 'F' ? 205 - 'A' + 10 : -1 , 206 >= '0' && 206 <= '9' ? 206 - '0' : 206 >= 'a' && 206 <= 'f' ? 206 - 'a' + 10 : 206 >= 'A' && 206 <= 'F' ? 206 - 'A' + 10 : -1 , 207 >= '0' && 207 <= '9' ? 207 - '0' : 207 >= 'a' && 207 <= 'f' ? 207 - 'a' + 10 : 207 >= 'A' && 207 <= 'F' ? 207 - 'A' + 10 : -1 , 208 >= '0' && 208 <= '9' ? 208 - '0' : 208 >= 'a' && 208 <= 'f' ? 208 - 'a' + 10 : 208 >= 'A' && 208 <= 'F' ? 208 - 'A' + 10 : -1 , 209 >= '0' && 209 <= '9' ? 209 - '0' : 209 >= 'a' && 209 <= 'f' ? 209 - 'a' + 10 : 209 >= 'A' && 209 <= 'F' ? 209 - 'A' + 10 : -1 , 210 >= '0' && 210 <= '9' ? 210 - '0' : 210 >= 'a' && 210 <= 'f' ? 210 - 'a' + 10 : 210 >= 'A' && 210 <= 'F' ? 210 - 'A' + 10 : -1 , 211 >= '0' && 211 <= '9' ? 211 - '0' : 211 >= 'a' && 211 <= 'f' ? 211 - 'a' + 10 : 211 >= 'A' && 211 <= 'F' ? 211 - 'A' + 10 : -1 , 212 >= '0' && 212 <= '9' ? 212 - '0' : 212 >= 'a' && 212 <= 'f' ? 212 - 'a' + 10 : 212 >= 'A' && 212 <= 'F' ? 212 - 'A' + 10 : -1 , 213 >= '0' && 213 <= '9' ? 213 - '0' : 213 >= 'a' && 213 <= 'f' ? 213 - 'a' + 10 : 213 >= 'A' && 213 <= 'F' ? 213 - 'A' + 10 : -1 , 214 >= '0' && 214 <= '9' ? 214 - '0' : 214 >= 'a' && 214 <= 'f' ? 214 - 'a' + 10 : 214 >= 'A' && 214 <= 'F' ? 214 - 'A' + 10 : -1 , 215 >= '0' && 215 <= '9' ? 215 - '0' : 215 >= 'a' && 215 <= 'f' ? 215 - 'a' + 10 : 215 >= 'A' && 215 <= 'F' ? 215 - 'A' + 10 : -1 , 216 >= '0' && 216 <= '9' ? 216 - '0' : 216 >= 'a' && 216 <= 'f' ? 216 - 'a' + 10 : 216 >= 'A' && 216 <= 'F' ? 216 - 'A' + 10 : -1 , 217 >= '0' && 217 <= '9' ? 217 - '0' : 217 >= 'a' && 217 <= 'f' ? 217 - 'a' + 10 : 217 >= 'A' && 217 <= 'F' ? 217 - 'A' + 10 : -1 , 218 >= '0' && 218 <= '9' ? 218 - '0' : 218 >= 'a' && 218 <= 'f' ? 218 - 'a' + 10 : 218 >= 'A' && 218 <= 'F' ? 218 - 'A' + 10 : -1 , 219 >= '0' && 219 <= '9' ? 219 - '0' : 219 >= 'a' && 219 <= 'f' ? 219 - 'a' + 10 : 219 >= 'A' && 219 <= 'F' ? 219 - 'A' + 10 : -1 , 220 >= '0' && 220 <= '9' ? 220 - '0' : 220 >= 'a' && 220 <= 'f' ? 220 - 'a' + 10 : 220 >= 'A' && 220 <= 'F' ? 220 - 'A' + 10 : -1 , 221 >= '0' && 221 <= '9' ? 221 - '0' : 221 >= 'a' && 221 <= 'f' ? 221 - 'a' + 10 : 221 >= 'A' && 221 <= 'F' ? 221 - 'A' + 10 : -1 , 222 >= '0' && 222 <= '9' ? 222 - '0' : 222 >= 'a' && 222 <= 'f' ? 222 - 'a' + 10 : 222 >= 'A' && 222 <= 'F' ? 222 - 'A' + 10 : -1 , 223 >= '0' && 223 <= '9' ? 223 - '0' : 223 >= 'a' && 223 <= 'f' ? 223 - 'a' + 10 : 223 >= 'A' && 223 <= 'F' ? 223 - 'A' + 10 : -1 , 224 >= '0' && 224 <= '9' ? 224 - '0' : 224 >= 'a' && 224 <= 'f' ? 224 - 'a' + 10 : 224 >= 'A' && 224 <= 'F' ? 224 - 'A' + 10 : -1 , 225 >= '0' && 225 <= '9' ? 225 - '0' : 225 >= 'a' && 225 <= 'f' ? 225 - 'a' + 10 : 225 >= 'A' && 225 <= 'F' ? 225 - 'A' + 10 : -1 , 226 >= '0' && 226 <= '9' ? 226 - '0' : 226 >= 'a' && 226 <= 'f' ? 226 - 'a' + 10 : 226 >= 'A' && 226 <= 'F' ? 226 - 'A' + 10 : -1 , 227 >= '0' && 227 <= '9' ? 227 - '0' : 227 >= 'a' && 227 <= 'f' ? 227 - 'a' + 10 : 227 >= 'A' && 227 <= 'F' ? 227 - 'A' + 10 : -1 , 228 >= '0' && 228 <= '9' ? 228 - '0' : 228 >= 'a' && 228 <= 'f' ? 228 - 'a' + 10 : 228 >= 'A' && 228 <= 'F' ? 228 - 'A' + 10 : -1 , 229 >= '0' && 229 <= '9' ? 229 - '0' : 229 >= 'a' && 229 <= 'f' ? 229 - 'a' + 10 : 229 >= 'A' && 229 <= 'F' ? 229 - 'A' + 10 : -1 , 230 >= '0' && 230 <= '9' ? 230 - '0' : 230 >= 'a' && 230 <= 'f' ? 230 - 'a' + 10 : 230 >= 'A' && 230 <= 'F' ? 230 - 'A' + 10 : -1 , 231 >= '0' && 231 <= '9' ? 231 - '0' : 231 >= 'a' && 231 <= 'f' ? 231 - 'a' + 10 : 231 >= 'A' && 231 <= 'F' ? 231 - 'A' + 10 : -1 , 232 >= '0' && 232 <= '9' ? 232 - '0' : 232 >= 'a' && 232 <= 'f' ? 232 - 'a' + 10 : 232 >= 'A' && 232 <= 'F' ? 232 - 'A' + 10 : -1 , 233 >= '0' && 233 <= '9' ? 233 - '0' : 233 >= 'a' && 233 <= 'f' ? 233 - 'a' + 10 : 233 >= 'A' && 233 <= 'F' ? 233 - 'A' + 10 : -1 , 234 >= '0' && 234 <= '9' ? 234 - '0' : 234 >= 'a' && 234 <= 'f' ? 234 - 'a' + 10 : 234 >= 'A' && 234 <= 'F' ? 234 - 'A' + 10 : -1 , 235 >= '0' && 235 <= '9' ? 235 - '0' : 235 >= 'a' && 235 <= 'f' ? 235 - 'a' + 10 : 235 >= 'A' && 235 <= 'F' ? 235 - 'A' + 10 : -1 , 236 >= '0' && 236 <= '9' ? 236 - '0' : 236 >= 'a' && 236 <= 'f' ? 236 - 'a' + 10 : 236 >= 'A' && 236 <= 'F' ? 236 - 'A' + 10 : -1 , 237 >= '0' && 237 <= '9' ? 237 - '0' : 237 >= 'a' && 237 <= 'f' ? 237 - 'a' + 10 : 237 >= 'A' && 237 <= 'F' ? 237 - 'A' + 10 : -1 , 238 >= '0' && 238 <= '9' ? 238 - '0' : 238 >= 'a' && 238 <= 'f' ? 238 - 'a' + 10 : 238 >= 'A' && 238 <= 'F' ? 238 - 'A' + 10 : -1 , 239 >= '0' && 239 <= '9' ? 239 - '0' : 239 >= 'a' && 239 <= 'f' ? 239 - 'a' + 10 : 239 >= 'A' && 239 <= 'F' ? 239 - 'A' + 10 : -1 , 240 >= '0' && 240 <= '9' ? 240 - '0' : 240 >= 'a' && 240 <= 'f' ? 240 - 'a' + 10 : 240 >= 'A' && 240 <= 'F' ? 240 - 'A' + 10 : -1 , 241 >= '0' && 241 <= '9' ? 241 - '0' : 241 >= 'a' && 241 <= 'f' ? 241 - 'a' + 10 : 241 >= 'A' && 241 <= 'F' ? 241 - 'A' + 10 : -1 , 242 >= '0' && 242 <= '9' ? 242 - '0' : 242 >= 'a' && 242 <= 'f' ? 242 - 'a' + 10 : 242 >= 'A' && 242 <= 'F' ? 242 - 'A' + 10 : -1 , 243 >= '0' && 243 <= '9' ? 243 - '0' : 243 >= 'a' && 243 <= 'f' ? 243 - 'a' + 10 : 243 >= 'A' && 243 <= 'F' ? 243 - 'A' + 10 : -1 , 244 >= '0' && 244 <= '9' ? 244 - '0' : 244 >= 'a' && 244 <= 'f' ? 244 - 'a' + 10 : 244 >= 'A' && 244 <= 'F' ? 244 - 'A' + 10 : -1 , 245 >= '0' && 245 <= '9' ? 245 - '0' : 245 >= 'a' && 245 <= 'f' ? 245 - 'a' + 10 : 245 >= 'A' && 245 <= 'F' ? 245 - 'A' + 10 : -1 , 246 >= '0' && 246 <= '9' ? 246 - '0' : 246 >= 'a' && 246 <= 'f' ? 246 - 'a' + 10 : 246 >= 'A' && 246 <= 'F' ? 246 - 'A' + 10 : -1 , 247 >= '0' && 247 <= '9' ? 247 - '0' : 247 >= 'a' && 247 <= 'f' ? 247 - 'a' + 10 : 247 >= 'A' && 247 <= 'F' ? 247 - 'A' + 10 : -1 , 248 >= '0' && 248 <= '9' ? 248 - '0' : 248 >= 'a' && 248 <= 'f' ? 248 - 'a' + 10 : 248 >= 'A' && 248 <= 'F' ? 248 - 'A' + 10 : -1 , 249 >= '0' && 249 <= '9' ? 249 - '0' : 249 >= 'a' && 249 <= 'f' ? 249 - 'a' + 10 : 249 >= 'A' && 249 <= 'F' ? 249 - 'A' + 10 : -1 , 250 >= '0' && 250 <= '9' ? 250 - '0' : 250 >= 'a' && 250 <= 'f' ? 250 - 'a' + 10 : 250 >= 'A' && 250 <= 'F' ? 250 - 'A' + 10 : -1 , 251 >= '0' && 251 <= '9' ? 251 - '0' : 251 >= 'a' && 251 <= 'f' ? 251 - 'a' + 10 : 251 >= 'A' && 251 <= 'F' ? 251 - 'A' + 10 : -1 , 252 >= '0' && 252 <= '9' ? 252 - '0' : 252 >= 'a' && 252 <= 'f' ? 252 - 'a' + 10 : 252 >= 'A' && 252 <= 'F' ? 252 - 'A' + 10 : -1 , 253 >= '0' && 253 <= '9' ? 253 - '0' : 253 >= 'a' && 253 <= 'f' ? 253 - 'a' + 10 : 253 >= 'A' && 253 <= 'F' ? 253 - 'A' + 10 : -1 , 254 >= '0' && 254 <= '9' ? 254 - '0' : 254 >= 'a' && 254 <= 'f' ? 254 - 'a' + 10 : 254 >= 'A' && 254 <= 'F' ? 254 - 'A' + 10 : -1 , 255 >= '0' && 255 <= '9' ? 255 - '0' : 255 >= 'a' && 255 <= 'f' ? 255 - 'a' + 10 : 255 >= 'A' && 255 <= 'F' ? 255 - 'A' + 10 : -1 }; static UV decode_4hex (dec_t *dec) { signed char d1, d2, d3, d4; unsigned char *cur = (unsigned char *)dec->cur; d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly four hexadecimal digits expected"); d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly four hexadecimal digits expected"); d3 = decode_hexdigit [cur [2]]; if (expect_false (d3 < 0)) ERR ("exactly four hexadecimal digits expected"); d4 = decode_hexdigit [cur [3]]; if (expect_false (d4 < 0)) ERR ("exactly four hexadecimal digits expected"); dec->cur += 4; return ((UV)d1) << 12 | ((UV)d2) << 8 | ((UV)d3) << 4 | ((UV)d4); fail: return (UV)-1; } static UV decode_2hex (dec_t *dec) { signed char d1, d2; unsigned char *cur = (unsigned char *)dec->cur; d1 = decode_hexdigit [cur [0]]; if (expect_false (d1 < 0)) ERR ("exactly two hexadecimal digits expected"); d2 = decode_hexdigit [cur [1]]; if (expect_false (d2 < 0)) ERR ("exactly two hexadecimal digits expected"); dec->cur += 2; return ((UV)d1) << 4 | ((UV)d2); fail: return (UV)-1; } static UV decode_3oct (dec_t *dec) { IV d1, d2, d3; unsigned char *cur = (unsigned char *)dec->cur; d1 = (IV)(cur[0] - '0'); if (d1 < 0 || d1 > 7) ERR ("exactly three octal digits expected"); d2 = (IV)(cur[1] - '0'); if (d2 < 0 || d2 > 7) ERR ("exactly three octal digits expected"); d3 = (IV)(cur[2] - '0'); if (d3 < 0 || d3 > 7) ERR ("exactly three octal digits expected"); dec->cur += 3; return (d1 * 64) + (d2 * 8) + d3; fail: return (UV)-1; } static SV * _decode_str (pTHX_ dec_t *dec, char endstr) { SV *sv = 0; int utf8 = 0; char *dec_cur = dec->cur; unsigned char ch; int allow_squote = (dec->json.flags & F_ALLOW_SQUOTE) && (endstr == 0x27); do { char buf [SHORT_STRING_LEN + UTF8_MAXBYTES]; char *cur = buf; do { ch = *(unsigned char *)dec_cur++; if (expect_false (ch == endstr)) { --dec_cur; break; } else if (expect_false (ch == '\\')) { switch (*dec_cur) { case '\\': case '/': case '"': *cur++ = *dec_cur++; break; case 'b': ++dec_cur; *cur++ = '\010'; break; case 't': ++dec_cur; *cur++ = '\011'; break; case 'n': ++dec_cur; *cur++ = '\012'; break; case 'f': ++dec_cur; *cur++ = '\014'; break; case 'r': ++dec_cur; *cur++ = '\015'; break; case 'x': { UV c; if (!(dec->json.flags & F_BINARY)) ERR ("illegal hex character in non-binary string"); ++dec_cur; dec->cur = dec_cur; c = decode_2hex (dec); if (c == (UV)-1) goto fail; *cur++ = c; dec_cur += 2; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { UV c; if (!(dec->json.flags & F_BINARY)) ERR ("illegal octal character in non-binary string"); dec->cur = dec_cur; c = decode_3oct (dec); if (c == (UV)-1) goto fail; *cur++ = c; dec_cur += 3; break; } case 'u': { UV lo, hi; ++dec_cur; dec->cur = dec_cur; hi = decode_4hex (dec); dec_cur = dec->cur; if (hi == (UV)-1) goto fail; if (dec->json.flags & F_BINARY) ERR ("illegal unicode character in binary string"); /* possibly a surrogate pair */ if (hi >= 0xd800) { if (hi < 0xdc00) { if (dec_cur [0] != '\\' || dec_cur [1] != 'u') ERR ("missing low surrogate character in surrogate pair"); dec_cur += 2; dec->cur = dec_cur; lo = decode_4hex (dec); dec_cur = dec->cur; if (lo == (UV)-1) goto fail; if (lo < 0xdc00 || lo >= 0xe000) ERR ("surrogate pair expected"); hi = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000; } else if (hi < 0xe000) { ERR ("missing high surrogate character in surrogate pair"); } } if (hi >= 0x80) { utf8 = 1; cur = (char*)encode_utf8 ((U8*)cur, hi); } else *cur++ = hi; } break; default: --dec_cur; ERR ("illegal backslash escape sequence in string"); } } else if (expect_true (ch >= 0x20 && ch < 0x80)) { *cur++ = ch; if (expect_false (allow_squote && ch == 0x27)) { --dec_cur; break; } } else if (ch >= 0x80) { STRLEN clen; --dec_cur; decode_utf8 (aTHX_ (U8*)dec_cur, dec->end - dec_cur, &clen); if (clen == (STRLEN)-1) ERR ("malformed UTF-8 character in JSON string"); do *cur++ = *dec_cur++; while (--clen); utf8 = 1; } else if (dec->json.flags & F_RELAXED && ch == '\t') { *cur++ = ch; } else { --dec_cur; if (!ch) ERR ("unexpected end of string while parsing JSON string"); else ERR ("invalid character encountered while parsing JSON string"); } } while (cur < buf + SHORT_STRING_LEN); { STRLEN len = cur - buf; if (sv) { STRLEN cur = SvCUR (sv); if (SvLEN (sv) <= cur + len) SvGROW (sv, cur + (len < (cur >> 2) ? cur >> 2 : len) + 1); memcpy (SvPVX (sv) + SvCUR (sv), buf, len); SvCUR_set (sv, SvCUR (sv) + len); } else sv = newSVpvn (buf, len); } } while (*dec_cur != endstr); ++dec_cur; if (sv) { SvPOK_only (sv); *SvEND (sv) = 0; if (utf8) SvUTF8_on (sv); } else sv = newSVpvn ("", 0); dec->cur = dec_cur; return sv; fail: dec->cur = dec_cur; return 0; } INLINE SV * decode_str (pTHX_ dec_t *dec) { return _decode_str(aTHX_ dec, '"'); } INLINE SV * decode_str_sq (pTHX_ dec_t *dec) { return _decode_str(aTHX_ dec, 0x27); } static SV * decode_num (pTHX_ dec_t *dec) { int is_nv = 0; char *start = dec->cur; /* [minus] */ if (*dec->cur == '-') ++dec->cur; if (*dec->cur == '0') { ++dec->cur; if (*dec->cur >= '0' && *dec->cur <= '9') ERR ("malformed number (leading zero must not be followed by another digit)"); } else if (*dec->cur < '0' || *dec->cur > '9') ERR ("malformed number (no digits after initial minus)"); else do { ++dec->cur; } while (*dec->cur >= '0' && *dec->cur <= '9'); /* [frac] */ if (*dec->cur == '.') { ++dec->cur; if (*dec->cur < '0' || *dec->cur > '9') ERR ("malformed number (no digits after decimal point)"); do { ++dec->cur; } while (*dec->cur >= '0' && *dec->cur <= '9'); is_nv = 1; } /* [exp] */ if (*dec->cur == 'e' || *dec->cur == 'E') { ++dec->cur; if (*dec->cur == '-' || *dec->cur == '+') ++dec->cur; if (*dec->cur < '0' || *dec->cur > '9') ERR ("malformed number (no digits after exp sign)"); do { ++dec->cur; } while (*dec->cur >= '0' && *dec->cur <= '9'); is_nv = 1; } if (!is_nv) { int len = dec->cur - start; /* special case the rather common 1..5-digit-int case */ if (*start == '-') switch (len) { case 2: return newSViv (-(IV)( start [1] - '0' * 1)); case 3: return newSViv (-(IV)( start [1] * 10 + start [2] - '0' * 11)); case 4: return newSViv (-(IV)( start [1] * 100 + start [2] * 10 + start [3] - '0' * 111)); case 5: return newSViv (-(IV)( start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 1111)); case 6: return newSViv (-(IV)(start [1] * 10000 + start [2] * 1000 + start [3] * 100 + start [4] * 10 + start [5] - '0' * 11111)); } else switch (len) { case 1: return newSViv ( start [0] - '0' * 1); case 2: return newSViv ( start [0] * 10 + start [1] - '0' * 11); case 3: return newSViv ( start [0] * 100 + start [1] * 10 + start [2] - '0' * 111); case 4: return newSViv ( start [0] * 1000 + start [1] * 100 + start [2] * 10 + start [3] - '0' * 1111); case 5: return newSViv ( start [0] * 10000 + start [1] * 1000 + start [2] * 100 + start [3] * 10 + start [4] - '0' * 11111); } { UV uv; int numtype = grok_number (start, len, &uv); if (numtype & IS_NUMBER_IN_UV) { if (numtype & IS_NUMBER_NEG) { if (uv < (UV)IV_MIN) return newSViv (-(IV)uv); } else return newSVuv (uv); } } len -= *start == '-' ? 1 : 0; /* does not fit into IV or UV, try NV */ if ((sizeof (NV) == sizeof (double) && DBL_DIG >= len) #if defined (LDBL_DIG) || (sizeof (NV) == sizeof (long double) && LDBL_DIG >= len) #endif ) /* fits into NV without loss of precision */ return newSVnv (json_atof (start)); if (dec->json.flags & F_ALLOW_BIGNUM) { SV* pv = newSVpvs("require Math::BigInt && return Math::BigInt->new(\""); sv_catpv(pv, start); sv_catpvs(pv, "\");"); eval_sv(pv, G_SCALAR); SvREFCNT_dec(pv); { dSP; SV *retval = SvREFCNT_inc(POPs); PUTBACK; return retval; } } /* everything else fails, convert it to a string */ return newSVpvn (start, dec->cur - start); } if (dec->json.flags & F_ALLOW_BIGNUM) { SV* pv = newSVpvs("require Math::BigFloat && return Math::BigFloat->new(\""); sv_catpv(pv, start); sv_catpvs(pv, "\");"); eval_sv(pv, G_SCALAR); SvREFCNT_dec(pv); { dSP; SV *retval = SvREFCNT_inc(POPs); PUTBACK; return retval; } } /* loss of precision here */ return newSVnv (json_atof (start)); fail: return 0; } static SV * decode_av (pTHX_ dec_t *dec) { AV *av = newAV (); DEC_INC_DEPTH; decode_ws (dec); if (*dec->cur == ']') ++dec->cur; else for (;;) { SV *value; value = decode_sv (aTHX_ dec); if (!value) goto fail; av_push (av, value); decode_ws (dec); if (*dec->cur == ']') { ++dec->cur; break; } if (*dec->cur != ',') ERR (", or ] expected while parsing array"); ++dec->cur; decode_ws (dec); if (*dec->cur == ']' && dec->json.flags & F_RELAXED) { ++dec->cur; break; } } DEC_DEC_DEPTH; return newRV_noinc ((SV *)av); fail: SvREFCNT_dec (av); DEC_DEC_DEPTH; return 0; } static SV * decode_hv (pTHX_ dec_t *dec) { SV *sv; HV *hv = newHV (); int allow_squote = dec->json.flags & F_ALLOW_SQUOTE; int allow_barekey = dec->json.flags & F_ALLOW_BAREKEY; char endstr = '"'; DEC_INC_DEPTH; decode_ws (dec); if (*dec->cur == '}') ++dec->cur; else for (;;) { int is_bare = allow_barekey; if (expect_false(allow_barekey && *dec->cur >= 'A' && *dec->cur <= 'z')) ; else if (expect_false(allow_squote)) { if (*dec->cur != '"' && *dec->cur != 0x27) { ERR ("'\"' or ''' expected"); } else if (*dec->cur == 0x27) endstr = 0x27; is_bare=0; ++dec->cur; } else { EXPECT_CH ('"'); is_bare=0; } /* heuristic: assume that */ /* a) decode_str + hv_store_ent are abysmally slow. */ /* b) most hash keys are short, simple ascii text. */ /* => try to "fast-match" such strings to avoid */ /* the overhead of decode_str + hv_store_ent. */ { SV *value; char *p = dec->cur; char *e = p + 24; /* only try up to 24 bytes */ for (;;) { /* the >= 0x80 is false on most architectures */ if (!is_bare && (p == e || *p < 0x20 || *(U8*)p >= 0x80 || *p == '\\' || allow_squote)) { /* slow path, back up and use decode_str */ SV *key = _decode_str (aTHX_ dec, endstr); if (!key) goto fail; decode_ws (dec); EXPECT_CH (':'); decode_ws (dec); value = decode_sv (aTHX_ dec); if (!value) { SvREFCNT_dec (key); goto fail; } hv_store_ent (hv, key, value, 0); SvREFCNT_dec (key); break; } else if (*p == endstr || (is_bare && (*p == ':' || *p == ' ' || *p == 0x0a || *p == 0x0d || *p == 0x09))) { /* fast path, got a simple key */ char *key = dec->cur; int len = p - key; dec->cur = p + 1; decode_ws (dec); if (*p != ':') EXPECT_CH (':'); decode_ws (dec); value = decode_sv (aTHX_ dec); if (!value) goto fail; hv_store (hv, key, len, value, 0); break; } ++p; } } decode_ws (dec); if (*dec->cur == '}') { ++dec->cur; break; } if (*dec->cur != ',') ERR (", or } expected while parsing object/hash"); ++dec->cur; decode_ws (dec); if (*dec->cur == '}' && dec->json.flags & F_RELAXED) { ++dec->cur; break; } } DEC_DEC_DEPTH; sv = newRV_noinc ((SV *)hv); /* check filter callbacks */ if (dec->json.flags & F_HOOK) { if (dec->json.cb_sk_object && HvKEYS (hv) == 1) { HE *cb, *he; hv_iterinit (hv); he = hv_iternext (hv); hv_iterinit (hv); /* the next line creates a mortal sv each time its called. */ /* might want to optimise this for common cases. */ cb = hv_fetch_ent (dec->json.cb_sk_object, hv_iterkeysv (he), 0, 0); if (cb) { dSP; int count; ENTER; SAVETMPS; PUSHMARK (SP); XPUSHs (HeVAL (he)); sv_2mortal (sv); PUTBACK; count = call_sv (HeVAL (cb), G_ARRAY); SPAGAIN; if (count == 1) { sv = newSVsv (POPs); PUTBACK; FREETMPS; LEAVE; return sv; } SvREFCNT_inc (sv); SP -= count; PUTBACK; FREETMPS; LEAVE; } } if (dec->json.cb_object) { dSP; int count; ENTER; SAVETMPS; PUSHMARK (SP); XPUSHs (sv_2mortal (sv)); PUTBACK; count = call_sv (dec->json.cb_object, G_ARRAY); SPAGAIN; if (count == 1) { sv = newSVsv (POPs); PUTBACK; FREETMPS; LEAVE; return sv; } SvREFCNT_inc (sv); SP -= count; PUTBACK; FREETMPS; LEAVE; } } return sv; fail: SvREFCNT_dec (hv); DEC_DEC_DEPTH; return 0; } static SV * decode_tag (pTHX_ dec_t *dec) { SV *tag = 0; SV *val = 0; if (!(dec->json.flags & F_ALLOW_TAGS)) ERR ("malformed JSON string, neither array, object, number, string or atom"); ++dec->cur; decode_ws (dec); tag = decode_sv (aTHX_ dec); if (!tag) goto fail; if (!SvPOK (tag)) ERR ("malformed JSON string, (tag) must be a string"); decode_ws (dec); if (*dec->cur != ')') ERR (") expected after tag"); ++dec->cur; decode_ws (dec); val = decode_sv (aTHX_ dec); if (!val) goto fail; if (!SvROK (val) || SvTYPE (SvRV (val)) != SVt_PVAV) ERR ("malformed JSON string, tag value must be an array"); { dMY_CXT; AV *av = (AV *)SvRV (val); int i, len = av_len (av) + 1; HV *stash = gv_stashsv (tag, 0); SV *sv; GV *method; dSP; if (!stash) ERR ("cannot decode perl-object (package does not exist)"); method = gv_fetchmethod_autoload (stash, "THAW", 0); if (!method) ERR ("cannot decode perl-object (package does not have a THAW method)"); ENTER; SAVETMPS; PUSHMARK (SP); EXTEND (SP, len + 2); /* we re-bless the reference to get overload and other niceties right */ PUSHs (tag); PUSHs (MY_CXT.sv_json); for (i = 0; i < len; ++i) PUSHs (*av_fetch (av, i, 1)); PUTBACK; call_sv ((SV *)GvCV (method), G_SCALAR); SPAGAIN; SvREFCNT_dec (tag); SvREFCNT_dec (val); sv = SvREFCNT_inc (POPs); PUTBACK; FREETMPS; LEAVE; return sv; } fail: SvREFCNT_dec (tag); SvREFCNT_dec (val); return 0; } static SV * decode_sv (pTHX_ dec_t *dec) { /* the beauty of JSON: you need exactly one character lookahead */ /* to parse everything. */ switch (*dec->cur) { case '"': ++dec->cur; return decode_str (aTHX_ dec); case 0x27: if (dec->json.flags & F_ALLOW_SQUOTE) { ++dec->cur; return decode_str_sq (aTHX_ dec); } ERR ("malformed JSON string, neither tag, array, object, number, string or atom"); break; case '[': ++dec->cur; return decode_av (aTHX_ dec); case '{': ++dec->cur; return decode_hv (aTHX_ dec); case '(': return decode_tag (aTHX_ dec); case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return decode_num (aTHX_ dec); case 't': if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "true", 4)) { dMY_CXT; dec->cur += 4; return newSVsv(MY_CXT.json_true); } else ERR ("'true' expected"); break; case 'f': if (dec->end - dec->cur >= 5 && !memcmp (dec->cur, "false", 5)) { dMY_CXT; dec->cur += 5; return newSVsv(MY_CXT.json_false); } else ERR ("'false' expected"); break; case 'n': if (dec->end - dec->cur >= 4 && !memcmp (dec->cur, "null", 4)) { dec->cur += 4; return newSVsv(&PL_sv_undef); } else ERR ("'null' expected"); break; default: ERR ("malformed JSON string, neither tag, array, object, number, string or atom"); break; } fail: return 0; } static SV * decode_json (pTHX_ SV *string, JSON *json, U8 **offset_return) { dec_t dec; SV *sv; dMY_CXT; /* work around bugs in 5.10 where manipulating magic values * makes perl ignore the magic in subsequent accesses. * also make a copy of non-PV values, to get them into a clean * state (SvPV should do that, but it's buggy, see below). */ /*SvGETMAGIC (string);*/ if (SvMAGICAL (string) || !SvPOK (string) || SvIsCOW_shared_hash(string)) string = sv_2mortal (newSVsv (string)); SvUPGRADE (string, SVt_PV); /* work around a bug in perl 5.10, which causes SvCUR to fail an * assertion with -DDEBUGGING, although SvCUR is documented to * return the xpv_cur field which certainly exists after upgrading. * according to nicholas clark, calling SvPOK fixes this. * But it doesn't fix it, so try another workaround, call SvPV_nolen * and hope for the best. * Damnit, SvPV_nolen still trips over yet another assertion. This * assertion business is seriously broken, try yet another workaround * for the broken -DDEBUGGING. */ { #ifdef DEBUGGING STRLEN offset = SvOK (string) ? sv_len (string) : 0; #else STRLEN offset = SvCUR (string); #endif if (offset > json->max_size && json->max_size) croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu", (unsigned long)SvCUR (string), (unsigned long)json->max_size); } #if PERL_VERSION >= 8 if (DECODE_WANTS_OCTETS (json)) sv_utf8_downgrade (string, 0); else sv_utf8_upgrade (string); #endif SvGROW (string, SvCUR (string) + 1); /* should basically be a NOP */ dec.json = *json; dec.cur = SvPVX (string); dec.end = SvEND (string); dec.err = 0; dec.depth = 0; if (dec.json.cb_object || dec.json.cb_sk_object) dec.json.flags |= F_HOOK; *dec.end = 0; /* this should basically be a nop, too, but make sure it's there */ decode_ws (&dec); sv = decode_sv (aTHX_ &dec); if (offset_return) *offset_return = (U8*)dec.cur; if (!(offset_return || !sv)) { /* check for trailing garbage */ decode_ws (&dec); if (*dec.cur) { dec.err = "garbage after JSON object"; SvREFCNT_dec (sv); sv = 0; } } if (!sv) { SV *uni = sv_newmortal (); #if PERL_VERSION >= 8 /* horrible hack to silence warning inside pv_uni_display */ COP cop = *PL_curcop; cop.cop_warnings = pWARN_NONE; ENTER; SAVEVPTR (PL_curcop); PL_curcop = &cop; pv_uni_display (uni, (U8*)dec.cur, dec.end - dec.cur, 20, UNI_DISPLAY_QQ); LEAVE; #endif croak ("%s, at character offset %d (before \"%s\")", dec.err, (int)ptr_to_index (aTHX_ string, (U8*)dec.cur), dec.cur != dec.end ? SvPV_nolen (uni) : "(end of string)"); } if (!(dec.json.flags & F_ALLOW_NONREF) && (!SvROK (sv) || SvRV(sv) == SvRV(MY_CXT.json_true) || SvRV(sv) == SvRV(MY_CXT.json_false))) croak ("JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)"); return sv_2mortal (sv); } /*/////////////////////////////////////////////////////////////////////////// */ /* incremental parser */ static void incr_parse (JSON *self) { const char *p = SvPVX (self->incr_text) + self->incr_pos; /* the state machine here is a bit convoluted and could be simplified a lot */ /* but this would make it slower, so... */ for (;;) { /*printf ("loop pod %d *p<%c><%s>, mode %d nest %d\n", p - SvPVX (self->incr_text), *p, p, self->incr_mode, self->incr_nest);//D */ switch (self->incr_mode) { /* only used for initial whitespace skipping */ case INCR_M_WS: for (;;) { if (*p > 0x20) { if (*p == '#') { self->incr_mode = INCR_M_C0; goto incr_m_c; } else { self->incr_mode = INCR_M_JSON; goto incr_m_json; } } else if (!*p) goto interrupt; ++p; } /* skip a single char inside a string (for \\-processing) */ case INCR_M_BS: if (!*p) goto interrupt; ++p; self->incr_mode = INCR_M_STR; goto incr_m_str; /* inside #-style comments */ case INCR_M_C0: case INCR_M_C1: incr_m_c: for (;;) { if (*p == '\n') { self->incr_mode = self->incr_mode == INCR_M_C0 ? INCR_M_WS : INCR_M_JSON; break; } else if (!*p) goto interrupt; ++p; } break; /* inside a string */ case INCR_M_STR: incr_m_str: for (;;) { if (*p == '"') { ++p; self->incr_mode = INCR_M_JSON; if (!self->incr_nest) goto interrupt; goto incr_m_json; } else if (*p == '\\') { ++p; /* "virtually" consumes character after \ */ if (!*p) /* if at end of string we have to switch modes */ { self->incr_mode = INCR_M_BS; goto interrupt; } } else if (!*p) goto interrupt; ++p; } /* after initial ws, outside string */ case INCR_M_JSON: incr_m_json: for (;;) { switch (*p++) { case 0: --p; goto interrupt; case 0x09: case 0x0a: case 0x0d: case 0x20: if (!self->incr_nest) { --p; /* do not eat the whitespace, let the next round do it */ goto interrupt; } break; case '"': self->incr_mode = INCR_M_STR; goto incr_m_str; case '[': case '{': case '(': if (++self->incr_nest > self->max_depth) croak (ERR_NESTING_EXCEEDED); break; case ']': case '}': if (--self->incr_nest <= 0) goto interrupt; break; case ')': --self->incr_nest; break; case '#': self->incr_mode = INCR_M_C1; goto incr_m_c; } } } modechange: ; } interrupt: self->incr_pos = p - SvPVX (self->incr_text); /*printf ("interrupt<%.*s>\n", self->incr_pos, SvPVX(self->incr_text));//D */ /*printf ("return pos %d mode %d nest %d\n", self->incr_pos, self->incr_mode, self->incr_nest);//D */ } /*/////////////////////////////////////////////////////////////////////////// */ /* XS interface functions */ MODULE = Cpanel::JSON::XS PACKAGE = Cpanel::JSON::XS BOOT: { MY_CXT_INIT; init_MY_CXT(aTHX_ &MY_CXT); CvNODEBUG_on (get_cv ("Cpanel::JSON::XS::incr_text", 0)); /* the debugger completely breaks lvalue subs */ } PROTOTYPES: DISABLE #_if PERL_IMPLICIT_CONTEXT for embedding, but no ithreads, then CLONE is never # called #ifdef USE_ITHREADS void CLONE (...) CODE: { MY_CXT_CLONE; /* possible declaration */ init_MY_CXT(aTHX_ &MY_CXT); return; /* skip implicit PUTBACK, returning @_ to caller, more efficient*/ } #endif void END(...) PREINIT: dMY_CXT; SV * sv; PPCODE: sv = MY_CXT.sv_json; MY_CXT.sv_json = NULL; /* todo use SvREFCNT_dec_NN once ppport is fixed */ SvREFCNT_dec(sv); return; /* skip implicit PUTBACK, returning @_ to caller, more efficient*/ void new (char *klass) PPCODE: { dMY_CXT; SV *pv = NEWSV (0, sizeof (JSON)); SvPOK_only (pv); json_init ((JSON *)SvPVX (pv)); XPUSHs (sv_2mortal (sv_bless ( newRV_noinc (pv), strEQ (klass, "Cpanel::JSON::XS") ? JSON_STASH : gv_stashpv (klass, 1) ))); } void ascii (JSON *self, int enable = 1) ALIAS: ascii = F_ASCII latin1 = F_LATIN1 binary = F_BINARY utf8 = F_UTF8 indent = F_INDENT canonical = F_CANONICAL space_before = F_SPACE_BEFORE space_after = F_SPACE_AFTER pretty = F_PRETTY allow_nonref = F_ALLOW_NONREF shrink = F_SHRINK allow_blessed = F_ALLOW_BLESSED convert_blessed = F_CONV_BLESSED relaxed = SET_RELAXED allow_unknown = F_ALLOW_UNKNOWN allow_tags = F_ALLOW_TAGS allow_barekey = F_ALLOW_BAREKEY allow_singlequote = F_ALLOW_SQUOTE allow_bignum = F_ALLOW_BIGNUM escape_slash = F_ESCAPE_SLASH allow_stringify = F_ALLOW_STRINGIFY PPCODE: { if (enable) self->flags |= ix; else self->flags &= ~ix; XPUSHs (ST (0)); } void get_ascii (JSON *self) ALIAS: get_ascii = F_ASCII get_latin1 = F_LATIN1 get_binary = F_BINARY get_utf8 = F_UTF8 get_indent = F_INDENT get_canonical = F_CANONICAL get_space_before = F_SPACE_BEFORE get_space_after = F_SPACE_AFTER get_allow_nonref = F_ALLOW_NONREF get_shrink = F_SHRINK get_allow_blessed = F_ALLOW_BLESSED get_convert_blessed = F_CONV_BLESSED get_relaxed = F_RELAXED get_allow_unknown = F_ALLOW_UNKNOWN get_allow_tags = F_ALLOW_TAGS get_allow_barekey = F_ALLOW_BAREKEY get_allow_singlequote = F_ALLOW_SQUOTE get_allow_bignum = F_ALLOW_BIGNUM get_escape_slash = F_ESCAPE_SLASH get_allow_stringify = F_ALLOW_STRINGIFY PPCODE: XPUSHs (boolSV (self->flags & ix)); void max_depth (JSON *self, U32 max_depth = 0x80000000UL) PPCODE: self->max_depth = max_depth; XPUSHs (ST (0)); U32 get_max_depth (JSON *self) CODE: RETVAL = self->max_depth; OUTPUT: RETVAL void max_size (JSON *self, U32 max_size = 0) PPCODE: self->max_size = max_size; XPUSHs (ST (0)); int get_max_size (JSON *self) CODE: RETVAL = self->max_size; OUTPUT: RETVAL void stringify_infnan (JSON *self, IV infnan_mode = 1) PPCODE: self->infnan_mode = (unsigned char)infnan_mode; if (self->infnan_mode < 0 || self->infnan_mode > 2) { croak ("invalid stringify_infnan mode %c. Must be 0, 1 or 2", self->infnan_mode); } XPUSHs (ST (0)); int get_stringify_infnan (JSON *self) CODE: RETVAL = (int)self->infnan_mode; OUTPUT: RETVAL void sort_by (JSON *self, SV* cb = &PL_sv_yes) PPCODE: { SvREFCNT_dec (self->cb_sort_by); self->cb_sort_by = SvOK (cb) ? newSVsv (cb) : 0; if (self->cb_sort_by) self->flags |= F_CANONICAL; XPUSHs (ST (0)); } void filter_json_object (JSON *self, SV *cb = &PL_sv_undef) PPCODE: { SvREFCNT_dec (self->cb_object); self->cb_object = SvOK (cb) ? newSVsv (cb) : 0; XPUSHs (ST (0)); } void filter_json_single_key_object (JSON *self, SV *key, SV *cb = &PL_sv_undef) PPCODE: { if (!self->cb_sk_object) self->cb_sk_object = newHV (); if (SvOK (cb)) hv_store_ent (self->cb_sk_object, key, newSVsv (cb), 0); else { hv_delete_ent (self->cb_sk_object, key, G_DISCARD, 0); if (!HvKEYS (self->cb_sk_object)) { SvREFCNT_dec (self->cb_sk_object); self->cb_sk_object = 0; } } XPUSHs (ST (0)); } void encode (JSON *self, SV *scalar) PPCODE: PUTBACK; scalar = encode_json (aTHX_ scalar, self); SPAGAIN; XPUSHs (scalar); void decode (JSON *self, SV *jsonstr) PPCODE: PUTBACK; jsonstr = decode_json (aTHX_ jsonstr, self, 0); SPAGAIN; XPUSHs (jsonstr); void decode_prefix (JSON *self, SV *jsonstr) PPCODE: { SV *sv; U8 *offset; PUTBACK; sv = decode_json (aTHX_ jsonstr, self, &offset); SPAGAIN; EXTEND (SP, 2); PUSHs (sv); PUSHs (sv_2mortal (newSVuv (ptr_to_index (aTHX_ jsonstr, offset)))); } void incr_parse (JSON *self, SV *jsonstr = 0) PPCODE: { if (!self->incr_text) self->incr_text = newSVpvn ("", 0); /* if utf8-ness doesn't match the decoder, need to upgrade/downgrade */ if (!DECODE_WANTS_OCTETS (self) == !SvUTF8 (self->incr_text)) { if (DECODE_WANTS_OCTETS (self)) { if (self->incr_pos) self->incr_pos = utf8_length ((U8 *)SvPVX (self->incr_text), (U8 *)SvPVX (self->incr_text) + self->incr_pos); sv_utf8_downgrade (self->incr_text, 0); } else { sv_utf8_upgrade (self->incr_text); if (self->incr_pos) self->incr_pos = utf8_hop ((U8 *)SvPVX (self->incr_text), self->incr_pos) - (U8 *)SvPVX (self->incr_text); } } /* append data, if any */ if (jsonstr) { /* make sure both strings have same encoding */ if (SvUTF8 (jsonstr) != SvUTF8 (self->incr_text)) { if (SvUTF8 (jsonstr)) sv_utf8_downgrade (jsonstr, 0); else sv_utf8_upgrade (jsonstr); } /* and then just blindly append */ { STRLEN len; const char *str = SvPV (jsonstr, len); STRLEN cur = SvCUR (self->incr_text); if (SvLEN (self->incr_text) <= cur + len) SvGROW (self->incr_text, cur + (len < (cur >> 2) ? cur >> 2 : len) + 1); Move (str, SvEND (self->incr_text), len, char); SvCUR_set (self->incr_text, SvCUR (self->incr_text) + len); *SvEND (self->incr_text) = 0; /* this should basically be a nop, too, but make sure it's there */ } } if (GIMME_V != G_VOID) do { SV *sv; U8 *offset; if (!INCR_DONE (self)) { incr_parse (self); if (self->incr_pos > self->max_size && self->max_size) croak ("attempted decode of JSON text of %lu bytes size, but max_size is set to %lu", (unsigned long)self->incr_pos, (unsigned long)self->max_size); if (!INCR_DONE (self)) { /* as an optimisation, do not accumulate white space in the incr buffer */ if (self->incr_mode == INCR_M_WS && self->incr_pos) { self->incr_pos = 0; SvCUR_set (self->incr_text, 0); } break; } } PUTBACK; sv = decode_json (aTHX_ self->incr_text, self, &offset); SPAGAIN; XPUSHs (sv); self->incr_pos -= offset - (U8*)SvPVX (self->incr_text); self->incr_nest = 0; self->incr_mode = 0; #if PERL_VERSION > 9 sv_chop (self->incr_text, (const char* const)offset); #else sv_chop (self->incr_text, (char*)offset); #endif } while (GIMME_V == G_ARRAY); } #if PERL_VERSION > 6 SV *incr_text (JSON *self) ATTRS: lvalue CODE: { if (self->incr_pos) croak ("incr_text can not be called when the incremental parser already started parsing"); RETVAL = self->incr_text ? SvREFCNT_inc (self->incr_text) : &PL_sv_undef; } OUTPUT: RETVAL #else SV *incr_text (JSON *self) CODE: { if (self->incr_pos) croak ("incr_text can not be called when the incremental parser already started parsing"); RETVAL = self->incr_text ? SvREFCNT_inc (self->incr_text) : &PL_sv_undef; } OUTPUT: RETVAL #endif void incr_skip (JSON *self) CODE: { if (self->incr_pos) { sv_chop (self->incr_text, SvPV_nolen (self->incr_text) + self->incr_pos); self->incr_pos = 0; self->incr_nest = 0; self->incr_mode = 0; } } void incr_reset (JSON *self) CODE: { SvREFCNT_dec (self->incr_text); self->incr_text = 0; self->incr_pos = 0; self->incr_nest = 0; self->incr_mode = 0; } void DESTROY (JSON *self) CODE: SvREFCNT_dec (self->cb_sk_object); SvREFCNT_dec (self->cb_object); SvREFCNT_dec (self->cb_sort_by); SvREFCNT_dec (self->incr_text); PROTOTYPES: ENABLE void encode_json (SV *scalar) ALIAS: _to_json = 0 encode_json = F_UTF8 PPCODE: { JSON json; json_init (&json); json.flags |= ix; PUTBACK; scalar = encode_json (aTHX_ scalar, &json); SPAGAIN; XPUSHs (scalar); } void decode_json (SV *jsonstr, SV *allow_nonref = NULL) ALIAS: _from_json = 0 decode_json = F_UTF8 PPCODE: { JSON json; json_init (&json); json.flags |= ix; if (ix && allow_nonref) json.flags |= F_ALLOW_NONREF; PUTBACK; jsonstr = decode_json (aTHX_ jsonstr, &json, 0); SPAGAIN; XPUSHs (jsonstr); }