3 * Classes, which help reading streams of data from files.
4 * Based on the classes from Danilo Segan <danilo@kvota.net>
6 * @version $Id: streams.php 138 2009-06-23 13:22:09Z nbachiyski $
13 * Provides file-like methods for manipulating a string instead
16 class POMO_StringReader {
20 function POMO_StringReader($str = '') {
23 $this->is_overloaded = ((ini_get("mbstring.func_overload") & 2) != 0) && function_exists('mb_substr');
26 function _substr($string, $start, $length) {
27 if ($this->is_overloaded) {
28 return mb_substr($string,$start,$length,'ascii');
30 return substr($string,$start,$length);
34 function _strlen($string) {
35 if ($this->is_overloaded) {
36 return mb_strlen($string,'ascii');
38 return strlen($string);
42 function read($bytes) {
43 $data = $this->_substr($this->_str, $this->_pos, $bytes);
44 $this->_pos += $bytes;
45 if ($this->_strlen($this->_str) < $this->_pos) $this->_pos = $this->_strlen($this->_str);
49 function seekto($pos) {
51 if ($this->_strlen($this->_str) < $this->_pos) $this->_pos = $this->_strlen($this->_str);
60 return $this->_strlen($this->_str);
66 * Reads the contents of the file in the beginning.
68 class POMO_CachedFileReader extends POMO_StringReader {
69 function POMO_CachedFileReader($filename) {
70 parent::POMO_StringReader();
71 $this->_str = file_get_contents($filename);
72 if (false === $this->_str)
79 * Allows reading integers from a file.
81 class POMO_CachedIntFileReader extends POMO_CachedFileReader {
83 var $endian = 'little';
86 * Opens a file and caches it.
88 * @param $filename string name of the file to be opened
89 * @param $endian string endianness of the words in the file, allowed
90 * values are 'little' or 'big'. Default value is 'little'
92 function POMO_CachedIntFileReader($filename, $endian = 'little') {
93 $this->endian = $endian;
94 parent::POMO_CachedFileReader($filename);
98 * Sets the endianness of the file.
100 * @param $endian string 'big' or 'little'
102 function setEndian($endian) {
103 $this->endian = $endian;
107 * Reads a 32bit Integer from the Stream
109 * @return mixed The integer, corresponding to the next 32 bits from
110 * the stream of false if there are not enough bytes or on error
112 function readint32() {
113 $bytes = $this->read(4);
114 if (4 != $this->_strlen($bytes))
116 $endian_letter = ('big' == $this->endian)? 'N' : 'V';
117 $int = unpack($endian_letter, $bytes);
118 return array_shift($int);
122 * Reads an array of 32-bit Integers from the Stream
124 * @param integer count How many elements should be read
125 * @return mixed Array of integers or false if there isn't
126 * enough data or on error
128 function readint32array($count) {
129 $bytes = $this->read(4 * $count);
130 if (4*$count != $this->_strlen($bytes))
132 $endian_letter = ('big' == $this->endian)? 'N' : 'V';
133 return unpack($endian_letter.$count, $bytes);