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>
4 # temporary stack for public-inbox-index
5 package PublicInbox::IdxStack;
9 use constant PACK_FMT => eval { pack('Q', 1) } ? 'A1QQH*H*' : 'A1IIH*H*';
11 # start off in write-only mode
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__
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);
26 $fmt =~ s/H\*/H$len/g;
27 $self->{rec_size} = length($rec);
28 $self->{unpack_fmt} = $fmt;
30 print { $self->{wr} } $rec or die "print: $!";
31 $self->{tot_size} += length($rec);
36 $self->{rec_size} ? $self->{tot_size} / $self->{rec_size} : 0;
39 # switch into read-only mode and returns self
42 my $io = $self->{rd} = delete($self->{wr});
43 $io->flush or die "flush: $!";
49 my $sz = $self->{rec_size} or return;
50 my $rec_pos = $self->{tot_size} -= $sz;
51 return if $rec_pos < 0;
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);