source: gs2-extensions/parallel-building/trunk/src/perllib/MIME/Base91.pm@ 27383

Last change on this file since 27383 was 27383, checked in by jmt12, 11 years ago

Adding a perl module for the slightly more efficient Base91 encoding (as compared to Base64 encoding - required by tweaks to ThriftFS to get binary data transport working)

File size: 2.4 KB
Line 
1# Found on CPAN:
2# http://search.cpan.org/~stefanos/MIME-Base91-1.1/Base91.pm
3# In the absence of anything to the contrary, assuming GPL:
4# http://www.cpan.org/misc/cpan-faq.html#How_is_Perl_licensed
5
6package MIME::Base91;
7
8require 5.005_62;
9use strict;
10use warnings;
11
12my @b91_enctab = (
13 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
14 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
15 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
16 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
17 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '#', '$',
18 '%', '&', '(', ')', '*', '+', ',', '.', '/', ':', ';', '<', '=',
19 '>', '?', '@', '[', ']', '^', '_', '`', '{', '|', '}', '~', '"'
20);
21
22my %b91_dectab;
23for (my $i = 0; $i < @b91_enctab; ++$i) {
24 $b91_dectab{$b91_enctab[$i]} = $i;
25}
26
27use vars qw( $VERSION );
28$VERSION = '1.1';
29
30sub import {
31 *encode = \&encode_base91;
32 *decode = \&decode_base91;
33}
34
35sub decode_base91 {
36 my @d = split(//,shift(@_));
37 my $v = -1;
38 my $b = 0;
39 my $n = 0;
40 my $o;
41 my $c;
42
43 for (my $i = 0; $i < @d; ++$i) {
44 $c = $b91_dectab{$d[$i]};
45 if(!defined($c)){
46 next;
47 }
48 if ($v < 0){
49 $v = $c;
50 }else{
51 $v += $c * 91;
52 $b |= ($v << $n);
53 $n += ($v & 8191) > 88 ? 13 : 14;
54 do {
55 $o .= chr($b & 255);
56 $b >>= 8;
57 $n -= 8;
58 } while ($n > 7);
59 $v = -1;
60 }
61 }
62 if($v + 1){
63 $o .= chr(($b | $v << $n) & 255);
64 }
65 return $o;
66}
67
68sub encode_base91 {
69 my @d = split(//,shift(@_));
70 my $b = 0;
71 my $n = 0;
72 my $o;
73 my $v;
74
75 for (my $i = 0; $i < @d; ++$i) {
76 $b |= ord($d[$i]) << $n;
77 $n += 8;
78 if($n > 13){
79 $v = $b & 8191;
80 if ($v > 88){
81 $b >>= 13;
82 $n -= 13;
83 }else{
84 $v = $b & 16383;
85 $b >>= 14;
86 $n -= 14;
87 }
88 $o .= $b91_enctab[$v % 91] . $b91_enctab[$v / 91];
89 }
90 }
91 if($n){
92 $o .= $b91_enctab[$b % 91];
93 if ($n > 7 || $b > 90){
94 $o .= $b91_enctab[$b / 91];
95 }
96 }
97 return $o;
98}
99
1001;
101__END__
102
103=head1 NAME
104
105MIME::Base91 - Base91 encoder / decoder
106
107=head1 SYNOPSIS
108
109 use MIME::Base91;
110
111 $encoded = MIME::Base91::encode($data);
112 $decoded = MIME::Base91::decode($encoded);
113
114=head1 DESCRIPTION
115
116Encode data similar way like MIME::Base64 does.
117
118=head1 EXPORT
119
120NOTHING
121
122=head1 AUTHOR
123
124-
125
126=head1 SEE ALSO
127
128perl(1), MIME::Base64(3pm).
129
130=cut
Note: See TracBrowser for help on using the repository browser.