From: Matt S Trout Date: Wed, 22 May 2013 17:21:56 +0000 (+0000) Subject: Initial import of JSON::MaybeXS X-Git-Tag: v1.000000~7 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=3be1e192d881621dc1bd90747ae94d5862746f82;p=p5sagit%2FJSON-MaybeXS.git Initial import of JSON::MaybeXS --- 3be1e192d881621dc1bd90747ae94d5862746f82 diff --git a/lib/JSON/MaybeXS.pm b/lib/JSON/MaybeXS.pm new file mode 100644 index 0000000..3e4f1b3 --- /dev/null +++ b/lib/JSON/MaybeXS.pm @@ -0,0 +1,32 @@ +package JSON::MaybeXS; + +use strict; +use warnings FATAL => 'all'; +use base qw(Exporter); + +BEGIN { + our $JSON_Class; + + our @err; + + if (eval { require Cpanel::JSON::XS; 1; }) { + $JSON_Class = 'Cpanel::JSON::XS'; + } else { + push @err, "Error loading Cpanel::JSON::XS: $@"; + if (eval { require JSON::PP; 1; }) { + $JSON_Class = 'JSON::PP'; + } else { + push @err, "Error loading JSON::PP: $@"; + } + } + unless ($JSON_Class) { + die join("\n", "Couldn't load a JSON module:", @err); + } + $JSON_Class->import(qw(encode_json decode_json)); +} + +our @EXPORT = qw(encode_json decode_json JSON); + +sub JSON () { our $JSON_Class } + +1; diff --git a/t/neither.t b/t/neither.t new file mode 100644 index 0000000..7070daf --- /dev/null +++ b/t/neither.t @@ -0,0 +1,16 @@ +use strict; +use warnings FATAL => 'all'; +use Test::Without::Module 'Cpanel::JSON::XS'; +use Test::Without::Module 'JSON::PP'; +use Test::More; + +ok(!eval { require JSON::MaybeXS; 1 }, 'Class failed to load'); + +# Test::Without::Module always causes 'did not return a true value' errors + +like( + $@, qr{Cpanel/JSON/XS.pm did not.*JSON/PP.pm did not}s, + 'Both errors reported' +); + +done_testing; diff --git a/t/pp.t b/t/pp.t new file mode 100644 index 0000000..b52f27e --- /dev/null +++ b/t/pp.t @@ -0,0 +1,20 @@ +use strict; +use warnings FATAL => 'all'; +use Test::Without::Module 'Cpanel::JSON::XS'; +use if !do { require JSON::PP; 1; }, 'Test::More', skip_all => 'No JSON::PP'; +use Test::More; +use JSON::MaybeXS; + +is(JSON, 'JSON::PP', 'Correct JSON class'); + +is( + \&encode_json, \&JSON::PP::encode_json, + 'Correct encode_json function' +); + +is( + \&decode_json, \&JSON::PP::decode_json, + 'Correct encode_json function' +); + +done_testing; diff --git a/t/xs.t b/t/xs.t new file mode 100644 index 0000000..2c9243a --- /dev/null +++ b/t/xs.t @@ -0,0 +1,19 @@ +use strict; +use warnings FATAL => 'all'; +use if !do { require Cpanel::JSON::XS; 1; }, 'Test::More', skip_all => 'No Cpanel::JSON::XS'; +use Test::More; +use JSON::MaybeXS; + +is(JSON, 'Cpanel::JSON::XS', 'Correct JSON class'); + +is( + \&encode_json, \&Cpanel::JSON::XS::encode_json, + 'Correct encode_json function' +); + +is( + \&decode_json, \&Cpanel::JSON::XS::decode_json, + 'Correct encode_json function' +); + +done_testing;