Last active
December 10, 2015 01:58
-
-
Save gerdr/4363369 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
my @CHARS = '0'..'9', 'a'..'z', 'A'..'Z'; | |
my %MAP = @CHARS.pairs.map(*.invert); | |
sub encode($string as Str, :$escape = '_', *@skip) { | |
my multi encode-char($_ where any(@CHARS, @skip)) { $_ } | |
my multi encode-char($_) { | |
my $cp = .ord; | |
$escape, reverse gather for ^4 { | |
NEXT $cp div= 62; | |
take @CHARS[$cp % 62]; | |
} | |
} | |
$string.comb.map(&encode-char).join | |
} | |
sub decode($string as Str, :$escape = '_') { | |
my sub decode-char($_) { | |
chr [+] .comb[$escape.chars..*].kv.map: { | |
%MAP{$^v} * 62**(3 - $^k) | |
} | |
} | |
$string.subst(:g, / $escape <[0..9a..zA..Z]> ** 4 /, &decode-char) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment