Skip to content

Commit

Permalink
Tidy up Text::Escape a bit, fix some rough edges
Browse files Browse the repository at this point in the history
(but not all)
  • Loading branch information
Anthony Parsons committed Aug 11, 2011
1 parent 4c5be46 commit 60c1016
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions lib/Text/Escape.pm
Expand Up @@ -2,19 +2,21 @@ use v6;
module Text::Escape; module Text::Escape;


sub escape($str, $how) is export { sub escape($str, $how) is export {
my $m = $how.lc; given $how.lc {
return $str if $m eq 'none'; when 'none' { $str }
return escape_str($str, &escape_html_char) if $m eq 'html'; when 'html' { escape_str($str, &escape_html_char) }
return escape_str($str, &escape_uri_char ) if $m eq 'url' | 'uri'; when 'uri' | 'url' { escape_str($str, &escape_uri_char) }
die "Don't know how to escape format '$how' yet"; default { fail "Don't know how to escape format $how yet" }
}
} }


sub escape_html_char($c) { sub escape_html_char($c) {
my %escapes = ( my %escapes = (
'<' => '&lt;', q{<} => '&lt;',
'>' => '&gt;', q{>} => '&gt;',
'&' => '&amp;', q{&} => '&amp;',
'"' => '&quot;', q{"} => '&quot;',
q{'} => '&#39;',
); );
%escapes{$c} // $c; %escapes{$c} // $c;
} }
Expand All @@ -23,17 +25,18 @@ sub escape_uri_char($c) {
my $allowed = 'abcdefghijklmnopqrstuvwxyz' my $allowed = 'abcdefghijklmnopqrstuvwxyz'
~ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ~ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
~ '0123456789' ~ '0123456789'
~ '-_.!~*\'()'; ~ q{-_.!~*'()};

return $c if defined $allowed.index($c); return $c if defined $allowed.index($c);
# I do not fully assured with thats '+' here,
# mb that is not fully correct put it always on both side # TODO: each char should be UTF-8 encoded, then its bytes %-encoded
return sprintf('+%%%x+', ord($c)); return q{%} ~ ord($c).fmt('%x');
} }


sub escape_str($str, $callback) { sub escape_str($str, $callback) {
my $result = ''; my $result = '';
for 0 .. ($str.chars -1 ) -> $index { for ^$str.chars -> $index {
$result ~= $callback( $str.substr: $index, 1 ); $result ~= $callback($str.substr: $index, 1)
} }
return $result; return $result;
} }
Expand Down

0 comments on commit 60c1016

Please sign in to comment.