00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00016 final class BufferedInputStream extends InputStream
00017 {
00018 private $runAheadBytes = 0;
00019
00020 private $in = null;
00021 private $closed = false;
00022
00023 private $buffer = null;
00024 private $bufferLength = 0;
00025
00026 private $position = 0;
00027 private $markPosition = null;
00028
00029 public function __construct(InputStream $in)
00030 {
00031 $this->in = $in;
00032 }
00033
00037 public static function create(InputStream $in)
00038 {
00039 return new self($in);
00040 }
00041
00045 public function close()
00046 {
00047 $this->closed = true;
00048
00049 return $this;
00050 }
00051
00052 public function isEof()
00053 {
00054 return $this->in->isEof();
00055 }
00056
00057 public function markSupported()
00058 {
00059 return true;
00060 }
00061
00065 public function mark()
00066 {
00067 $this->markPosition = $this->position;
00068
00069 return $this;
00070 }
00071
00075 public function reset()
00076 {
00077 $this->position = $this->markPosition;
00078
00079 return $this;
00080 }
00081
00082 public function available()
00083 {
00084 if ($this->closed)
00085 return 0;
00086
00087 return ($this->bufferLength - $this->position);
00088 }
00089
00093 public function setRunAheadBytes($runAheadBytes)
00094 {
00095 $this->runAheadBytes = $runAheadBytes;
00096
00097 return $this;
00098 }
00099
00100 public function read($count)
00101 {
00102 if ($this->closed)
00103 return null;
00104
00105 $remainingCount = $count;
00106 $availableCount = $this->available();
00107
00108 if ($remainingCount <= $availableCount)
00109 $readFromBuffer = $count;
00110 else
00111 $readFromBuffer = $availableCount;
00112
00113 $result = null;
00114
00115 if ($readFromBuffer > 0) {
00116 $result = substr(
00117 $this->buffer, $this->position, $readFromBuffer
00118 );
00119
00120 $this->position += $readFromBuffer;
00121 $remainingCount -= $readFromBuffer;
00122 }
00123
00124 if ($remainingCount > 0) {
00125
00126 $readAtOnce = ($remainingCount < $this->runAheadBytes)
00127 ? $this->runAheadBytes
00128 : $remainingCount;
00129
00130 $readBytes = $this->in->read($readAtOnce);
00131 $readBytesLength = strlen($readBytes);
00132
00133 if ($readBytesLength > 0) {
00134 $this->buffer .= $readBytes;
00135 $this->bufferLength += $readBytesLength;
00136
00137 if ($readBytesLength <= $remainingCount) {
00138 $this->position += $readBytesLength;
00139 $result .= $readBytes;
00140 } else {
00141 $this->position += $remainingCount;
00142 $result .= substr($readBytes, 0, $remainingCount);
00143 }
00144 }
00145 }
00146
00147 return $result;
00148 }
00149 }
00150 ?>