]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/MsgIter.pm
msg_iter: new internal API for iterating through MIME
[public-inbox.git] / lib / PublicInbox / MsgIter.pm
1 # Copyright (C) 2016 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 package PublicInbox::MsgIter;
5 use strict;
6 use warnings;
7 use base qw(Exporter);
8 our @EXPORT = qw(msg_iter);
9
10 # Like Email::MIME::walk_parts, but this is:
11 # * non-recursive
12 # * passes depth and indices to the iterator callback
13 sub msg_iter ($$) {
14         my ($mime, $cb) = @_;
15         my @parts = $mime->subparts;
16         if (@parts) {
17                 my $i = 0;
18                 @parts = map { [ $_, 1, ++$i ] } @parts;
19                 while (my $p = shift @parts) {
20                         my ($part, $depth, @idx) = @$p;
21                         my @sub = $part->subparts;
22                         if (@sub) {
23                                 $depth++;
24                                 $i = 0;
25                                 @sub = map { [ $_, $depth, @idx, ++$i ] } @sub;
26                                 @parts = (@sub, @parts);
27                         } else {
28                                 $cb->($p);
29                         }
30                 }
31         } else {
32                 $cb->([$mime, 0, 0]);
33         }
34 }
35
36 1;