3 namespace CoreFramework\Stack\File;
6 * A general file-based stack class
8 * @author Roland Haeder <webmaster@ship-simu.org>
10 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
11 * @license GNU GPL 3.0 or any newer version
12 * @link http://www.ship-simu.org
14 * This program is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 class BaseFileStack extends BaseStacker {
29 * Magic for this stack
31 const STACK_MAGIC = 'STACKv0.1';
34 * Name of array index for gap position
36 const ARRAY_INDEX_GAP_POSITION = 'gap';
39 * Name of array index for hash
41 const ARRAY_INDEX_HASH = 'hash';
44 * Name of array index for length of raw data
46 const ARRAY_INDEX_DATA_LENGTH = 'length';
49 * Protected constructor
51 * @param $className Name of the class
54 protected function __construct ($className) {
55 // Call parent constructor
56 parent::__construct($className);
60 * Reads the file header
63 * @todo To hard assertions here, better rewrite them to exceptions
65 public function readFileHeader () {
66 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
68 // First rewind to beginning as the header sits at the beginning ...
69 $this->getIteratorInstance()->rewind();
71 // Then read it (see constructor for calculation)
72 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
73 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
75 // Have all requested bytes been read?
76 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
77 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
79 // Last character must be the separator
80 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
81 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
82 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
84 // Okay, then remove it
85 $data = substr($data, 0, -1);
87 // And update seek position
88 $this->getIteratorInstance()->updateSeekPosition();
95 * 2 => current seek position
97 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
100 $this->getIteratorInstance()->setHeader($header);
102 // Check if the array has only 3 elements
103 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
104 assert(count($header) == 3);
105 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
108 assert($header[0] == self::STACK_MAGIC);
109 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
111 // Check length of count and seek position
112 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
113 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
114 assert(strlen($header[2]) == BaseBinaryFile::LENGTH_POSITION);
115 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
117 // Decode count and seek position
118 $header[1] = hex2bin($header[1]);
119 $header[2] = hex2bin($header[2]);
121 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
125 * Flushes the file header
129 public function flushFileHeader () {
130 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
132 // Put all informations together
133 $header = sprintf('%s%s%s%s%s%s',
137 // Separator magic<->count
138 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
140 // Total entries (will be zero) and pad it to 20 chars
141 str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
143 // Separator count<->seek position
144 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
146 // Position (will be zero)
147 str_pad($this->dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
149 // Separator position<->entries
150 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
153 // Write it to disk (header is always at seek position 0)
154 $this->getIteratorInstance()->writeData(0, $header, FALSE);
156 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
160 * Initializes this file-based stack.
162 * @param $fileName File name of this stack
163 * @param $type Type of this stack (e.g. url_source for URL sources)
165 * @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.
167 protected function initFileStack ($fileName, $type) {
168 // Get a stack file instance
169 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName, $this));
171 // Get iterator instance
172 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
174 // Is the instance implementing the right interface?
175 assert($iteratorInstance instanceof SeekableWritableFileIterator);
178 $this->setIteratorInstance($iteratorInstance);
180 // Calculate header size
181 $this->getIteratorInstance()->setHeaderSize(
182 strlen(self::STACK_MAGIC) +
183 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
184 BaseBinaryFile::LENGTH_COUNT +
185 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
186 BaseBinaryFile::LENGTH_POSITION +
187 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
190 // Init counters and gaps array
191 $this->getIteratorInstance()->initCountersGapsArray();
193 // Is the file's header initialized?
194 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
195 // No, then create it (which may pre-allocate the stack)
196 $this->getIteratorInstance()->createFileHeader();
198 // And pre-allocate a bit
199 $this->getIteratorInstance()->preAllocateFile('file_stack');
202 // Load the file header
203 $this->readFileHeader();
205 // Count all entries in file
206 $this->getIteratorInstance()->analyzeFile();
209 * Get stack index instance. This can be used for faster
210 * "defragmentation" and startup.
212 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
215 $this->setIndexInstance($indexInstance);
219 * Adds a value to given stack
221 * @param $stackerName Name of the stack
222 * @param $value Value to add to this stacker
224 * @throws FullStackerException If the stack is full
226 protected function addValue ($stackerName, $value) {
228 if ($this->isStackFull($stackerName)) {
230 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
234 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
236 // No objects/resources are allowed as their serialization takes to long
237 assert(!is_object($value));
238 assert(!is_resource($value));
241 * Now add the value to the file stack which returns gap position, a
242 * hash and length of the raw data.
244 $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
246 // Add the hash and gap position to the index
247 $this->getIndexInstance()->addHashToIndex($stackerName, $data);
251 * Get last value from named stacker
253 * @param $stackerName Name of the stack
254 * @return $value Value of last added value
255 * @throws EmptyStackerException If the stack is empty
257 protected function getLastValue ($stackerName) {
258 // Is the stack not yet initialized or full?
259 if ($this->isStackEmpty($stackerName)) {
260 // Throw an exception
261 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
264 // Now get the last value
265 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
273 * Get first value from named stacker
275 * @param $stackerName Name of the stack
276 * @return $value Value of last added value
277 * @throws EmptyStackerException If the stack is empty
279 protected function getFirstValue ($stackerName) {
280 // Is the stack not yet initialized or full?
281 if ($this->isStackEmpty($stackerName)) {
282 // Throw an exception
283 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
286 // Now get the first value
287 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
295 * "Pops" last entry from stack
297 * @param $stackerName Name of the stack
298 * @return $value Value "poped" from array
299 * @throws EmptyStackerException If the stack is empty
301 protected function popLast ($stackerName) {
302 // Is the stack not yet initialized or full?
303 if ($this->isStackEmpty($stackerName)) {
304 // Throw an exception
305 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
308 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
309 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
314 * "Pops" first entry from stack
316 * @param $stackerName Name of the stack
317 * @return $value Value "shifted" from array
318 * @throws EmptyStackerException If the named stacker is empty
320 protected function popFirst ($stackerName) {
321 // Is the stack not yet initialized or full?
322 if ($this->isStackEmpty($stackerName)) {
323 // Throw an exception
324 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
327 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
328 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
333 * Checks whether the given stack is full
335 * @param $stackerName Name of the stack
336 * @return $isFull Whether the stack is full
338 protected function isStackFull ($stackerName) {
339 // File-based stacks will only run full if the disk space is low.
340 // @TODO Please implement this, returning FALSE
348 * Checks whether the given stack is empty
350 * @param $stackerName Name of the stack
351 * @return $isEmpty Whether the stack is empty
352 * @throws NoStackerException If given stack is missing
354 public function isStackEmpty ($stackerName) {
355 // So, is the stack empty?
356 $isEmpty = (($this->getStackCount($stackerName)) == 0);
363 * Initializes given stacker
365 * @param $stackerName Name of the stack
366 * @param $forceReInit Force re-initialization
368 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
370 public function initStack ($stackerName, $forceReInit = FALSE) {
371 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
375 * Initializes all stacks
378 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
380 public function initStacks (array $stacks, $forceReInit = FALSE) {
381 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
385 * Checks whether the given stack is initialized (set in array $stackers)
387 * @param $stackerName Name of the stack
388 * @return $isInitialized Whether the stack is initialized
389 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
391 public function isStackInitialized ($stackerName) {
392 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
396 * Determines whether the EOF has been reached
398 * @return $isEndOfFileReached Whether the EOF has been reached
399 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
401 public function isEndOfFileReached () {
402 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
406 * Getter for file name
408 * @return $fileName The current file name
409 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
411 public function getFileName () {
412 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
416 * Getter for size of given stack (array count)
418 * @param $stackerName Name of the stack
419 * @return $count Size of stack (array count)
421 public function getStackCount ($stackerName) {
422 // Now, simply return the found count value, this must be up-to-date then!
423 return $this->getIteratorInstance()->getCounter();
427 * Calculates minimum length for one entry/block
429 * @return $length Minimum length for one entry/block
431 public function calculateMinimumBlockLength () {
434 // Length of entry group
435 BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
437 self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
439 strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
446 * Initializes counter for valid entries, arrays for damaged entries and
447 * an array for gap seek positions. If you call this method on your own,
448 * please re-analyze the file structure. So you are better to call
449 * analyzeFile() instead of this method.
452 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
454 public function initCountersGapsArray () {
455 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
459 * Getter for header size
461 * @return $totalEntries Size of file header
462 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
464 public final function getHeaderSize () {
465 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
469 * Setter for header size
471 * @param $headerSize Size of file header
473 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
475 public final function setHeaderSize ($headerSize) {
476 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
480 * Getter for header array
482 * @return $totalEntries Size of file header
483 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
485 public final function getHeader () {
486 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
492 * @param $header Array for a file header
494 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
496 public final function setHeader (array $header) {
497 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
501 * Updates seekPosition attribute from file to avoid to much access on file.
504 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
506 public function updateSeekPosition () {
507 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
511 * Getter for total entries
513 * @return $totalEntries Total entries in this file
514 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
516 public final function getCounter () {
517 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
521 * Writes data at given position
523 * @param $seekPosition Seek position
524 * @param $data Data to be written
525 * @param $flushHeader Whether to flush the header (default: flush)
527 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
529 public function writeData ($seekPosition, $data, $flushHeader = TRUE) {
530 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
531 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
535 * Writes given value to the file and returns a hash and gap position for it
537 * @param $groupId Group identifier
538 * @param $value Value to be added to the stack
539 * @return $data Hash and gap position
540 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
542 public function writeValueToFile ($groupId, $value) {
543 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,value[%s]=%s', __METHOD__, __LINE__, $groupId, gettype($value), print_r($value, TRUE)));
544 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
548 * Searches for next suitable gap the given length of data can fit in
549 * including padding bytes.
551 * @param $length Length of raw data
552 * @return $seekPosition Found next gap's seek position
553 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
555 public function searchNextGap ($length) {
556 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] length=%s', __METHOD__, __LINE__, $length));
557 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
561 * "Getter" for file size
563 * @return $fileSize Size of currently loaded file
565 public function getFileSize () {
566 // Call iterator's method
567 return $this->getIteratorInstance()->getFileSize();
571 * Writes given raw data to the file and returns a gap position and length
573 * @param $groupId Group identifier
574 * @param $hash Hash from encoded value
575 * @param $encoded Encoded value to be written to the file
576 * @return $data Gap position and length of the raw data
578 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
580 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,encoded()=%d - CALLED!', __METHOD__, __LINE__, $groupId, $hash, strlen($encoded)));
582 // Raw data been written to the file
583 $rawData = sprintf('%s%s%s%s%s',
585 BaseBinaryFile::SEPARATOR_GROUP_HASH,
587 BaseBinaryFile::SEPARATOR_HASH_VALUE,
592 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
594 // Search for next free gap
595 $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
597 // Gap position cannot be smaller than header length + 1
598 assert($gapPosition > $this->getIteratorInstance()->getHeaderSize());
601 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gapPosition=%s', __METHOD__, __LINE__, $groupId, $hash, $gapPosition));
603 // Then write the data at that gap
604 $this->getIteratorInstance()->writeData($gapPosition, $rawData);
607 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d - EXIT!', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
609 // Return gap position, hash and length of raw data
611 self::ARRAY_INDEX_GAP_POSITION => $gapPosition,
612 self::ARRAY_INDEX_HASH => $hash,
613 self::ARRAY_INDEX_DATA_LENGTH => strlen($rawData)