Prepare for git repository
[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
14 sub new
15 {
16         my $pkg = shift;
17         my $size = shift;
18
19         # 0 - size
20         # 1 - lth
21         # 2 - end
22         # 3 - start
23         # 4 - pos
24         # 5 - buffer []
25         return bless [$size+1, 0, 0, 0, 0, []], (ref $pkg || $pkg);
26 }
27
28 sub write
29 {
30         my $self = shift;
31
32         $self->[5]->[$self->[2]++] = shift;
33         $self->[2] = 0 if $self->[2] >= $self->[0];
34         $self->[1]++ if $self->[1] < $self->[0];
35         if ($self->[1] == $self->[0] && $self->[2] == $self->[3]) {
36                 $self->[3] = $self->[2]+1;
37                 $self->[3] = 0 if $self->[3] >= $self->[0]; 
38         }
39 }
40
41 sub read
42 {
43         my $self = shift;
44         return unless $self->[1];
45         my $r;
46         
47         if ($self->[4] != $self->[2]) {
48                 $r = $self->[5]->[$self->[4]++];
49                 $self->[4] = 0 if $self->[4] >= $self->[0];
50         }
51         return $r;
52 }
53
54 sub rewind
55 {
56         my $self = shift;
57         $self->[4] = $self->[3];
58 }
59
60 sub lth
61 {
62         my $self = shift;
63         return $self->[1];
64 }
65
66 sub readall
67 {
68         my $self = shift;
69         my @out;
70         
71         $self->rewind;
72         while (my $r = $self->read) {
73                 push @out, $r;
74         }
75         return @out;
76 }
77 1;