fix a test failing under -Dmad
[p5sagit/p5-mst-13.2.git] / ext / IO / Compress / Base / lib / IO / Compress / Base / Common.pm
CommitLineData
25f0751f 1package IO::Compress::Base::Common;
2
3use strict ;
4use warnings;
5use bytes;
6
7use Carp;
8use Scalar::Util qw(blessed readonly);
9use File::GlobMapper;
10
11require Exporter;
12our ($VERSION, @ISA, @EXPORT, %EXPORT_TAGS);
13@ISA = qw(Exporter);
63ad731d 14$VERSION = '2.001';
25f0751f 15
16@EXPORT = qw( isaFilehandle isaFilename whatIsInput whatIsOutput
17 isaFileGlobString cleanFileGlobString oneTarget
18 setBinModeInput setBinModeOutput
19 ckInOutParams
20 createSelfTiedObject
21
22 WANT_CODE
23 WANT_EXT
24 WANT_UNDEF
25 WANT_HASH
26
27 STATUS_OK
28 STATUS_ENDSTREAM
29 STATUS_EOF
30 STATUS_ERROR
31 );
32
33%EXPORT_TAGS = ( Status => [qw( STATUS_OK
34 STATUS_ENDSTREAM
35 STATUS_EOF
36 STATUS_ERROR
37 )]);
38
39
40use constant STATUS_OK => 0;
41use constant STATUS_ENDSTREAM => 1;
42use constant STATUS_EOF => 2;
43use constant STATUS_ERROR => -1;
44#use constant STATUS_OK => 0;
45#use constant STATUS_ENDSTREAM => 1;
46#use constant STATUS_ERROR => 2;
47#use constant STATUS_EOF => 3;
48
49our ($needBinmode);
50$needBinmode = ($^O eq 'MSWin32' ||
51 ($] >= 5.006 && eval ' ${^UNICODE} || ${^UTF8LOCALE} '))
52 ? 1 : 1 ;
53
54sub setBinModeInput($)
55{
56 my $handle = shift ;
57
58 binmode $handle
59 if $needBinmode;
60}
61
62sub setBinModeOutput($)
63{
64 my $handle = shift ;
65
66 binmode $handle
67 if $needBinmode;
68}
69
70sub isaFilehandle($)
71{
72 use utf8; # Pragma needed to keep Perl 5.6.0 happy
73 return (defined $_[0] and
74 (UNIVERSAL::isa($_[0],'GLOB') or UNIVERSAL::isa(\$_[0],'GLOB'))
75 and defined fileno($_[0]) )
76}
77
78sub isaFilename($)
79{
80 return (defined $_[0] and
81 ! ref $_[0] and
82 UNIVERSAL::isa(\$_[0], 'SCALAR'));
83}
84
85sub isaFileGlobString
86{
87 return defined $_[0] && $_[0] =~ /^<.*>$/;
88}
89
90sub cleanFileGlobString
91{
92 my $string = shift ;
93
94 $string =~ s/^\s*<\s*(.*)\s*>\s*$/$1/;
95
96 return $string;
97}
98
99use constant WANT_CODE => 1 ;
100use constant WANT_EXT => 2 ;
101use constant WANT_UNDEF => 4 ;
102#use constant WANT_HASH => 8 ;
103use constant WANT_HASH => 0 ;
104
105sub whatIsInput($;$)
106{
107 my $got = whatIs(@_);
108
109 if (defined $got && $got eq 'filename' && defined $_[0] && $_[0] eq '-')
110 {
4ebc85a4 111 #use IO::File;
25f0751f 112 $got = 'handle';
4ebc85a4 113 $_[0] = *STDIN;
114 #$_[0] = new IO::File("<-");
25f0751f 115 }
116
117 return $got;
118}
119
120sub whatIsOutput($;$)
121{
122 my $got = whatIs(@_);
123
124 if (defined $got && $got eq 'filename' && defined $_[0] && $_[0] eq '-')
125 {
126 $got = 'handle';
4ebc85a4 127 $_[0] = *STDOUT;
128 #$_[0] = new IO::File(">-");
25f0751f 129 }
130
131 return $got;
132}
133
134sub whatIs ($;$)
135{
136 return 'handle' if isaFilehandle($_[0]);
137
138 my $wantCode = defined $_[1] && $_[1] & WANT_CODE ;
139 my $extended = defined $_[1] && $_[1] & WANT_EXT ;
140 my $undef = defined $_[1] && $_[1] & WANT_UNDEF ;
141 my $hash = defined $_[1] && $_[1] & WANT_HASH ;
142
143 return 'undef' if ! defined $_[0] && $undef ;
144
145 if (ref $_[0]) {
146 return '' if blessed($_[0]); # is an object
147 #return '' if UNIVERSAL::isa($_[0], 'UNIVERSAL'); # is an object
148 return 'buffer' if UNIVERSAL::isa($_[0], 'SCALAR');
149 return 'array' if UNIVERSAL::isa($_[0], 'ARRAY') && $extended ;
150 return 'hash' if UNIVERSAL::isa($_[0], 'HASH') && $hash ;
151 return 'code' if UNIVERSAL::isa($_[0], 'CODE') && $wantCode ;
152 return '';
153 }
154
155 return 'fileglob' if $extended && isaFileGlobString($_[0]);
156 return 'filename';
157}
158
159sub oneTarget
160{
161 return $_[0] =~ /^(code|handle|buffer|filename)$/;
162}
163
164sub Validator::new
165{
166 my $class = shift ;
167
168 my $Class = shift ;
169 my $error_ref = shift ;
170 my $reportClass = shift ;
171
172 my %data = (Class => $Class,
173 Error => $error_ref,
174 reportClass => $reportClass,
175 ) ;
176
177 my $obj = bless \%data, $class ;
178
179 local $Carp::CarpLevel = 1;
180
181 my $inType = $data{inType} = whatIsInput($_[0], WANT_EXT|WANT_HASH);
182 my $outType = $data{outType} = whatIsOutput($_[1], WANT_EXT|WANT_HASH);
183
184 my $oneInput = $data{oneInput} = oneTarget($inType);
185 my $oneOutput = $data{oneOutput} = oneTarget($outType);
186
187 if (! $inType)
188 {
189 $obj->croakError("$reportClass: illegal input parameter") ;
190 #return undef ;
191 }
192
193# if ($inType eq 'hash')
194# {
195# $obj->{Hash} = 1 ;
196# $obj->{oneInput} = 1 ;
197# return $obj->validateHash($_[0]);
198# }
199
200 if (! $outType)
201 {
202 $obj->croakError("$reportClass: illegal output parameter") ;
203 #return undef ;
204 }
205
206
207 if ($inType ne 'fileglob' && $outType eq 'fileglob')
208 {
209 $obj->croakError("Need input fileglob for outout fileglob");
210 }
211
212# if ($inType ne 'fileglob' && $outType eq 'hash' && $inType ne 'filename' )
213# {
214# $obj->croakError("input must ne filename or fileglob when output is a hash");
215# }
216
217 if ($inType eq 'fileglob' && $outType eq 'fileglob')
218 {
219 $data{GlobMap} = 1 ;
220 $data{inType} = $data{outType} = 'filename';
221 my $mapper = new File::GlobMapper($_[0], $_[1]);
222 if ( ! $mapper )
223 {
224 return $obj->saveErrorString($File::GlobMapper::Error) ;
225 }
226 $data{Pairs} = $mapper->getFileMap();
227
228 return $obj;
229 }
230
231 $obj->croakError("$reportClass: input and output $inType are identical")
232 if $inType eq $outType && $_[0] eq $_[1] && $_[0] ne '-' ;
233
234 if ($inType eq 'fileglob') # && $outType ne 'fileglob'
235 {
236 my $glob = cleanFileGlobString($_[0]);
237 my @inputs = glob($glob);
238
239 if (@inputs == 0)
240 {
241 # TODO -- legal or die?
242 die "globmap matched zero file -- legal or die???" ;
243 }
244 elsif (@inputs == 1)
245 {
246 $obj->validateInputFilenames($inputs[0])
247 or return undef;
248 $_[0] = $inputs[0] ;
249 $data{inType} = 'filename' ;
250 $data{oneInput} = 1;
251 }
252 else
253 {
254 $obj->validateInputFilenames(@inputs)
255 or return undef;
256 $_[0] = [ @inputs ] ;
257 $data{inType} = 'filenames' ;
258 }
259 }
260 elsif ($inType eq 'filename')
261 {
262 $obj->validateInputFilenames($_[0])
263 or return undef;
264 }
265 elsif ($inType eq 'array')
266 {
267 $data{inType} = 'filenames' ;
268 $obj->validateInputArray($_[0])
269 or return undef ;
270 }
271
272 return $obj->saveErrorString("$reportClass: output buffer is read-only")
273 if $outType eq 'buffer' && readonly(${ $_[1] });
274
275 if ($outType eq 'filename' )
276 {
277 $obj->croakError("$reportClass: output filename is undef or null string")
278 if ! defined $_[1] || $_[1] eq '' ;
e7d45986 279
280 if (-e $_[1])
281 {
282 if (-d _ )
283 {
284 return $obj->saveErrorString("output file '$_[1]' is a directory");
285 }
286 }
25f0751f 287 }
288
289 return $obj ;
290}
291
292sub Validator::saveErrorString
293{
294 my $self = shift ;
295 ${ $self->{Error} } = shift ;
296 return undef;
297
298}
299
300sub Validator::croakError
301{
302 my $self = shift ;
303 $self->saveErrorString($_[0]);
304 croak $_[0];
305}
306
307
308
309sub Validator::validateInputFilenames
310{
311 my $self = shift ;
312
313 foreach my $filename (@_)
314 {
315 $self->croakError("$self->{reportClass}: input filename is undef or null string")
316 if ! defined $filename || $filename eq '' ;
317
318 next if $filename eq '-';
319
320 if (! -e $filename )
321 {
322 return $self->saveErrorString("input file '$filename' does not exist");
323 }
324
e7d45986 325 if (-d _ )
326 {
327 return $self->saveErrorString("input file '$filename' is a directory");
328 }
329
330 if (! -r _ )
25f0751f 331 {
332 return $self->saveErrorString("cannot open file '$filename': $!");
333 }
334 }
335
336 return 1 ;
337}
338
339sub Validator::validateInputArray
340{
341 my $self = shift ;
342
343 if ( @{ $_[0] } == 0 )
344 {
345 return $self->saveErrorString("empty array reference") ;
346 }
347
348 foreach my $element ( @{ $_[0] } )
349 {
350 my $inType = whatIsInput($element);
351
352 if (! $inType)
353 {
354 $self->croakError("unknown input parameter") ;
355 }
356 elsif($inType eq 'filename')
357 {
358 $self->validateInputFilenames($element)
359 or return undef ;
360 }
361 else
362 {
363 $self->croakError("not a filename") ;
364 }
365 }
366
367 return 1 ;
368}
369
370#sub Validator::validateHash
371#{
372# my $self = shift ;
373# my $href = shift ;
374#
375# while (my($k, $v) = each %$href)
376# {
377# my $ktype = whatIsInput($k);
378# my $vtype = whatIsOutput($v, WANT_EXT|WANT_UNDEF) ;
379#
380# if ($ktype ne 'filename')
381# {
382# return $self->saveErrorString("hash key not filename") ;
383# }
384#
385# my %valid = map { $_ => 1 } qw(filename buffer array undef handle) ;
386# if (! $valid{$vtype})
387# {
388# return $self->saveErrorString("hash value not ok") ;
389# }
390# }
391#
392# return $self ;
393#}
394
395sub createSelfTiedObject
396{
397 my $class = shift || (caller)[0] ;
398 my $error_ref = shift ;
399
400 my $obj = bless Symbol::gensym(), ref($class) || $class;
401 tie *$obj, $obj if $] >= 5.005;
402 *$obj->{Closed} = 1 ;
403 $$error_ref = '';
404 *$obj->{Error} = $error_ref ;
405 my $errno = 0 ;
406 *$obj->{ErrorNo} = \$errno ;
407
408 return $obj;
409}
410
411
412
413#package Parse::Parameters ;
414#
415#
416#require Exporter;
417#our ($VERSION, @ISA, @EXPORT);
418#$VERSION = '2.000_08';
419#@ISA = qw(Exporter);
420
421$EXPORT_TAGS{Parse} = [qw( ParseParameters
422 Parse_any Parse_unsigned Parse_signed
423 Parse_boolean Parse_custom Parse_string
258133d1 424 Parse_multiple Parse_writable_scalar
25f0751f 425 )
426 ];
427
428push @EXPORT, @{ $EXPORT_TAGS{Parse} } ;
429
430use constant Parse_any => 0x01;
431use constant Parse_unsigned => 0x02;
432use constant Parse_signed => 0x04;
433use constant Parse_boolean => 0x08;
434use constant Parse_string => 0x10;
435use constant Parse_custom => 0x12;
436
258133d1 437#use constant Parse_store_ref => 0x100 ;
438use constant Parse_multiple => 0x100 ;
439use constant Parse_writable => 0x200 ;
440use constant Parse_writable_scalar => 0x400 | Parse_writable ;
25f0751f 441
442use constant OFF_PARSED => 0 ;
443use constant OFF_TYPE => 1 ;
444use constant OFF_DEFAULT => 2 ;
445use constant OFF_FIXED => 3 ;
446use constant OFF_FIRST_ONLY => 4 ;
447use constant OFF_STICKY => 5 ;
448
449
450
451sub ParseParameters
452{
453 my $level = shift || 0 ;
454
455 my $sub = (caller($level + 1))[3] ;
456 local $Carp::CarpLevel = 1 ;
457 my $p = new IO::Compress::Base::Parameters() ;
458 $p->parse(@_)
459 or croak "$sub: $p->{Error}" ;
460
461 return $p;
462}
463
464#package IO::Compress::Base::Parameters;
465
466use strict;
467use warnings;
468use Carp;
469
470sub IO::Compress::Base::Parameters::new
471{
472 my $class = shift ;
473
474 my $obj = { Error => '',
475 Got => {},
476 } ;
477
478 #return bless $obj, ref($class) || $class || __PACKAGE__ ;
479 return bless $obj, 'IO::Compress::Base::Parameters' ;
480}
481
482sub IO::Compress::Base::Parameters::setError
483{
484 my $self = shift ;
485 my $error = shift ;
486 my $retval = @_ ? shift : undef ;
487
488 $self->{Error} = $error ;
489 return $retval;
490}
491
492#sub getError
493#{
494# my $self = shift ;
495# return $self->{Error} ;
496#}
497
498sub IO::Compress::Base::Parameters::parse
499{
500 my $self = shift ;
501
502 my $default = shift ;
503
504 my $got = $self->{Got} ;
505 my $firstTime = keys %{ $got } == 0 ;
506
507 my (@Bad) ;
508 my @entered = () ;
509
510 # Allow the options to be passed as a hash reference or
511 # as the complete hash.
512 if (@_ == 0) {
513 @entered = () ;
514 }
515 elsif (@_ == 1) {
516 my $href = $_[0] ;
517 return $self->setError("Expected even number of parameters, got 1")
518 if ! defined $href or ! ref $href or ref $href ne "HASH" ;
519
520 foreach my $key (keys %$href) {
521 push @entered, $key ;
522 push @entered, \$href->{$key} ;
523 }
524 }
525 else {
526 my $count = @_;
527 return $self->setError("Expected even number of parameters, got $count")
528 if $count % 2 != 0 ;
529
530 for my $i (0.. $count / 2 - 1) {
531 push @entered, $_[2* $i] ;
532 push @entered, \$_[2* $i+1] ;
533 }
534 }
535
536
537 while (my ($key, $v) = each %$default)
538 {
539 croak "need 4 params [@$v]"
540 if @$v != 4 ;
541
542 my ($first_only, $sticky, $type, $value) = @$v ;
543 my $x ;
544 $self->_checkType($key, \$value, $type, 0, \$x)
545 or return undef ;
546
547 $key = lc $key;
548
549 if ($firstTime || ! $sticky) {
258133d1 550 $x = [ $x ]
551 if $type & Parse_multiple;
552
25f0751f 553 $got->{$key} = [0, $type, $value, $x, $first_only, $sticky] ;
554 }
555
556 $got->{$key}[OFF_PARSED] = 0 ;
557 }
558
258133d1 559 my %parsed = ();
25f0751f 560 for my $i (0.. @entered / 2 - 1) {
561 my $key = $entered[2* $i] ;
562 my $value = $entered[2* $i+1] ;
563
564 #print "Key [$key] Value [$value]" ;
565 #print defined $$value ? "[$$value]\n" : "[undef]\n";
566
567 $key =~ s/^-// ;
568 my $canonkey = lc $key;
569
570 if ($got->{$canonkey} && ($firstTime ||
571 ! $got->{$canonkey}[OFF_FIRST_ONLY] ))
572 {
573 my $type = $got->{$canonkey}[OFF_TYPE] ;
258133d1 574 my $parsed = $parsed{$canonkey};
575 ++ $parsed{$canonkey};
576
577 return $self->setError("Muliple instances of '$key' found")
578 if $parsed && $type & Parse_multiple == 0 ;
579
25f0751f 580 my $s ;
581 $self->_checkType($key, $value, $type, 1, \$s)
582 or return undef ;
258133d1 583
25f0751f 584 $value = $$value ;
258133d1 585 if ($type & Parse_multiple) {
586 $got->{$canonkey}[OFF_PARSED] = 1;
587 push @{ $got->{$canonkey}[OFF_FIXED] }, $s ;
588 }
589 else {
590 $got->{$canonkey} = [1, $type, $value, $s] ;
591 }
25f0751f 592 }
593 else
594 { push (@Bad, $key) }
595 }
596
597 if (@Bad) {
598 my ($bad) = join(", ", @Bad) ;
599 return $self->setError("unknown key value(s) @Bad") ;
600 }
601
602 return 1;
603}
604
605sub IO::Compress::Base::Parameters::_checkType
606{
607 my $self = shift ;
608
609 my $key = shift ;
610 my $value = shift ;
611 my $type = shift ;
612 my $validate = shift ;
613 my $output = shift;
614
615 #local $Carp::CarpLevel = $level ;
616 #print "PARSE $type $key $value $validate $sub\n" ;
258133d1 617
618 if ($type & Parse_writable_scalar)
25f0751f 619 {
258133d1 620 return $self->setError("Parameter '$key' not writable")
621 if $validate && readonly $$value ;
622
623 if (ref $$value)
624 {
625 return $self->setError("Parameter '$key' not a scalar reference")
626 if $validate && ref $$value ne 'SCALAR' ;
627
628 $$output = $$value ;
629 }
630 else
631 {
632 return $self->setError("Parameter '$key' not a scalar")
633 if $validate && ref $value ne 'SCALAR' ;
634
635 $$output = $value ;
636 }
25f0751f 637
25f0751f 638 return 1;
639 }
640
258133d1 641# if ($type & Parse_store_ref)
642# {
643# #$value = $$value
644# # if ref ${ $value } ;
645#
646# $$output = $value ;
647# return 1;
648# }
649
25f0751f 650 $value = $$value ;
651
652 if ($type & Parse_any)
653 {
654 $$output = $value ;
655 return 1;
656 }
657 elsif ($type & Parse_unsigned)
658 {
659 return $self->setError("Parameter '$key' must be an unsigned int, got 'undef'")
660 if $validate && ! defined $value ;
661 return $self->setError("Parameter '$key' must be an unsigned int, got '$value'")
662 if $validate && $value !~ /^\d+$/;
663
664 $$output = defined $value ? $value : 0 ;
665 return 1;
666 }
667 elsif ($type & Parse_signed)
668 {
669 return $self->setError("Parameter '$key' must be a signed int, got 'undef'")
670 if $validate && ! defined $value ;
671 return $self->setError("Parameter '$key' must be a signed int, got '$value'")
672 if $validate && $value !~ /^-?\d+$/;
673
674 $$output = defined $value ? $value : 0 ;
675 return 1 ;
676 }
677 elsif ($type & Parse_boolean)
678 {
679 return $self->setError("Parameter '$key' must be an int, got '$value'")
680 if $validate && defined $value && $value !~ /^\d*$/;
681 $$output = defined $value ? $value != 0 : 0 ;
682 return 1;
683 }
684 elsif ($type & Parse_string)
685 {
686 $$output = defined $value ? $value : "" ;
687 return 1;
688 }
689
690 $$output = $value ;
691 return 1;
692}
693
694
695
696sub IO::Compress::Base::Parameters::parsed
697{
698 my $self = shift ;
699 my $name = shift ;
700
701 return $self->{Got}{lc $name}[OFF_PARSED] ;
702}
703
704sub IO::Compress::Base::Parameters::value
705{
706 my $self = shift ;
707 my $name = shift ;
708
709 if (@_)
710 {
711 $self->{Got}{lc $name}[OFF_PARSED] = 1;
712 $self->{Got}{lc $name}[OFF_DEFAULT] = $_[0] ;
713 $self->{Got}{lc $name}[OFF_FIXED] = $_[0] ;
714 }
715
716 return $self->{Got}{lc $name}[OFF_FIXED] ;
717}
718
719sub IO::Compress::Base::Parameters::valueOrDefault
720{
721 my $self = shift ;
722 my $name = shift ;
723 my $default = shift ;
724
725 my $value = $self->{Got}{lc $name}[OFF_DEFAULT] ;
726
727 return $value if defined $value ;
728 return $default ;
729}
730
731sub IO::Compress::Base::Parameters::wantValue
732{
733 my $self = shift ;
734 my $name = shift ;
735
736 return defined $self->{Got}{lc $name}[OFF_DEFAULT] ;
737
738}
739
740sub IO::Compress::Base::Parameters::clone
741{
742 my $self = shift ;
743 my $obj = { };
744 my %got ;
745
746 while (my ($k, $v) = each %{ $self->{Got} }) {
747 $got{$k} = [ @$v ];
748 }
749
750 $obj->{Error} = $self->{Error};
751 $obj->{Got} = \%got ;
752
753 return bless $obj, 'IO::Compress::Base::Parameters' ;
754}
755
e7d45986 756package U64;
757
758use constant MAX32 => 0xFFFFFFFF ;
759use constant LOW => 0 ;
760use constant HIGH => 1;
761
762sub new
763{
764 my $class = shift ;
765
766 my $high = 0 ;
767 my $low = 0 ;
768
769 if (@_ == 2) {
770 $high = shift ;
771 $low = shift ;
772 }
773 elsif (@_ == 1) {
774 $low = shift ;
775 }
776
777 bless [$low, $high], $class;
778}
779
780sub newUnpack_V64
781{
782 my $string = shift;
783
784 my ($low, $hi) = unpack "V V", $string ;
785 bless [ $low, $hi ], "U64";
786}
787
788sub newUnpack_V32
789{
790 my $string = shift;
791
792 my $low = unpack "V", $string ;
793 bless [ $low, 0 ], "U64";
794}
795
796sub reset
797{
798 my $self = shift;
799 $self->[HIGH] = $self->[LOW] = 0;
800}
801
802sub clone
803{
804 my $self = shift;
805 bless [ @$self ], ref $self ;
806}
807
808sub getHigh
809{
810 my $self = shift;
811 return $self->[HIGH];
812}
813
814sub getLow
815{
816 my $self = shift;
817 return $self->[LOW];
818}
819
820sub get32bit
821{
822 my $self = shift;
823 return $self->[LOW];
824}
825
826sub add
827{
828 my $self = shift;
829 my $value = shift;
830
831 if (ref $value eq 'U64') {
832 $self->[HIGH] += $value->[HIGH] ;
833 $value = $value->[LOW];
834 }
835
836 my $available = MAX32 - $self->[LOW] ;
837
838 if ($value > $available) {
839 ++ $self->[HIGH] ;
840 $self->[LOW] = $value - $available - 1;
841 }
842 else {
843 $self->[LOW] += $value ;
844 }
845}
846
847sub equal
848{
849 my $self = shift;
850 my $other = shift;
851
852 return $self->[LOW] == $other->[LOW] &&
853 $self->[HIGH] == $other->[HIGH] ;
854}
855
856sub getPacked_V64
857{
858 my $self = shift;
859
860 return pack "V V", @$self ;
861}
862
863sub getPacked_V32
864{
865 my $self = shift;
866
867 return pack "V", $self->[LOW] ;
868}
869
870sub pack_V64
871{
872 my $low = shift;
873
874 return pack "V V", $low, 0;
875}
876
877
25f0751f 878package IO::Compress::Base::Common;
879
8801;