1#!perl -w
2
3use strict;
4use warnings;
5
6use Test::More tests => 13;
7
8use File::Temp 'tempfile';
9
10{
11
12    package LenDigest;
13    require Digest::base;
14    our @ISA = qw(Digest::base);
15
16    sub new {
17        my $class = shift;
18        my $str   = "";
19        bless \$str, $class;
20    }
21
22    sub add {
23        my $self = shift;
24        $$self .= join( "", @_ );
25        return $self;
26    }
27
28    sub digest {
29        my $self  = shift;
30        my $len   = length($$self);
31        my $first = ( $len > 0 ) ? substr( $$self, 0, 1 ) : "X";
32        $$self = "";
33        return sprintf "$first%04d", $len;
34    }
35}
36
37my $ctx = LenDigest->new;
38is( $ctx->digest, "X0000" );
39
40my $EBCDIC = ord('A') == 193;
41
42if ($EBCDIC) {
43    is( $ctx->hexdigest,            "e7f0f0f0f0" );
44    is( $ctx->b64digest,            "5/Dw8PA" );
45    is( $ctx->base64_padded_digest, "5/Dw8PA=" );
46}
47else {
48    is( $ctx->hexdigest,            "5830303030" );
49    is( $ctx->b64digest,            "WDAwMDA" );
50    is( $ctx->base64_padded_digest, "WDAwMDA=" );
51}
52
53$ctx->add("foo");
54is( $ctx->digest, "f0003" );
55
56$ctx->add("foo");
57is( $ctx->hexdigest, $EBCDIC ? "86f0f0f0f3" : "6630303033" );
58
59$ctx->add("foo");
60is( $ctx->b64digest, $EBCDIC ? "hvDw8PM" : "ZjAwMDM" );
61
62{
63    my ( $fh, $tempfile ) = tempfile( UNLINK => 1 );
64    binmode($fh);
65    print $fh "abc" x 100, "\n";
66    close($fh) || die;
67
68    open( my $fh2, $tempfile ) || die;
69    $ctx->addfile($fh2);
70    close($fh2);
71
72    is( $ctx->digest, "a0301" );
73}
74
75eval { $ctx->add_bits("1010"); };
76like( $@, '/^Number of bits must be multiple of 8/' );
77
78$ctx->add_bits( $EBCDIC ? "11100100" : "01010101" );
79is( $ctx->digest, "U0001" );
80
81eval { $ctx->add_bits( "abc", 12 ); };
82like( $@, '/^Number of bits must be multiple of 8/' );
83
84$ctx->add_bits( "abc", 16 );
85is( $ctx->digest, "a0002" );
86
87$ctx->add_bits( "abc", 32 );
88is( $ctx->digest, "a0003" );
89