]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IdxStack.pm
idx_stack: avoid conditional hash assignment weirdness
[public-inbox.git] / lib / PublicInbox / IdxStack.pm
1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # temporary stack for public-inbox-index
5 package PublicInbox::IdxStack;
6 use v5.10.1;
7 use strict;
8 use Fcntl qw(:seek);
9 use constant PACK_FMT => eval { pack('Q', 1) } ? 'A1QQH*H*' : 'A1IIH*H*';
10
11 # start off in write-only mode
12 sub new {
13         open(my $io, '+>', undef) or die "open: $!";
14         # latest_cmt is still useful when the newest revision is a `d'(elete),
15         # otherwise we favor $sync->{latest_cmt} for checkpoints and {quit}
16         bless { wr => $io, latest_cmt => $_[1] }, __PACKAGE__
17 }
18
19 # file_char = [d|m]
20 sub push_rec {
21         my ($self, $file_char, $at, $ct, $blob_oid, $cmt_oid) = @_;
22         my $rec = pack(PACK_FMT, $file_char, $at, $ct, $blob_oid, $cmt_oid);
23         $self->{unpack_fmt} // do {
24                 my $len = length($cmt_oid);
25                 my $fmt = PACK_FMT;
26                 $fmt =~ s/H\*/H$len/g;
27                 $self->{rec_size} = length($rec);
28                 $self->{unpack_fmt} = $fmt;
29         };
30         print { $self->{wr} } $rec or die "print: $!";
31         $self->{tot_size} += length($rec);
32 }
33
34 sub num_records {
35         my ($self) = @_;
36         $self->{rec_size} ? $self->{tot_size} / $self->{rec_size} : 0;
37 }
38
39 # switch into read-only mode and returns self
40 sub read_prepare {
41         my ($self) = @_;
42         my $io = $self->{rd} = delete($self->{wr});
43         $io->flush or die "flush: $!";
44         $self;
45 }
46
47 sub pop_rec {
48         my ($self) = @_;
49         my $sz = $self->{rec_size} or return;
50         my $rec_pos = $self->{tot_size} -= $sz;
51         return if $rec_pos < 0;
52         my $io = $self->{rd};
53         seek($io, $rec_pos, SEEK_SET) or die "seek: $!";
54         my $r = read($io, my $buf, $sz);
55         defined($r) or die "read: $!";
56         $r == $sz or die "read($r != $sz)";
57         unpack($self->{unpack_fmt}, $buf);
58 }
59
60 1;