/
Priority.pm
307 lines (219 loc) · 7.47 KB
/
Priority.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package List::Priority;
use 5.006;
use strict;
use warnings;
use vars qw($VERSION);
use Carp;
use List::Util qw/min max/;
$VERSION = '0.05';
# Constructor. Enables Inheritance
sub new {
my $this = shift;
my $class = ref($this) || $this;
my $self = {};
bless $self, $class;
if (@_) {
my %options = @_;
$self->{options} = \%options;
}
$self->{size} = 0;
return $self;
}
# Insert an element into the list
sub insert {
# Arguments check
croak 'List::Priority - Expected 3 arguments!' if (scalar(@_) != 3);
# Argument assignment
(my $self, my $priority, my $object) = @_;
# Check that priority is numeric - Thanks Randel/Joseph!
croak 'List::Priority - Priority must be numeric!'
if ((~$priority & $priority) ne '0');
# If the list is full
if (defined($self->{options}{capacity}) and
$self->{options}{capacity} <= $self->{size}) {
my ($bottom_priority) = min(keys %{$self->{queues}});
# And the object's priority is higher than the lowest on the list
# - remove the lowest one to insert it
if ($priority > $bottom_priority) {
$self->_extract($bottom_priority);
}
# Else, just return - the list is full.
else {
return 'List::Priority - Object denied, list is full';
}
}
# Insert
push(@{$self->{queues}{$priority}}, $object);
++$self->{size};
return 1;
}
# Helper method for pop() and shift()
# If $priority is defined, return the first-in element with that priority.
# Otherwise, use $minmax() to find the best priority in the set, and
# extract the first element with that priority.
sub _extract {
my ($self, $priority) = @_;
return undef if ($self->{size} == 0);
return undef unless (defined ($priority));
# Remove the queue's first element
my $object = CORE::shift (@{$self->{queues}{$priority}});
# If the queue is now empty - delete it
delete $self->{queues}{$priority}
if (scalar(@{$self->{queues}{$priority}}) == 0);
# Return the object I just shifted out of the queue
--$self->{size};
return $object;
}
# Find out the extreme (top or bottom) priority
sub _extreme_priority {
my ($self, $minmax) = @_;
return $minmax->(keys %{$self->{queues}});
}
sub highest_priority {
my $self = shift;
return $self->_extreme_priority(\&max);
}
sub lowest_priority {
my $self = shift;
return $self->_extreme_priority(\&min);
}
sub pop {
# Arguments check
croak 'List::Priority - pop expected 1 argument' if (scalar(@_) != 1);
my ($self) = @_;
return $self->_extract($self->highest_priority);
}
sub shift {
# Arguments check
croak 'List::Priority - shift expected 1 argument' if (scalar(@_) != 1);
my ($self) = @_;
return $self->_extract($self->lowest_priority);
}
sub size {
my ($self) = @_;
return $self->{size};
}
sub capacity {
my ($self, $new_capacity) = @_;
if (@_ > 1) {
$self->{options}{capacity} = $new_capacity;
if (defined $new_capacity) {
while ($self->size > $new_capacity) {
$self->shift;
}
}
}
return $self->{options}{capacity};
}
1;
__END__
# Documentation
=head1 NAME
List::Priority - Perl extension for a list that manipulates objects by their
priority
=head1 SYNOPSIS
use List::Priority;
# Create an instance
my $list = List::Priority->new();
# Insert some elements, each with a unique priority
$list->insert(2,'World!');
$list->insert(5,'Hello');
$list->insert(3,' ');
# Print
print $list->size() # prints 3
while (my $element = $list->pop()) {
print $element;
}
=head1 DESCRIPTION
If you want to handle multiple data items by their order of importance,
this one's for you.
You may retrieve the highest-priority item from the list using C<pop()>, or the
lowest-priority item from the list using C<shift()>. If two items have the same
priority, they are returned in first-in, first-out order. New items are
inserted using C<insert()>.
You can constrain the capacity of the list using the C<capacity> parameter.
Low-priority items are automatically evicted once the specified capacity is
exceeded. By default the list's capacity is unlimited.
Currently insertion (in ordered or random order) is constant-time, but C<shift>
and C<pop> are linear in the number of priorities. Hence List::Priority is a
good choice if one of the following conditions is true:
=over
=item * you need one of its unusual features, like the ability to remove both
high- and low-priority items, or to constrain the list's capacity,
=item * you need to do a lot of inserting, but the list will never contain more
than a few thousand different priority levels.
=back
If neither of these describes your use case, another priority queue
implementation like L<POE::XS::Queue::Array> may perform better.
I'd like to thank Joseph N. Hall and Randal L. Schwartz for their
excellent book "Effective Perl Programming" for one of the code hacks.
=head1 METHODS
=over 4
=item B<new>
$p_list = List::Priority->new();
B<new> is the constructor for List::Priority objects. It accepts a key-value
list with the list attributes.
=over
=item * B<capacity>
The maximum size of the list.
Inserting after the capacity is reached will result either in a no-op, or the
removal of the most recent lowest priority objects, according to the
C<insert()>'s priority.
$list = List::Priority->new(capacity => 10);
=back
=item B<insert>
$result = $p_list->insert($priority, $scalar);
Inserts the scalar to the list. Time taken is approximately constant.
C<$priority> must be numeric. C<$scalar> can be any scalar, including
references (objects).
Returns 1 on success, and a string describing the error upon failure.
=item B<pop>
$object = $p_list->pop();
Extracts the highest-priority scalar from the list.
Time taken is approximately linear in the number of I<priorities> already in
the list.
Returns the highest-priority object on success, and C<undef> on failure.
=item B<shift>
$object = $p_list->shift();
Extracts the B<lowest>-priority scalar from the list.
Time taken is approximately linear in the number of I<priorities> already in
the list.
Returns the lowest-priority object on success, C<undef> on failure.
=item B<highest_priority>
$priority = $p_list->highest_priority();
Returns the priority of the highest-priority item. Time taken is linear in the
number of priorities in the list.
=item B<lowest_priority>
$priority = $p_list->lowest_priority();
Returns the priority of the lowest-priority item. Time taken is linear in the
number of priorities in the list.
=item B<size>
$num_elts = $p_list->size();
Takes no arguments. Returns the number of elements in the priority queue.
Time taken is constant.
=item B<capacity>
my $capacity = $l->capacity(); # get capacity
$l->capacity($new_capacity); # set capacity to $new_capacity
$l->capacity(undef); # set capacity to infinity
Get/set the list's capacity. If called with an argument, sets the capacity to
that value, discarding any excess low-priority items. To make the capacity
infinite (the default for new lists), call C<capacity()> with an explicit
undefined argument.
Time taken is O($old_capacity - $new_capacity) if $new_capacity <
$old_capacity, constant otherwise.
Returns the (new) capacity.
=back
=head1 EXPORT
None. All interfaces are OO.
=head1 TODO
More tests.
=head1 AUTHOR
Eyal Udassin, <eyaludassin@hotmail.com>
Currently maintained by Miles Gould, <miles@assyrian.org.uk>
Thanks to Maik Hentsche for bugfixes.
=head1 CONTRIBUTING
You can find the Git repository at L<http://github.com/pozorvlak/List-Priority>.
=head1 SEE ALSO
L<Heap::Priority>, L<List::PriorityQueue>, L<Hash::PriorityQueue>,
L<POE::Queue>, L<Timeout::Queue>, L<Data::PrioQ::SkewBinomial>.
=cut