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));
237 // Now add the value to the file stack (which returns a hash)
238 $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
240 // Add the hash and gap position to the index
241 $this->getIndexInstance()->addHashToIndex($stackerName, $data);
245 * Get last value from named stacker
247 * @param $stackerName Name of the stack
248 * @return $value Value of last added value
249 * @throws EmptyStackerException If the stack is empty
251 protected function getLastValue ($stackerName) {
252 // Is the stack not yet initialized or full?
253 if ($this->isStackEmpty($stackerName)) {
254 // Throw an exception
255 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
258 // Now get the last value
259 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
267 * Get first value from named stacker
269 * @param $stackerName Name of the stack
270 * @return $value Value of last added value
271 * @throws EmptyStackerException If the stack is empty
273 protected function getFirstValue ($stackerName) {
274 // Is the stack not yet initialized or full?
275 if ($this->isStackEmpty($stackerName)) {
276 // Throw an exception
277 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
280 // Now get the first value
281 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
289 * "Pops" last entry from stack
291 * @param $stackerName Name of the stack
292 * @return $value Value "poped" from array
293 * @throws EmptyStackerException If the stack is empty
295 protected function popLast ($stackerName) {
296 // Is the stack not yet initialized or full?
297 if ($this->isStackEmpty($stackerName)) {
298 // Throw an exception
299 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
302 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
303 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
308 * "Pops" first entry from stack
310 * @param $stackerName Name of the stack
311 * @return $value Value "shifted" from array
312 * @throws EmptyStackerException If the named stacker is empty
314 protected function popFirst ($stackerName) {
315 // Is the stack not yet initialized or full?
316 if ($this->isStackEmpty($stackerName)) {
317 // Throw an exception
318 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
321 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
322 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
327 * Checks whether the given stack is full
329 * @param $stackerName Name of the stack
330 * @return $isFull Whether the stack is full
332 protected function isStackFull ($stackerName) {
333 // File-based stacks will only run full if the disk space is low.
334 // @TODO Please implement this, returning FALSE
342 * Checks whether the given stack is empty
344 * @param $stackerName Name of the stack
345 * @return $isEmpty Whether the stack is empty
346 * @throws NoStackerException If given stack is missing
348 public function isStackEmpty ($stackerName) {
349 // So, is the stack empty?
350 $isEmpty = (($this->getStackCount($stackerName)) == 0);
357 * Initializes given stacker
359 * @param $stackerName Name of the stack
360 * @param $forceReInit Force re-initialization
362 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
364 public function initStack ($stackerName, $forceReInit = FALSE) {
365 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
369 * Initializes all stacks
372 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
374 public function initStacks (array $stacks, $forceReInit = FALSE) {
375 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
379 * Checks whether the given stack is initialized (set in array $stackers)
381 * @param $stackerName Name of the stack
382 * @return $isInitialized Whether the stack is initialized
383 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
385 public function isStackInitialized ($stackerName) {
386 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
390 * Determines whether the EOF has been reached
392 * @return $isEndOfFileReached Whether the EOF has been reached
393 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
395 public function isEndOfFileReached () {
396 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
400 * Getter for file name
402 * @return $fileName The current file name
403 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
405 public function getFileName () {
406 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
410 * Getter for size of given stack (array count)
412 * @param $stackerName Name of the stack
413 * @return $count Size of stack (array count)
415 public function getStackCount ($stackerName) {
416 // Now, simply return the found count value, this must be up-to-date then!
417 return $this->getIteratorInstance()->getCounter();
421 * Calculates minimum length for one entry/block
423 * @return $length Minimum length for one entry/block
425 public function calculateMinimumBlockLength () {
428 // Length of entry group
429 BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
431 self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
433 strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
440 * Initializes counter for valid entries, arrays for damaged entries and
441 * an array for gap seek positions. If you call this method on your own,
442 * please re-analyze the file structure. So you are better to call
443 * analyzeFile() instead of this method.
446 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
448 public function initCountersGapsArray () {
449 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
453 * Getter for header size
455 * @return $totalEntries Size of file header
456 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
458 public final function getHeaderSize () {
459 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
463 * Setter for header size
465 * @param $headerSize Size of file header
467 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
469 public final function setHeaderSize ($headerSize) {
470 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
474 * Getter for header array
476 * @return $totalEntries Size of file header
477 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
479 public final function getHeader () {
480 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
486 * @param $header Array for a file header
488 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
490 public final function setHeader (array $header) {
491 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
495 * Updates seekPosition attribute from file to avoid to much access on file.
498 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
500 public function updateSeekPosition () {
501 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
505 * Getter for total entries
507 * @return $totalEntries Total entries in this file
508 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
510 public final function getCounter () {
511 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
515 * Writes data at given position
517 * @param $seekPosition Seek position
518 * @param $data Data to be written
519 * @param $flushHeader Whether to flush the header (default: flush)
521 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
523 public function writeData ($seekPosition, $data, $flushHeader = TRUE) {
524 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
525 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
529 * Writes given value to the file and returns a hash and gap position for it
531 * @param $groupId Group identifier
532 * @param $value Value to be added to the stack
533 * @return $data Hash and gap position
534 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
536 public function writeValueToFile ($groupId, $value) {
537 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,value[%s]=%s', __METHOD__, __LINE__, $groupId, gettype($value), print_r($value, TRUE)));
538 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
542 * Searches for next suitable gap the given length of data can fit in
543 * including padding bytes.
545 * @param $length Length of raw data
546 * @return $seekPosition Found next gap's seek position
547 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
549 public function searchNextGap ($length) {
550 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] length=%s', __METHOD__, __LINE__, $length));
551 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
555 * "Getter" for file size
557 * @return $fileSize Size of currently loaded file
559 public function getFileSize () {
560 // Call iterator's method
561 return $this->getIteratorInstance()->getFileSize();
565 * Writes given raw data to the file and returns a gap position and length
567 * @param $groupId Group identifier
568 * @param $hash Hash from encoded value
569 * @param $encoded Encoded value to be written to the file
570 * @return $data Gap position and length of the raw data
572 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
574 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,encoded()=%s - CALLED!', __METHOD__, __LINE__, $groupId, $hash, strlen($encoded)));
576 // Raw data been written to the file
577 $rawData = sprintf('%s%s%s%s%s',
579 BaseBinaryFile::SEPARATOR_GROUP_HASH,
581 BaseBinaryFile::SEPARATOR_HASH_VALUE,
586 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%s', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
588 // Search for next free gap
589 $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
591 // Gap position cannot be smaller than header length + 1
592 assert($gapPosition > $this->getIteratorInstance()->getHeaderSize());
595 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gapPosition=%s', __METHOD__, __LINE__, $groupId, $hash, $gapPosition));
597 // Then write the data at that gap
598 $this->getIteratorInstance()->writeData($gapPosition, $rawData);
601 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%s - EXIT!', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
603 // Return gap position, hash and length of raw data
605 self::ARRAY_INDEX_GAP_POSITION => $gapPosition,
606 self::ARRAY_INDEX_HASH => $hash,
607 self::ARRAY_INDEX_DATA_LENGTH => strlen($rawData)