]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/Eml.pm
eml: fix leak workaround
[public-inbox.git] / lib / PublicInbox / Eml.pm
index 955d6a96a51c12b549478145afd45491dd5c9e25..3c681ba5bc2eb6efc6b0252b67a26ebd2f3b6904 100644 (file)
@@ -28,7 +28,7 @@ package PublicInbox::Eml;
 use strict;
 use v5.10.1;
 use Carp qw(croak);
-use Encode qw(find_encoding decode encode); # stdlib
+use Encode qw(find_encoding); # stdlib
 use Text::Wrap qw(wrap); # stdlib, we need Perl 5.6+ for $huge
 use MIME::Base64 3.05; # Perl 5.10.0 / 5.9.2
 use MIME::QuotedPrint 3.05; # ditto
@@ -333,10 +333,18 @@ sub body_set {
 }
 
 sub body_str_set {
-       my ($self, $body_str) = @_;
-       my $charset = ct($self)->{attributes}->{charset} or
+       my ($self, $str) = @_;
+       my $cs = ct($self)->{attributes}->{charset} //
                croak('body_str was given, but no charset is defined');
-       body_set($self, \(encode($charset, $body_str, Encode::FB_CROAK)));
+       my $enc = find_encoding($cs) // croak "unknown encoding `$cs'";
+       my $tmp;
+       {
+               my @w;
+               local $SIG{__WARN__} = sub { push @w, @_ };
+               $tmp = $enc->encode($str, Encode::FB_WARN);
+               croak(@w) if @w;
+       };
+       body_set($self, \$tmp);
 }
 
 sub content_type { scalar header($_[0], 'Content-Type') }
@@ -452,15 +460,20 @@ sub body {
 sub body_str {
        my ($self) = @_;
        my $ct = ct($self);
-       my $charset = $ct->{attributes}->{charset};
-       if (!$charset) {
-               if ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) {
+       my $cs = $ct->{attributes}->{charset} // do {
+               ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) and
                        return body($self);
-               }
                croak("can't get body as a string for ",
                        join("\n\t", header_raw($self, 'Content-Type')));
-       }
-       decode($charset, body($self), Encode::FB_CROAK);
+       };
+       my $enc = find_encoding($cs) or croak "unknown encoding `$cs'";
+       my $tmp = body($self);
+       # workaround https://rt.cpan.org/Public/Bug/Display.html?id=139622
+       my @w;
+       local $SIG{__WARN__} = sub { push @w, @_ };
+       my $ret = $enc->decode($tmp, Encode::FB_WARN);
+       croak(@w) if @w;
+       $ret;
 }
 
 sub as_string {
@@ -480,6 +493,14 @@ sub charset_set {
 
 sub crlf { $_[0]->{crlf} // "\n" }
 
+sub raw_size {
+       my ($self) = @_;
+       my $len = length(${$self->{hdr}});
+       defined($self->{bdy}) and
+               $len += length(${$self->{bdy}}) + length($self->{crlf});
+       $len;
+}
+
 # warnings to ignore when handling spam mailboxes and maybe other places
 sub warn_ignore {
        my $s = "@_";