Skip to content

Commit 2fc7c69

Browse files
committed
Added items() method
1 parent 4bcc7a7 commit 2fc7c69

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

ConcurrentFIFO.php

+38
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,44 @@ function clear() {
199199
ftruncate($this->fp, 0);
200200
flock($this->fp, LOCK_UN);
201201
}
202+
203+
/**
204+
* Return an array of items from the queue. Does not modify the queue in any way.
205+
*
206+
* @param int $offset skip $offset items at the start
207+
* @param int $count return up to $count items
208+
* @return multitype:string
209+
*/
210+
function items($offset=0, $count=0) {
211+
flock($this->fp, LOCK_SH) or die('Failed to get lock');
212+
213+
$index = $this->_read_index();
214+
if(!$index) return array();
215+
216+
$result = array();
217+
$p = $index['start'];
218+
while($p < $index['end']) {
219+
$l = $this->_read_int(self::LENGTH_FORMAT, self::LENGTH_SIZE);
220+
if(!$l) break;
221+
222+
$data = fread($this->fp, $l);
223+
$p += $l + self::LENGTH_SIZE;
224+
assert($p == ftell($this->fp));
225+
226+
if($offset) {
227+
$offset--;
228+
} else {
229+
$result[] = $data;
230+
if($count) {
231+
$count--;
232+
if(!$count) break;
233+
}
234+
}
235+
}
236+
237+
flock($this->fp, LOCK_UN);
238+
return $result;
239+
}
202240

203241
/**
204242
* Compacts the data file by shifting the unprocessed items to the start of the datafile

tests/FIFOTest.php

+16
Original file line numberDiff line numberDiff line change
@@ -96,4 +96,20 @@ function testAutoCompaction() {
9696
$this->assertEquals(null, $this->fifo->_read_index());
9797
}
9898

99+
function testItems() {
100+
for($i=0; $i<10; $i++) $this->fifo->enqueue('ITEM_' . $i);
101+
$this->assertSame(10, count($this->fifo->items()));
102+
103+
$this->assertEquals(array('ITEM_8', 'ITEM_9'), $this->fifo->items(8));
104+
$this->assertEquals(array('ITEM_4', 'ITEM_5', 'ITEM_6'), $this->fifo->items(4, 3));
105+
106+
$this->assertEquals(array('ITEM_8', 'ITEM_9'), $this->fifo->items(8, 12));
107+
$this->assertEquals(array(), $this->fifo->items(23));
108+
109+
$this->fifo->clear();
110+
$this->assertSame(array(), $this->fifo->items());
111+
$this->assertSame(array(), $this->fifo->items(4));
112+
$this->assertSame(array(), $this->fifo->items(4, 2));
113+
}
114+
99115
}

0 commit comments

Comments
 (0)