forked from xp-framework/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIterableInputStream.class.php
More file actions
executable file
·63 lines (56 loc) · 1.66 KB
/
IterableInputStream.class.php
File metadata and controls
executable file
·63 lines (56 loc) · 1.66 KB
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
<?php namespace io\streams;
use Iterator, Closure, Traversable;
use lang\IllegalArgumentException;
/** @test io.unittest.IterableInputStreamTest */
class IterableInputStream implements InputStream {
private $iterator;
private $buffer= null;
/** @param iterable|function(): Iterator $input */
public function __construct($input) {
if ($input instanceof Iterator) {
$this->iterator= $input;
} else if ($input instanceof Closure) {
$this->iterator= cast($input(), Iterator::class);
} else if (is_iterable($input)) {
$this->iterator= (function() use($input) { yield from $input; })();
} else {
throw new IllegalArgumentException('Expected iterable|function(): Iterator, have '.typeof($input));
}
$this->iterator->rewind();
}
/** @return int */
public function available() {
if (null !== $this->buffer) {
return strlen($this->buffer);
} else if ($this->iterator->valid()) {
$this->buffer= $this->iterator->current();
$this->iterator->next();
return strlen($this->buffer);
} else {
return 0;
}
}
/**
* Reads up to a given limit
*
* @param int $limit
* @return string
*/
public function read($limit= 8192) {
if (null !== $this->buffer) {
// Continue draining the buffer
} else if ($this->iterator->valid()) {
$this->buffer= $this->iterator->current();
$this->iterator->next();
} else {
return '';
}
$chunk= substr($this->buffer, 0, $limit);
$this->buffer= $limit >= strlen($this->buffer) ? null : substr($this->buffer, $limit);
return $chunk;
}
/** @return void */
public function close() {
// NOOP
}
}