summaryrefslogtreecommitdiff
path: root/Tanja.pm
diff options
context:
space:
mode:
authorYorhel <git@yorhel.nl>2012-02-18 15:46:46 +0100
committerYorhel <git@yorhel.nl>2012-02-18 15:46:46 +0100
commit9aa87efa574273d88e9f8e9dc870224659f608c9 (patch)
treeafb74e5a71caf37b0ba347f8ef1b3a3d6caff02c /Tanja.pm
parent52aa1ecfa8b4bf8a7217d02e6fb6fbe3801043cb (diff)
Load AnyEvent::Handle and JSON/JSON::XS modules when needed
Diffstat (limited to 'Tanja.pm')
-rw-r--r--Tanja.pm24
1 files changed, 14 insertions, 10 deletions
diff --git a/Tanja.pm b/Tanja.pm
index c3d5094..670c6cd 100644
--- a/Tanja.pm
+++ b/Tanja.pm
@@ -1,13 +1,10 @@
-# TODO: Split into multiple files? (Or at least don't load AnyEvent::Handle and
-# JSON::XS when they aren't needed.)
-
package Tanja;
use strict;
use warnings;
# Just make sure it's loaded. It doesn't export anything.
-use AnyEvent;
+use AnyEvent ();
# Args: [ pattern ], [ tuple ]
@@ -186,8 +183,8 @@ package Tanja::Link;
use strict;
use warnings;
-use AnyEvent::Handle;
use Errno 'EPIPE';
+use Carp 'croak';
# Args: Tanja::Server, $server||!$client, AnyEvent::Handle, $error->($message)
@@ -196,6 +193,8 @@ use Errno 'EPIPE';
# undef.
sub new {
my($own, $serv, $init, $handle, $err) = @_;
+ require AnyEvent::Handle;
+ croak 'No JSON module available.' if !Tanja::Link::JSON->init;
my $s = bless {
serv => $serv,
hdl => $handle,
@@ -327,22 +326,28 @@ sub close {
}
-# JSON serialization format
+# JSON serialization format. Requires either JSON or JSON::XS
package Tanja::Link::JSON;
use strict;
use warnings;
-use JSON::XS;
my @num_to_cmd = ('', qw|register unregister tuple response close|);
my %cmd_to_num = map +($num_to_cmd[$_], $_), keys @num_to_cmd;
+my $json;
+
+sub init {
+ $json = eval { require JSON::XS; JSON::XS->new->utf8 }
+ || eval { require JSON; JSON->new->utf8 };
+ !!$json;
+}
sub anyevent_read_type {
my $cb = $_[1];
sub {
$_[0]{rbuf} =~ s/^([^\012]*)\012// or return;
- my $d = eval { decode_json $1; };
+ my $d = eval { $json->decode($1); };
return $cb->($_[0], undef) || 1 if !$d || ref($d) ne 'ARRAY';
my $num = shift @$d;
return $cb->($_[0], undef) || 1 if !$num || $num !~ /^\d+$/ || $num > @num_to_cmd;
@@ -355,11 +360,10 @@ sub anyevent_read_type {
sub anyevent_write_type {
my(undef, $cmd, @args) = @_;
- encode_json([$cmd_to_num{$cmd}, @args])."\012";
+ $json->encode([$cmd_to_num{$cmd}, @args])."\012";
}
1;
# vim:noet:sw=4:ts=4
-