3 * A general file-based stack class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 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 * Name of array index for gap position
33 const ARRAY_INDEX_GAP_POSITION = 'gap';
36 * Name of array index for hash
38 const ARRAY_INDEX_HASH = 'hash';
41 * Name of array index for length of raw data
43 const ARRAY_INDEX_DATA_LENGTH = 'length';
46 * Protected constructor
48 * @param $className Name of the class
51 protected function __construct ($className) {
52 // Call parent constructor
53 parent::__construct($className);
57 * Reads the file header
60 * @todo To hard assertions here, better rewrite them to exceptions
62 public function readFileHeader () {
63 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
65 // First rewind to beginning as the header sits at the beginning ...
66 $this->getIteratorInstance()->rewind();
68 // Then read it (see constructor for calculation)
69 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
70 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
72 // Have all requested bytes been read?
73 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
74 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
76 // Last character must be the separator
77 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
78 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
79 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
81 // Okay, then remove it
82 $data = substr($data, 0, -1);
84 // And update seek position
85 $this->getIteratorInstance()->updateSeekPosition();
92 * 2 => current seek position
94 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
97 $this->getIteratorInstance()->setHeader($header);
99 // Check if the array has only 3 elements
100 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
101 assert(count($header) == 3);
102 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
105 assert($header[0] == self::STACK_MAGIC);
106 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
108 // Check length of count and seek position
109 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
110 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
111 assert(strlen($header[2]) == BaseBinaryFile::LENGTH_POSITION);
112 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
114 // Decode count and seek position
115 $header[1] = hex2bin($header[1]);
116 $header[2] = hex2bin($header[2]);
118 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
122 * Flushes the file header
126 public function flushFileHeader () {
127 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
129 // Put all informations together
130 $header = sprintf('%s%s%s%s%s%s',
134 // Separator magic<->count
135 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
137 // Total entries (will be zero) and pad it to 20 chars
138 str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
140 // Separator count<->seek position
141 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
143 // Position (will be zero)
144 str_pad($this->dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
146 // Separator position<->entries
147 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
150 // Write it to disk (header is always at seek position 0)
151 $this->getIteratorInstance()->writeData(0, $header, FALSE);
153 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
157 * Initializes this file-based stack.
159 * @param $fileName File name of this stack
160 * @param $type Type of this stack (e.g. url_source for URL sources)
162 * @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.
164 protected function initFileStack ($fileName, $type) {
165 // Get a stack file instance
166 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName, $this));
168 // Get iterator instance
169 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
171 // Is the instance implementing the right interface?
172 assert($iteratorInstance instanceof SeekableWritableFileIterator);
175 $this->setIteratorInstance($iteratorInstance);
177 // Calculate header size
178 $this->getIteratorInstance()->setHeaderSize(
179 strlen(self::STACK_MAGIC) +
180 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
181 BaseBinaryFile::LENGTH_COUNT +
182 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
183 BaseBinaryFile::LENGTH_POSITION +
184 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
187 // Init counters and gaps array
188 $this->getIteratorInstance()->initCountersGapsArray();
190 // Is the file's header initialized?
191 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
192 // No, then create it (which may pre-allocate the stack)
193 $this->getIteratorInstance()->createFileHeader();
195 // And pre-allocate a bit
196 $this->getIteratorInstance()->preAllocateFile('file_stack');
199 // Load the file header
200 $this->readFileHeader();
202 // Count all entries in file
203 $this->getIteratorInstance()->analyzeFile();
206 * Get stack index instance. This can be used for faster
207 * "defragmentation" and startup.
209 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
212 $this->setIndexInstance($indexInstance);
216 * Adds a value to given stack
218 * @param $stackerName Name of the stack
219 * @param $value Value to add to this stacker
221 * @throws FullStackerException If the stack is full
223 protected function addValue ($stackerName, $value) {
225 if ($this->isStackFull($stackerName)) {
227 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
231 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
233 // No objects/resources are allowed as their serialization takes to long
234 assert(!is_object($value));
235 assert(!is_resource($value));
238 * Now add the value to the file stack which returns gap position, a
239 * hash and length of the raw data.
241 $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
243 // Add the hash and gap position to the index
244 $this->getIndexInstance()->addHashToIndex($stackerName, $data);
248 * Get last value from named stacker
250 * @param $stackerName Name of the stack
251 * @return $value Value of last added value
252 * @throws EmptyStackerException If the stack is empty
254 protected function getLastValue ($stackerName) {
255 // Is the stack not yet initialized or full?
256 if ($this->isStackEmpty($stackerName)) {
257 // Throw an exception
258 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
261 // Now get the last value
262 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
270 * Get first value from named stacker
272 * @param $stackerName Name of the stack
273 * @return $value Value of last added value
274 * @throws EmptyStackerException If the stack is empty
276 protected function getFirstValue ($stackerName) {
277 // Is the stack not yet initialized or full?
278 if ($this->isStackEmpty($stackerName)) {
279 // Throw an exception
280 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
283 // Now get the first value
284 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
292 * "Pops" last entry from stack
294 * @param $stackerName Name of the stack
295 * @return $value Value "poped" from array
296 * @throws EmptyStackerException If the stack is empty
298 protected function popLast ($stackerName) {
299 // Is the stack not yet initialized or full?
300 if ($this->isStackEmpty($stackerName)) {
301 // Throw an exception
302 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
305 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
306 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
311 * "Pops" first entry from stack
313 * @param $stackerName Name of the stack
314 * @return $value Value "shifted" from array
315 * @throws EmptyStackerException If the named stacker is empty
317 protected function popFirst ($stackerName) {
318 // Is the stack not yet initialized or full?
319 if ($this->isStackEmpty($stackerName)) {
320 // Throw an exception
321 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
324 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
325 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
330 * Checks whether the given stack is full
332 * @param $stackerName Name of the stack
333 * @return $isFull Whether the stack is full
335 protected function isStackFull ($stackerName) {
336 // File-based stacks will only run full if the disk space is low.
337 // @TODO Please implement this, returning FALSE
345 * Checks whether the given stack is empty
347 * @param $stackerName Name of the stack
348 * @return $isEmpty Whether the stack is empty
349 * @throws NoStackerException If given stack is missing
351 public function isStackEmpty ($stackerName) {
352 // So, is the stack empty?
353 $isEmpty = (($this->getStackCount($stackerName)) == 0);
360 * Initializes given stacker
362 * @param $stackerName Name of the stack
363 * @param $forceReInit Force re-initialization
365 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
367 public function initStack ($stackerName, $forceReInit = FALSE) {
368 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
372 * Initializes all stacks
375 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
377 public function initStacks (array $stacks, $forceReInit = FALSE) {
378 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
382 * Checks whether the given stack is initialized (set in array $stackers)
384 * @param $stackerName Name of the stack
385 * @return $isInitialized Whether the stack is initialized
386 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
388 public function isStackInitialized ($stackerName) {
389 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
393 * Determines whether the EOF has been reached
395 * @return $isEndOfFileReached Whether the EOF has been reached
396 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
398 public function isEndOfFileReached () {
399 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
403 * Getter for file name
405 * @return $fileName The current file name
406 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
408 public function getFileName () {
409 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
413 * Getter for size of given stack (array count)
415 * @param $stackerName Name of the stack
416 * @return $count Size of stack (array count)
418 public function getStackCount ($stackerName) {
419 // Now, simply return the found count value, this must be up-to-date then!
420 return $this->getIteratorInstance()->getCounter();
424 * Calculates minimum length for one entry/block
426 * @return $length Minimum length for one entry/block
428 public function calculateMinimumBlockLength () {
431 // Length of entry group
432 BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
434 self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
436 strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
443 * Initializes counter for valid entries, arrays for damaged entries and
444 * an array for gap seek positions. If you call this method on your own,
445 * please re-analyze the file structure. So you are better to call
446 * analyzeFile() instead of this method.
449 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
451 public function initCountersGapsArray () {
452 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
456 * Getter for header size
458 * @return $totalEntries Size of file header
459 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
461 public final function getHeaderSize () {
462 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
466 * Setter for header size
468 * @param $headerSize Size of file header
470 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
472 public final function setHeaderSize ($headerSize) {
473 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
477 * Getter for header array
479 * @return $totalEntries Size of file header
480 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
482 public final function getHeader () {
483 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
489 * @param $header Array for a file header
491 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
493 public final function setHeader (array $header) {
494 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
498 * Updates seekPosition attribute from file to avoid to much access on file.
501 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
503 public function updateSeekPosition () {
504 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
508 * Getter for total entries
510 * @return $totalEntries Total entries in this file
511 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
513 public final function getCounter () {
514 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
518 * Writes data at given position
520 * @param $seekPosition Seek position
521 * @param $data Data to be written
522 * @param $flushHeader Whether to flush the header (default: flush)
524 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
526 public function writeData ($seekPosition, $data, $flushHeader = TRUE) {
527 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
528 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
532 * Writes given value to the file and returns a hash and gap position for it
534 * @param $groupId Group identifier
535 * @param $value Value to be added to the stack
536 * @return $data Hash and gap position
537 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
539 public function writeValueToFile ($groupId, $value) {
540 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,value[%s]=%s', __METHOD__, __LINE__, $groupId, gettype($value), print_r($value, TRUE)));
541 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
545 * Searches for next suitable gap the given length of data can fit in
546 * including padding bytes.
548 * @param $length Length of raw data
549 * @return $seekPosition Found next gap's seek position
550 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
552 public function searchNextGap ($length) {
553 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] length=%s', __METHOD__, __LINE__, $length));
554 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
558 * "Getter" for file size
560 * @return $fileSize Size of currently loaded file
562 public function getFileSize () {
563 // Call iterator's method
564 return $this->getIteratorInstance()->getFileSize();
568 * Writes given raw data to the file and returns a gap position and length
570 * @param $groupId Group identifier
571 * @param $hash Hash from encoded value
572 * @param $encoded Encoded value to be written to the file
573 * @return $data Gap position and length of the raw data
575 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
577 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,encoded()=%d - CALLED!', __METHOD__, __LINE__, $groupId, $hash, strlen($encoded)));
579 // Raw data been written to the file
580 $rawData = sprintf('%s%s%s%s%s',
582 BaseBinaryFile::SEPARATOR_GROUP_HASH,
584 BaseBinaryFile::SEPARATOR_HASH_VALUE,
589 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
591 // Search for next free gap
592 $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
594 // Gap position cannot be smaller than header length + 1
595 assert($gapPosition > $this->getIteratorInstance()->getHeaderSize());
598 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gapPosition=%s', __METHOD__, __LINE__, $groupId, $hash, $gapPosition));
600 // Then write the data at that gap
601 $this->getIteratorInstance()->writeData($gapPosition, $rawData);
604 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d - EXIT!', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
606 // Return gap position, hash and length of raw data
608 self::ARRAY_INDEX_GAP_POSITION => $gapPosition,
609 self::ARRAY_INDEX_HASH => $hash,
610 self::ARRAY_INDEX_DATA_LENGTH => strlen($rawData)