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 * Separator magic->count
33 const SEPARATOR_MAGIC_COUNT = 0x01;
36 * Separator count->position
38 const SEPARATOR_COUNT_SEEK_POS = 0x02;
41 * Separator position->entries
43 const SEPARATOR_SEEK_POS_ENTRIES = 0x03;
46 * Separator hash->name
48 const SEPARATOR_HASH_NAME = 0x04;
53 const COUNT_NAME = 10;
58 const COUNT_LENGTH = 20;
63 const COUNT_POSITION = 20;
66 * Counter for total entries
68 private $totalEntries = 0;
71 * Current seek position
73 private $seekPosition = 0;
76 * Protected constructor
78 * @param $className Name of the class
81 protected function __construct ($className) {
82 // Call parent constructor
83 parent::__construct($className);
87 * Getter for total entries
89 * @return $totalEntries Total entries in this stack
91 private function getCounter () {
93 return $this->totalEntries;
101 private function incrementCounter () {
103 $this->totalEntries++;
107 * Getter for seek position
109 * @return $seekPosition Current seek position (stored here in object)
111 private function getSeekPosition () {
113 return $this->seekPosition;
117 * Setter for seek position
119 * @param $seekPosition Current seek position (stored here in object)
122 private function setSeekPosition ($seekPosition) {
124 $this->seekPosition = $seekPosition;
128 * Updates seekPosition attribute from file to avoid to much access on file.
132 private function updateSeekPosition () {
133 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
135 // Get key (= seek position)
136 $seekPosition = $this->getIteratorInstance()->key();
137 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
140 $this->setSeekPosition($seekPosition);
142 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
146 * Checks whether the file header is initialized
148 * @return $isInitialized Whether the file header is initialized
150 private function isFileHeaderInitialized () {
151 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
152 // Default is not initialized
153 $isInitialized = FALSE;
155 // Is the file initialized?
156 if ($this->isFileInitialized()) {
157 // Some bytes has been written, so rewind to start of it.
158 $rewindStatus = $this->getIteratorInstance()->rewind();
159 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] rewindStatus=%s', __METHOD__, __LINE__, $rewindStatus));
161 // Is the rewind() call successfull?
162 if ($rewindStatus != 1) {
163 // Something bad happened
164 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Could not rewind().', __METHOD__, __LINE__));
168 $this->readFileHeader();
172 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
173 return $isInitialized;
177 * Checks whether the file-based stack has been initialized
179 * @return $isInitialized Whether the file's size is zero
181 private function isFileInitialized () {
182 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
184 // Get it from iterator which holds the pointer instance. If FALSE is returned
185 $fileSize = $this->getIteratorInstance()->size();
186 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] fileSize=%s', __METHOD__, __LINE__, $fileSize));
189 * The returned file size should not be FALSE or NULL as this means
190 * that the pointer class does not work correctly.
192 assert(is_int($fileSize));
194 // Is more than 0 returned?
195 $isInitialized = ($fileSize > 0);
198 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
199 return $isInitialized;
203 * Creates the file-stack's header
207 private function createFileHeader () {
208 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
209 // The file's header should not be initialized here
210 assert(!$this->isFileHeaderInitialized());
212 // Simple flush file header which will create it.
213 $this->flushFileHeader();
215 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
219 * Flushes the file header
223 private function flushFileHeader () {
224 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
226 // Put all informations together
227 $header = sprintf('%s%s%s%s%s%s',
231 // Separator magic<->count
232 chr(self::SEPARATOR_MAGIC_COUNT),
234 // Total entries (will be zero) and pad it to 20 chars
235 str_pad($this->dec2hex($this->getCounter()), self::COUNT_LENGTH, '0', STR_PAD_LEFT),
237 // Separator count<->seek position
238 chr(self::SEPARATOR_COUNT_SEEK_POS),
240 // Position (will be zero)
241 str_pad($this->dec2hex($this->getSeekPosition(), 2), self::COUNT_POSITION, '0', STR_PAD_LEFT),
243 // Separator position<->entries
244 chr(self::SEPARATOR_SEEK_POS_ENTRIES)
247 // Write it to disk (header is always at seek position 0)
248 $this->writeData(0, $header);
250 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
254 * Writes data at given position
256 * @param $seekPosition Seek position
257 * @param $data Data to be written
260 private function writeData ($seekPosition, $data) {
261 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data()=%s - CALLED!', __METHOD__, __LINE__, $seekPosition, strlen($data)));
263 // Write data at given position
264 $this->getIteratorInstance()->writeAtPosition($seekPosition, $data);
266 // Update seek position
267 $this->updateSeekPosition();
269 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
273 * Pre-allocates file (if enabled) with some space for later faster write access.
277 private function preAllocateFile () {
278 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
281 if ($this->getConfigInstance()->getConfigEntry('file_stack_pre_allocate_enabled') != 'Y') {
283 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Not pre-allocating stack file.', __METHOD__, __LINE__));
285 // Don't continue here.
290 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Pre-allocating stack file ...', __METHOD__, __LINE__));
293 * Calculate minimum length for one entry:
294 * minimum length = hash length + separator + name + minimum entry size = ?? + 1 + 10 + 1 = ??
296 $minLengthEntry = self::getHashLength() + strlen(self::SEPARATOR_HASH_NAME) + self::COUNT_NAME + 1;
297 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] minLengthEntry=%s', __METHOD__, __LINE__, $minLengthEntry));
299 // Calulcate seek position
300 $seekPosition = $minLengthEntry * $this->getConfigInstance()->getConfigEntry('file_stack_pre_allocate_count');
301 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
303 // Now simply write a NUL there. This will pre-allocate the file.
304 $this->writeData($seekPosition, chr(0));
306 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
310 * Initializes this file-based stack.
312 * @param $fileName File name of this stack
315 protected function initFileStack ($fileName) {
316 // Get a file i/o pointer instance
317 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileName));
319 // Get iterator instance
320 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_io_iterator_class', array($pointerInstance));
322 // Is the instance implementing the right interface?
323 assert($iteratorInstance instanceof SeekableWritableFileIterator);
326 $this->setIteratorInstance($iteratorInstance);
328 // Is the file's header initialized?
329 if ($this->isFileHeaderInitialized()) {
331 $this->loadFileHeader();
333 // No, then create it (which may pre-allocate the stack)
334 $this->createFileHeader();
336 // And pre-allocate a bit
337 $this->preAllocateFile();
342 * Initializes given stacker
344 * @param $stackerName Name of the stack
345 * @param $forceReInit Force re-initialization
347 * @throws AlreadyInitializedStackerException If the stack is already initialized
349 public function initStack ($stackerName, $forceReInit = FALSE) {
350 // Is the stack already initialized?
351 if (($forceReInit === FALSE) && ($this->isStackInitialized($stackerName))) {
352 // Then throw the exception
353 throw new AlreadyInitializedStackerException(array($this, $stackerName, $forceReInit), self::EXCEPTION_STACKER_ALREADY_INITIALIZED);
356 // Initialize the given stack
357 $this->partialStub('stackerName=' . $stackerName . ',forceReInit=' . intval($forceReInit));
361 * Checks whether the given stack is initialized (set in array $stackers)
363 * @param $stackerName Name of the stack
364 * @return $isInitialized Whether the stack is initialized
366 public function isStackInitialized ($stackerName) {
368 $this->partialStub('stackerName=' . $stackerName);
369 $isInitialized = TRUE;
372 return $isInitialized;
376 * Getter for size of given stack (array count)
378 * @param $stackerName Name of the stack
379 * @return $count Size of stack (array count)
380 * @throws NoStackerException If given stack is missing
382 public function getStackCount ($stackerName) {
383 // Is the stack not yet initialized?
384 if (!$this->isStackInitialized($stackerName)) {
385 // Throw an exception
386 throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
389 // Now, count the array of entries
390 $this->partialStub('stackerName=' . $stackerName);
398 * Adds a value to given stack
400 * @param $stackerName Name of the stack
401 * @param $value Value to add to this stacker
403 * @throws FullStackerException Thrown if the stack is full
405 protected function addValue ($stackerName, $value) {
406 // Is the stack not yet initialized or full?
407 if (!$this->isStackInitialized($stackerName)) {
409 $this->initStack($stackerName);
410 } elseif ($this->isStackFull($stackerName)) {
412 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
415 // Now add the value to the stack
416 $this->partialStub('stackerName=' . $stackerName . ',value[]=' . gettype($value));
420 * Get last value from named stacker
422 * @param $stackerName Name of the stack
423 * @return $value Value of last added value
424 * @throws NoStackerException If the named stacker was not found
425 * @throws EmptyStackerException If the named stacker is empty
427 protected function getLastValue ($stackerName) {
428 // Is the stack not yet initialized or full?
429 if (!$this->isStackInitialized($stackerName)) {
430 // Throw an exception
431 throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
432 } elseif ($this->isStackEmpty($stackerName)) {
433 // Throw an exception
434 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
437 // Now get the last value
438 $this->partialStub('stackerName=' . $stackerName);
446 * Get first value from named stacker
448 * @param $stackerName Name of the stack
449 * @return $value Value of last added value
450 * @throws NoStackerException If the named stacker was not found
451 * @throws EmptyStackerException If the named stacker is empty
453 protected function getFirstValue ($stackerName) {
454 // Is the stack not yet initialized or full?
455 if (!$this->isStackInitialized($stackerName)) {
456 // Throw an exception
457 throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
458 } elseif ($this->isStackEmpty($stackerName)) {
459 // Throw an exception
460 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
463 // Now get the first value
464 $this->partialStub('stackerName=' . $stackerName);
472 * "Pops" last entry from stack
474 * @param $stackerName Name of the stack
475 * @return $value Value "poped" from array
476 * @throws NoStackerException If the named stacker was not found
477 * @throws EmptyStackerException If the named stacker is empty
479 protected function popLast ($stackerName) {
480 // Is the stack not yet initialized or full?
481 if (!$this->isStackInitialized($stackerName)) {
482 // Throw an exception
483 throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
484 } elseif ($this->isStackEmpty($stackerName)) {
485 // Throw an exception
486 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
489 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
490 $this->partialStub('stackerName=' . $stackerName);
495 * "Pops" first entry from stack
497 * @param $stackerName Name of the stack
498 * @return $value Value "shifted" from array
499 * @throws NoStackerException If the named stacker was not found
500 * @throws EmptyStackerException If the named stacker is empty
502 protected function popFirst ($stackerName) {
503 // Is the stack not yet initialized or full?
504 if (!$this->isStackInitialized($stackerName)) {
505 // Throw an exception
506 throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
507 } elseif ($this->isStackEmpty($stackerName)) {
508 // Throw an exception
509 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
512 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
513 $this->partialStub('stackerName=' . $stackerName);