485657b4f9a9baba4b925e94a07950018bae2022
[debian/amanda] / perl / Amanda / BigIntCompat.pm
1 # Copyright (c) 2005-2008 Zmanda, Inc.  All Rights Reserved.
2
3 # This library is free software; you can redistribute it and/or modify it
4 # under the terms of the GNU Lesser General Public License version 2.1 as 
5 # published by the Free Software Foundation.
6
7 # This library is distributed in the hope that it will be useful, but
8 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
9 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
10 # License for more details.
11
12 # You should have received a copy of the GNU Lesser General Public License
13 # along with this library; if not, write to the Free Software Foundation,
14 # Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA.
15
16 # Contact information: Zmanda Inc., 465 S Mathlida Ave, Suite 300
17 # Sunnyvale, CA 94086, USA, or: http://www.zmanda.com
18
19 package Amanda::BigIntCompat;
20
21 use strict;
22 use warnings;
23 use overload;
24 use Math::BigInt;
25
26 =head1 NAME
27
28 Amanda::BigIntCompat -- make C<Math::BigInt> behave consistently
29
30 =head1 SYNOPSIS
31
32   use Amanda::BigIntCompat;
33   use Math::BigInt;
34
35   my $bn = Math::BigInt->new(1);
36   print "okay\n" if $bn eq "1";
37
38 =head1 API STATUS
39
40 Stable
41
42 =head1 INTERFACE
43
44 This module will modify C<Math::BigInt> to hide inconsistent behaviors across
45 Perl versions. Spefically, it handles the following.
46
47 =over
48
49 =item stringification
50
51 Older versions of C<Math::BigInt>, like the one shipped with Perl 5.6.1,
52 stringify positive numbers with a leading C<+> (e.g. C<+1> instead of C<1>).
53
54 =back
55
56 =cut
57
58 my $test_num = Math::BigInt->new(1);
59 our $stringify = overload::Method($test_num, '""');
60
61 if ($test_num =~ /^\+/) {
62     eval <<'EVAL';
63         package Math::BigInt;
64         use overload 'eq' => sub {
65             my ($self, $other) = @_;
66             return "$self" eq "$other";
67         };
68
69         # stringify is already overloaded; seems to be no good way to
70         # re-overload it without triggering a warning
71         no warnings 'redefine';
72         sub stringify {
73             my $str = $Amanda::BigIntCompat::stringify->(@_);
74             $str =~ s/^\+//;
75             return $str;
76         }
77 EVAL
78     die $@ if $@;
79 }
80
81 # the "sign" method does not exist in older versions, either, but is used
82 # by bigint2uint64().
83 if (!$test_num->can("sign")) {
84     eval <<'EVAL';
85         package Math::BigInt;
86         sub sign { ($_[0] =~ /^-/)? "-" : "+"; }
87 EVAL
88     die $@ if $@;
89 }
90
91 # similarly for bstr
92 if (!$test_num->can("bstr")) {
93     eval <<'EVAL';
94         package Math::BigInt;
95         sub bstr { "$_[0]"; }
96 EVAL
97     die $@ if $@;
98 }
99 1;