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 33 2009-02-16 09:33:39Z nbachiyski $
13 * Provides file-like methods for manipulating a string instead
16 class POMO_StringReader {
20 function POMO_StringReader($str = '') {
25 function read($bytes) {
26 $data = substr($this->_str, $this->_pos, $bytes);
27 $this->_pos += $bytes;
28 if (strlen($this->_str)<$this->_pos)
29 $this->_pos = strlen($this->_str);
34 function seekto($pos) {
36 if (strlen($this->_str)<$this->_pos)
37 $this->_pos = strlen($this->_str);
46 return strlen($this->_str);
52 * Reads the contents of the file in the beginning.
54 class POMO_CachedFileReader extends POMO_StringReader {
55 function POMO_CachedFileReader($filename) {
56 $this->_str = file_get_contents($filename);
57 if (false === $this->_str)
64 * Allows reading integers from a file.
66 class POMO_CachedIntFileReader extends POMO_CachedFileReader {
68 var $endian = 'little';
71 * Opens a file and caches it.
73 * @param $filename string name of the file to be opened
74 * @param $endian string endianness of the words in the file, allowed
75 * values are 'little' or 'big'. Default value is 'little'
77 function POMO_CachedIntFileReader($filename, $endian = 'little') {
78 $this->endian = $endian;
79 parent::POMO_CachedFileReader($filename);
83 * Sets the endianness of the file.
85 * @param $endian string 'big' or 'little'
87 function setEndian($endian) {
88 $this->endian = $endian;
92 * Reads a 32bit Integer from the Stream
94 * @return mixed The integer, corresponding to the next 32 bits from
95 * the stream of false if there are not enough bytes or on error
97 function readint32() {
98 $bytes = $this->read(4);
99 if (4 != strlen($bytes))
101 $endian_letter = ('big' == $this->endian)? 'N' : 'V';
102 $int = unpack($endian_letter, $bytes);
103 return array_shift($int);
107 * Reads an array of 32-bit Integers from the Stream
109 * @param integer count How many elements should be read
110 * @return mixed Array of integers or false if there isn't
111 * enough data or on error
113 function readint32array($count) {
114 $bytes = $this->read(4 * $count);
115 if (4*$count != strlen($bytes))
117 $endian_letter = ('big' == $this->endian)? 'N' : 'V';
118 return unpack($endian_letter.$count, $bytes);