Skip to content

Instantly share code, notes, and snippets.

@gerdr
Last active December 10, 2015 01:58
Show Gist options
  • Save gerdr/4363369 to your computer and use it in GitHub Desktop.
Save gerdr/4363369 to your computer and use it in GitHub Desktop.
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