File: Base58.pm

package info (click to toggle)
libencode-base58-perl 0.01-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 296 kB
  • sloc: perl: 4,075; makefile: 2
file content (101 lines) | stat: -rw-r--r-- 1,782 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package Encode::Base58;

use strict;
use 5.008_001;
our $VERSION = '0.01';

use base qw(Exporter);
our @EXPORT = qw( encode_base58 decode_base58 );

my @alpha = qw(
    1 2 3 4 5 6 7 8 9
    a b c d e f g h i
    j k m n o p q r s
    t u v w x y z A B
    C D E F G H J K L
    M N P Q R S T U V
    W X Y Z
);

my $i = 0;
my %alpha = map { $_ => $i++ } @alpha;

sub encode_base58 {
    my $num = shift;

    return $alpha[0] if $num == 0;

    my $res = '';
    my $base = @alpha;

    while ($num > 0) {
        my $remain = $num % $base;
        $num = int($num / $base);
        $res = $alpha[$remain] . $res;
    }

    return $res;
}

sub decode_base58 {
    my $str = shift;

    my $decoded = 0;
    my $multi   = 1;
    my $base    = @alpha;

    while (length $str > 0) {
        my $digit = chop $str;
        $decoded += $multi * $alpha{$digit};
        $multi   *= $base;
    }

    return $decoded;
}

1;
__END__

=encoding utf-8

=for stopwords
Flickr Flickr's

=for test_synopsis
my $number;

=head1 NAME

Encode::Base58 - Base58 encodings (for Flickr short URI)

=head1 SYNOPSIS

  use Encode::Base58;

  my $short  = encode_base58($number);
  my $number = decode_base58($short);

=head1 DESCRIPTION

Encode::Base58 is a base58 encoder/decoder implementation in
Perl. Base58 encoding is used in shortening ID numbers into a short
string for Flickr's short URL (C<flic.kr>).

=head1 AUTHOR

Tatsuhiko Miyagawa E<lt>miyagawa@bulknews.netE<gt>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=head1 SEE ALSO

L<http://www.flickr.com/groups/api/discuss/72157616713786392/>

L<http://gist.github.com/101753> (in Ruby)

L<http://gist.github.com/101674> (in Objective-C and unit tests)

=cut