comment up the array slots
[spider.git] / perl / RingBuf.pm
1 #
2 # Finite size ring buffer creation and access routines
3 #
4 # Copyright (c) - 1998 Dirk Koopman G1TLH
5 #
6 # $Id$
7 #
8
9 use strict;
10
11 package RingBuf;
12
13 use vars qw($VERSION $BRANCH);
14 $VERSION = sprintf( "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/ );
15 $BRANCH = sprintf( "%d.%03d", q$Revision$ =~ /\d+\.\d+\.(\d+)\.(\d+)/  || (0,0));
16 $main::build += $VERSION;
17 $main::branch += $BRANCH;
18
19
20 sub new
21 {
22         my $pkg = shift;
23         my $size = shift;
24
25         # 0 - size
26         # 1 - lth
27         # 2 - end
28         # 3 - start
29         # 4 - pos
30         # 5 - buffer []
31         return bless [$size, 0, 0, 0, 0, []], (ref $pkg || $pkg);
32 }
33
34 sub write
35 {
36         my $self = shift;
37
38         $self->[5]->[$self->[2]++] = shift;
39         $self->[2] = 0 if $self->[2] >= $self->[0];
40         if ($self->[1] < $self->[0]) {
41                 $self->[1] = ++$self->[1];
42         }
43         $self->[2] = $self->[2];
44         if ($self->[1] == $self->[0] && $self->[2] == $self->[3]) {
45                 $self->[3] = $self->[2]+1;
46                 $self->[3] = 0 if $self->[3] >= $self->[0]; 
47         }
48 }
49
50 sub read
51 {
52         my $self = shift;
53         return unless $self->[1];
54         my $r;
55         
56         if ($self->[4] != $self->[2]) {
57                 $r = $self->[5]->[$self->[4]++];
58                 $self->[4] = 0 if $self->[4] >= $self->[0];
59         }
60         return $r;
61 }
62
63 sub rewind
64 {
65         my $self = shift;
66         $self->[4] = $self->[3];
67 }
68
69 sub lth
70 {
71         my $self = shift;
72         return $self->[1];
73 }
74
75 sub readall
76 {
77         my $self = shift;
78         my @out;
79         
80         $self->rewind;
81         while (my $r = $self->read) {
82                 push @out, $r;
83         }
84         return @out;
85 }
86 1;