3 * A general file-based stack class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseFileStack extends BaseStacker {
26 * Magic for this stack
28 const STACK_MAGIC = 'STACKv0.1';
31 * Protected constructor
33 * @param $className Name of the class
36 protected function __construct ($className) {
37 // Call parent constructor
38 parent::__construct($className);
40 // Calculate header size
42 strlen(self::STACK_MAGIC) +
43 strlen(chr(self::SEPARATOR_HEADER_DATA)) +
45 strlen(chr(self::SEPARATOR_HEADER_DATA)) +
46 self::LENGTH_POSITION +
47 strlen(chr(self::SEPARATOR_HEADER_ENTRIES))
50 // Init counters and gaps array
51 $this->initCountersGapsArray();
55 * Reads the file header
58 * @todo To hard assertions here, better rewrite them to exceptions
60 public function readFileHeader () {
61 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
63 // First rewind to beginning as the header sits at the beginning ...
64 $this->getIteratorInstance()->rewind();
66 // Then read it (see constructor for calculation)
67 $data = $this->getIteratorInstance()->read($this->getHeaderSize());
68 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getHeaderSize()));
70 // Have all requested bytes been read?
71 assert(strlen($data) == $this->getHeaderSize());
72 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
74 // Last character must be the separator
75 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
76 assert(substr($data, -1, 1) == chr(self::SEPARATOR_HEADER_ENTRIES));
77 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
79 // Okay, then remove it
80 $data = substr($data, 0, -1);
82 // And update seek position
83 $this->updateSeekPosition();
90 * 2 => current seek position
92 $header = explode(chr(self::SEPARATOR_HEADER_DATA), $data);
95 $this->setHeader($header);
97 // Check if the array has only 3 elements
98 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
99 assert(count($header) == 3);
100 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
103 assert($header[0] == self::STACK_MAGIC);
104 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
106 // Check length of count and seek position
107 assert(strlen($header[1]) == self::LENGTH_COUNT);
108 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
109 assert(strlen($header[2]) == self::LENGTH_POSITION);
110 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
112 // Decode count and seek position
113 $header[1] = hex2bin($header[1]);
114 $header[2] = hex2bin($header[2]);
116 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
120 * Flushes the file header
124 public function flushFileHeader () {
125 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
127 // Put all informations together
128 $header = sprintf('%s%s%s%s%s%s',
132 // Separator magic<->count
133 chr(self::SEPARATOR_HEADER_DATA),
135 // Total entries (will be zero) and pad it to 20 chars
136 str_pad($this->dec2hex($this->getCounter()), self::LENGTH_COUNT, '0', STR_PAD_LEFT),
138 // Separator count<->seek position
139 chr(self::SEPARATOR_HEADER_DATA),
141 // Position (will be zero)
142 str_pad($this->dec2hex($this->getSeekPosition(), 2), self::LENGTH_POSITION, '0', STR_PAD_LEFT),
144 // Separator position<->entries
145 chr(self::SEPARATOR_HEADER_ENTRIES)
148 // Write it to disk (header is always at seek position 0)
149 $this->writeData(0, $header, FALSE);
151 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
155 * Initializes this file-based stack.
157 * @param $fileName File name of this stack
158 * @param $type Type of this stack (e.g. url_source for URL sources)
160 * @todo Currently the stack file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole stack file.
162 protected function initFileStack ($fileName, $type) {
163 // Get a stack file instance
164 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName, $this));
166 // Get iterator instance
167 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
169 // Is the instance implementing the right interface?
170 assert($iteratorInstance instanceof SeekableWritableFileIterator);
173 $this->setIteratorInstance($iteratorInstance);
175 // Is the file's header initialized?
176 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
177 // No, then create it (which may pre-allocate the stack)
178 $this->getIteratorInstance()->createFileHeader();
180 // And pre-allocate a bit
181 $this->getIteratorInstance()->preAllocateFile('file_stack');
184 // Load the file header
185 $this->readFileHeader();
187 // Count all entries in file
188 $this->getIteratorInstance()->analyzeFile();
191 * Get stack index instance. This can be used for faster
192 * "defragmentation" and startup.
194 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
197 $this->setIndexInstance($indexInstance);
201 * Adds a value to given stack
203 * @param $stackerName Name of the stack
204 * @param $value Value to add to this stacker
206 * @throws FullStackerException If the stack is full
208 protected function addValue ($stackerName, $value) {
210 if ($this->isStackFull($stackerName)) {
212 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
215 // Now add the value to the stack
216 $this->partialStub('stackerName=' . $stackerName . ',value[]=' . gettype($value));
220 * Get last value from named stacker
222 * @param $stackerName Name of the stack
223 * @return $value Value of last added value
224 * @throws EmptyStackerException If the stack is empty
226 protected function getLastValue ($stackerName) {
227 // Is the stack not yet initialized or full?
228 if ($this->isStackEmpty($stackerName)) {
229 // Throw an exception
230 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
233 // Now get the last value
234 $this->partialStub('stackerName=' . $stackerName);
242 * Get first value from named stacker
244 * @param $stackerName Name of the stack
245 * @return $value Value of last added value
246 * @throws EmptyStackerException If the stack is empty
248 protected function getFirstValue ($stackerName) {
249 // Is the stack not yet initialized or full?
250 if ($this->isStackEmpty($stackerName)) {
251 // Throw an exception
252 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
255 // Now get the first value
256 $this->partialStub('stackerName=' . $stackerName);
264 * "Pops" last entry from stack
266 * @param $stackerName Name of the stack
267 * @return $value Value "poped" from array
268 * @throws EmptyStackerException If the stack is empty
270 protected function popLast ($stackerName) {
271 // Is the stack not yet initialized or full?
272 if ($this->isStackEmpty($stackerName)) {
273 // Throw an exception
274 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
277 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
278 $this->partialStub('stackerName=' . $stackerName);
283 * "Pops" first entry from stack
285 * @param $stackerName Name of the stack
286 * @return $value Value "shifted" from array
287 * @throws EmptyStackerException If the named stacker is empty
289 protected function popFirst ($stackerName) {
290 // Is the stack not yet initialized or full?
291 if ($this->isStackEmpty($stackerName)) {
292 // Throw an exception
293 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
296 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
297 $this->partialStub('stackerName=' . $stackerName);
302 * Checks whether the given stack is full
304 * @param $stackerName Name of the stack
305 * @return $isFull Whether the stack is full
307 protected function isStackFull ($stackerName) {
308 // File-based stacks will only run full if the disk space is low.
309 // @TODO Please implement this, returning FALSE
317 * Checks whether the given stack is empty
319 * @param $stackerName Name of the stack
320 * @return $isEmpty Whether the stack is empty
321 * @throws NoStackerException If given stack is missing
323 public function isStackEmpty ($stackerName) {
324 // So, is the stack empty?
325 $isEmpty = (($this->getStackCount($stackerName)) == 0);
332 * Initializes given stacker
334 * @param $stackerName Name of the stack
335 * @param $forceReInit Force re-initialization
337 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
339 public function initStack ($stackerName, $forceReInit = FALSE) {
340 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
344 * Initializes all stacks
347 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
349 public function initStacks (array $stacks, $forceReInit = FALSE) {
350 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
354 * Checks whether the given stack is initialized (set in array $stackers)
356 * @param $stackerName Name of the stack
357 * @return $isInitialized Whether the stack is initialized
358 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
360 public function isStackInitialized ($stackerName) {
361 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
365 * Close a file source and set it's instance to null and the file name
369 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
371 public function closeFile () {
372 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
376 * Determines whether the EOF has been reached
378 * @return $isEndOfFileReached Whether the EOF has been reached
379 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
381 public function isEndOfFileReached () {
382 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
386 * Getter for file name
388 * @return $fileName The current file name
389 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
391 public function getFileName () {
392 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
396 * Getter for size of given stack (array count)
398 * @param $stackerName Name of the stack
399 * @return $count Size of stack (array count)
401 public function getStackCount ($stackerName) {
402 // Now, simply return the found count value, this must be up-to-date then!
403 return $this->getCounter();
407 * Calculates minimum length for one entry/block
409 * @return $length Minimum length for one entry/block
411 public function calculateMinimumBlockLength () {
413 $length = self::getHashLength() + strlen(chr(self::SEPARATOR_HASH_NAME)) + self::LENGTH_NAME + 1 + strlen(chr(self::SEPARATOR_ENTRIES));