]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Hval.pm
huge refactor of encoding handling
[public-inbox.git] / lib / PublicInbox / Hval.pm
1 # Copyright (C) 2014, Eric Wong <normalperson@yhbt.net> and all contributors
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 #
4 # represents a header value in various forms
5 package PublicInbox::Hval;
6 use strict;
7 use warnings;
8 use fields qw(raw);
9 use Encode qw(find_encoding);
10 use CGI qw(escapeHTML);
11 use URI::Escape qw(uri_escape);
12
13 my $enc_ascii = find_encoding('us-ascii');
14
15 sub new {
16         my ($class, $raw) = @_;
17         my $self = fields::new($class);
18
19         # we never care about leading/trailing whitespace
20         $raw =~ s/\A\s*//;
21         $raw =~ s/\s*\z//;
22         $self->{raw} = $raw;
23         $self;
24 }
25
26 sub new_msgid {
27         my ($class, $raw) = @_;
28         $raw =~ s/\A<//;
29         $raw =~ s/>\z//;
30         $class->new($raw);
31 }
32
33 sub new_oneline {
34         my ($class, $raw) = @_;
35         $raw = '' unless defined $raw;
36         $raw =~ tr/\t\n / /s; # squeeze spaces
37         $raw =~ tr/\r//d; # kill CR
38         $class->new($raw);
39 }
40
41 sub ascii_html { $enc_ascii->encode(escapeHTML($_[0]), Encode::HTMLCREF) }
42
43 sub as_html { ascii_html($_[0]->{raw}) }
44 sub as_href { ascii_html(uri_escape($_[0]->{raw})) }
45
46 sub raw {
47         if (defined $_[1]) {
48                 $_[0]->{raw} = $_[1];
49         } else {
50                 $_[0]->{raw};
51         }
52 }
53
54 1;