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 for header data
33 const SEPARATOR_HEADER_DATA = 0x01;
36 * Separator header->entries
38 const SEPARATOR_HEADER_ENTRIES = 0x02;
41 * Separator hash->name
43 const SEPARATOR_HASH_NAME = 0x03;
48 const LENGTH_NAME = 10;
51 * Protected constructor
53 * @param $className Name of the class
56 protected function __construct ($className) {
57 // Call parent constructor
58 parent::__construct($className);
60 // Calculate header size
62 strlen(self::STACK_MAGIC) +
63 strlen(self::SEPARATOR_HEADER_DATA) +
65 strlen(self::SEPARATOR_HEADER_DATA) +
66 self::LENGTH_POSITION +
67 strlen(self::SEPARATOR_HEADER_ENTRIES)
70 // Init counters and gaps array
71 $this->initCountersGapsArray();
75 * Reads the file header
79 protected function readFileHeader () {
80 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
82 // First rewind to beginning as the header sits at the beginning ...
83 $this->getIteratorInstance()->rewind();
85 // Then read it (see constructor for calculation)
86 $data = $this->getIteratorInstance()->read($this->getHeaderSize());
87 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getHeaderSize()));
89 // Have all requested bytes been read?
90 assert(strlen($data) == $this->getHeaderSize());
91 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
93 // Last character must be the separator
94 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
95 assert(substr($data, -1, 1) == chr(self::SEPARATOR_HEADER_ENTRIES));
96 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
98 // Okay, then remove it
99 $data = substr($data, 0, -1);
101 // And update seek position
102 $this->updateSeekPosition();
109 * 2 => current seek position
111 $header = explode(chr(self::SEPARATOR_HEADER_DATA), $data);
114 $this->setHeader($header);
116 // Check if the array has only 3 elements
117 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
118 assert(count($header) == 3);
119 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
122 assert($header[0] == self::STACK_MAGIC);
123 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
125 // Check length of count and seek position
126 assert(strlen($header[1]) == self::LENGTH_COUNT);
127 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
128 assert(strlen($header[2]) == self::LENGTH_POSITION);
129 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
131 // Decode count and seek position
132 $header[1] = hex2bin($header[1]);
133 $header[2] = hex2bin($header[2]);
135 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
139 * Flushes the file header
143 protected function flushFileHeader () {
144 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
146 // Put all informations together
147 $header = sprintf('%s%s%s%s%s%s',
151 // Separator magic<->count
152 chr(self::SEPARATOR_HEADER_DATA),
154 // Total entries (will be zero) and pad it to 20 chars
155 str_pad($this->dec2hex($this->getCounter()), self::LENGTH_COUNT, '0', STR_PAD_LEFT),
157 // Separator count<->seek position
158 chr(self::SEPARATOR_HEADER_DATA),
160 // Position (will be zero)
161 str_pad($this->dec2hex($this->getSeekPosition(), 2), self::LENGTH_POSITION, '0', STR_PAD_LEFT),
163 // Separator position<->entries
164 chr(self::SEPARATOR_HEADER_ENTRIES)
167 // Write it to disk (header is always at seek position 0)
168 $this->writeData(0, $header, FALSE);
170 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
174 * Analyzes entries in stack file. This will count all found (and valid)
175 * entries, mark invalid as damaged and count gaps ("fragmentation"). If
176 * only gaps are found, the file is considered as "virgin" (no entries).
180 private function analyzeFile () {
181 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
183 // Make sure the file is initialized
184 assert($this->isFileInitialized());
186 // Init counters and gaps array
187 $this->initCountersGapsArray();
189 // Output message (as this may take some time)
190 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
192 // First rewind to the begining
193 $this->getIteratorInstance()->rewind();
195 // Then try to load all entries
196 while ($this->getIteratorInstance()->next()) {
198 $current = $this->getIteratorInstance()->current();
201 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] current=%s', __METHOD__, __LINE__, print_r($current, TRUE)));
204 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
208 * Initializes this file-based stack.
210 * @param $fileName File name of this stack
211 * @param $type Type of this stack (e.g. url_source for URL sources)
213 * @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.
215 protected function initFileStack ($fileName, $type) {
216 // Get a stack file instance
217 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName));
219 // Get iterator instance
220 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_io_iterator_class', array($fileInstance));
222 // Is the instance implementing the right interface?
223 assert($iteratorInstance instanceof SeekableWritableFileIterator);
226 $this->setIteratorInstance($iteratorInstance);
228 // Is the file's header initialized?
229 if (!$this->isFileHeaderInitialized()) {
230 // No, then create it (which may pre-allocate the stack)
231 $this->createFileHeader();
233 // And pre-allocate a bit
234 $this->preAllocateFile('file_stack');
237 // Load the file header
238 $this->readFileHeader();
240 // Count all entries in file
241 $this->analyzeFile();
244 * Get stack index instance. This can be used for faster
245 * "defragmentation" and startup.
247 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
250 $this->setIndexInstance($indexInstance);
254 * Calculates minimum length for one entry
256 * @return $length Minimum length for one entry
258 protected function caluclateMinimumFileEntryLength () {
260 $length = self::getHashLength() + strlen(self::SEPARATOR_HASH_NAME) + self::LENGTH_NAME + 1;
267 * Adds a value to given stack
269 * @param $stackerName Name of the stack
270 * @param $value Value to add to this stacker
272 * @throws FullStackerException If the stack is full
274 protected function addValue ($stackerName, $value) {
276 if ($this->isStackFull($stackerName)) {
278 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
281 // Now add the value to the stack
282 $this->partialStub('stackerName=' . $stackerName . ',value[]=' . gettype($value));
286 * Get last value from named stacker
288 * @param $stackerName Name of the stack
289 * @return $value Value of last added value
290 * @throws EmptyStackerException If the stack is empty
292 protected function getLastValue ($stackerName) {
293 // Is the stack not yet initialized or full?
294 if ($this->isStackEmpty($stackerName)) {
295 // Throw an exception
296 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
299 // Now get the last value
300 $this->partialStub('stackerName=' . $stackerName);
308 * Get first value from named stacker
310 * @param $stackerName Name of the stack
311 * @return $value Value of last added value
312 * @throws EmptyStackerException If the stack is empty
314 protected function getFirstValue ($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 get the first value
322 $this->partialStub('stackerName=' . $stackerName);
330 * "Pops" last entry from stack
332 * @param $stackerName Name of the stack
333 * @return $value Value "poped" from array
334 * @throws EmptyStackerException If the stack is empty
336 protected function popLast ($stackerName) {
337 // Is the stack not yet initialized or full?
338 if ($this->isStackEmpty($stackerName)) {
339 // Throw an exception
340 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
343 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
344 $this->partialStub('stackerName=' . $stackerName);
349 * "Pops" first entry from stack
351 * @param $stackerName Name of the stack
352 * @return $value Value "shifted" from array
353 * @throws EmptyStackerException If the named stacker is empty
355 protected function popFirst ($stackerName) {
356 // Is the stack not yet initialized or full?
357 if ($this->isStackEmpty($stackerName)) {
358 // Throw an exception
359 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
362 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
363 $this->partialStub('stackerName=' . $stackerName);
368 * Checks whether the given stack is full
370 * @param $stackerName Name of the stack
371 * @return $isFull Whether the stack is full
373 protected function isStackFull ($stackerName) {
374 // File-based stacks will only run full if the disk space is low.
375 // @TODO Please implement this, returning FALSE
383 * Checks whether the given stack is empty
385 * @param $stackerName Name of the stack
386 * @return $isEmpty Whether the stack is empty
387 * @throws NoStackerException If given stack is missing
389 public function isStackEmpty ($stackerName) {
390 // So, is the stack empty?
391 $isEmpty = (($this->getStackCount($stackerName)) == 0);
398 * Initializes given stacker
400 * @param $stackerName Name of the stack
401 * @param $forceReInit Force re-initialization
403 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
405 public function initStack ($stackerName, $forceReInit = FALSE) {
406 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
410 * Initializes all stacks
413 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
415 public function initStacks (array $stacks, $forceReInit = FALSE) {
416 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
420 * Checks whether the given stack is initialized (set in array $stackers)
422 * @param $stackerName Name of the stack
423 * @return $isInitialized Whether the stack is initialized
424 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
426 public function isStackInitialized ($stackerName) {
427 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
431 * Getter for size of given stack (array count)
433 * @param $stackerName Name of the stack
434 * @return $count Size of stack (array count)
436 public function getStackCount ($stackerName) {
437 // Now, simply return the found count value, this must be up-to-date then!
438 return $this->getCounter();