]> git.mxchange.org Git - core.git/blob - framework/main/classes/stacker/file/class_BaseFileStack.php
5513c77759fad82ed0eeacafd84c6871692976e2
[core.git] / framework / main / classes / stacker / file / class_BaseFileStack.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Stack\File;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\Stack\File\FileStackIndexFactory;
7 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
9 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
10 use Org\Mxchange\CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
11 use Org\Mxchange\CoreFramework\Stack\BaseStacker;
12 use Org\Mxchange\CoreFramework\Stack\File\InvalidMagicException;
13 use Org\Mxchange\CoreFramework\Stack\File\StackableFile;
14 use Org\Mxchange\CoreFramework\Traits\Index\IndexableTrait;
15 use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
16 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
17
18 // Import SPL stuff
19 use \InvalidArgumentException;
20 use \SplFileInfo;
21 use \UnexpectedValueException;
22
23 /**
24  * A general file-based stack class
25  *
26  * @author              Roland Haeder <webmaster@ship-simu.org>
27  * @version             0.0.0
28  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
29  * @license             GNU GPL 3.0 or any newer version
30  * @link                http://www.ship-simu.org
31  *
32  * This program is free software: you can redistribute it and/or modify
33  * it under the terms of the GNU General Public License as published by
34  * the Free Software Foundation, either version 3 of the License, or
35  * (at your option) any later version.
36  *
37  * This program is distributed in the hope that it will be useful,
38  * but WITHOUT ANY WARRANTY; without even the implied warranty of
39  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
40  * GNU General Public License for more details.
41  *
42  * You should have received a copy of the GNU General Public License
43  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
44  */
45 abstract class BaseFileStack extends BaseStacker implements StackableFile {
46         // Load traits
47         use IteratorTrait;
48
49         // Exception codes
50         const EXCEPTION_BAD_MAGIC = 0xe100;
51
52         /**
53          * Protected constructor
54          *
55          * @param       $className      Name of the class
56          * @return      void
57          */
58         protected function __construct (string $className) {
59                 // Call parent constructor
60                 parent::__construct($className);
61         }
62
63         /**
64          * Reads the file header
65          *
66          * @return      void
67          * @todo        To hard assertions here, better rewrite them to exceptions
68          * @throws      UnexpectedValueException        If header is not proper length
69          * @throws      InvalidMagicException   If a bad magic was found
70          */
71         public function readFileHeader () {
72                 // First rewind to beginning as the header sits at the beginning ...
73                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
74                 $this->getIteratorInstance()->rewind();
75
76                 // Then read it (see constructor for calculation)
77                 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
78                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getHeaderSize()));
79
80                 // Have all requested bytes been read?
81                 if (strlen($data) != $this->getIteratorInstance()->getHeaderSize()) {
82                         // Bad data length
83                         throw new UnexpectedValueException(sprintf('data(%d)=%s does not match iteratorInstance->headerSize=%d',
84                                 strlen($data),
85                                 $data,
86                                 $this->getIteratorInstance()->getHeaderSize()
87                         ));
88                 }
89
90                 // Last character must be the separator
91                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: data(-1)=%s', dechex(ord(substr($data, -1, 1)))));
92                 if (substr($data, -1, 1) !== chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)) {
93                         // Not valid separator
94                         throw new UnexpectedValueException(sprintf('data=%s does not have separator=%s at the end.',
95                                 $data,
96                                 BaseBinaryFile::SEPARATOR_HEADER_ENTRIES
97                         ));
98                 }
99
100                 // Okay, then remove it
101                 $data = substr($data, 0, -1);
102
103                 // And update seek position
104                 $this->getIteratorInstance()->updateSeekPosition();
105
106                 /*
107                  * Now split it:
108                  *
109                  * 0 => magic
110                  * 1 => total entries
111                  * 2 => current seek position
112                  */
113                 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
114
115                 // Check if the array has only 3 elements
116                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: header(%d)=%s', count($header), print_r($header, true)));
117                 if (count($header) != 3) {
118                         // Header array count is not expected
119                         throw new UnexpectedValueException(sprintf('data=%s has %d elements, expected 3',
120                                 $data,
121                                 count($header)
122                         ));
123                 } elseif ($header[0] != StackableFile::STACK_MAGIC) {
124                         // Bad magic
125                         throw new InvalidMagicException($data, self::EXCEPTION_BAD_MAGIC);
126                 }
127
128                 // Check length of count and seek position
129                 if (strlen($header[1]) != BaseBinaryFile::LENGTH_COUNT) {
130                         // Count length not valid
131                         throw new UnexpectedValueException(sprintf('header[1](%d)=%s is not expected %d length',
132                                 strlen($header[1]),
133                                 $header[1],
134                                 BaseBinaryFile::LENGTH_COUNT
135                         ));
136                 } elseif (strlen($header[1]) != BaseBinaryFile::LENGTH_POSITION) {
137                         // Position length not valid
138                         throw new UnexpectedValueException(sprintf('header[2](%d)=%s is not expected %d length',
139                                 strlen($header[1]),
140                                 $header[1],
141                                 BaseBinaryFile::LENGTH_POSITION
142                         ));
143                 }
144
145                 // Decode count and seek position
146                 $header[1] = hex2bin($header[1]);
147                 $header[2] = hex2bin($header[2]);
148
149                 // Set header here
150                 $this->getIteratorInstance()->setHeader($header);
151
152                 // Trace message
153                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: EXIT!', __METHOD__, __LINE__));
154         }
155
156         /**
157          * Flushes the file header
158          *
159          * @return      void
160          */
161         public function flushFileHeader () {
162                 // Put all informations together
163                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
164                 $header = sprintf('%s%s%s%s%s%s',
165                         // Magic
166                         StackableFile::STACK_MAGIC,
167
168                         // Separator magic<->count
169                         chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
170
171                         // Total entries (will be zero) and pad it to 20 chars
172                         str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
173
174                         // Separator count<->seek position
175                         chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
176
177                         // Position (will be zero)
178                         str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
179
180                         // Separator position<->entries
181                         chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
182                 );
183
184                 // Write it to disk (header is always at seek position 0)
185                 $this->getIteratorInstance()->writeData(0, $header, false);
186
187                 // Trace message
188                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
189         }
190
191         /**
192          * Initializes this file-based stack.
193          *
194          * @param       $fileInfoInstance       An instance of a SplFileInfo class
195          * @param       $type           Type of this stack (e.g. url_source for URL sources)
196          * @return      void
197          * @throws      InvalidArgumentException        If a parameter is invalid
198          * @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.
199          */
200         protected function initFileStack (SplFileInfo $fileInfoInstance, string $type) {
201                 // Validate parameter
202                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: fileInfoInstance[%s]=%s,type=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance, $type));
203                 if (empty($type)) {
204                         // Invalid parameter
205                         throw new InvalidArgumentException('Parameter "type" is empty');
206                 }
207
208                 // Get a stack file instance
209                 $stackInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileInfoInstance, $this));
210
211                 // Get iterator instance
212                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($stackInstance));
213
214                 // Set iterator here
215                 $this->setIteratorInstance($iteratorInstance);
216
217                 // Calculate header size
218                 $this->getIteratorInstance()->setHeaderSize(
219                         strlen(StackableFile::STACK_MAGIC) +
220                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
221                         BaseBinaryFile::LENGTH_COUNT +
222                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
223                         BaseBinaryFile::LENGTH_POSITION +
224                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
225                 );
226
227                 // Init counters and gaps array
228                 $this->getIteratorInstance()->initCountersGapsArray();
229
230                 // Is the file's header initialized?
231                 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
232                         // No, then create it (which may pre-allocate the stack)
233                         $this->getIteratorInstance()->createFileHeader();
234
235                         // And pre-allocate a bit
236                         $this->getIteratorInstance()->preAllocateFile('file_stack');
237                 }
238
239                 // Load the file header
240                 $this->readFileHeader();
241
242                 // Count all entries in file
243                 $this->getIteratorInstance()->analyzeFile();
244
245                 /*
246                  * Get stack index instance. This can be used for faster
247                  * "defragmentation" and startup.
248                  */
249                 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileInfoInstance, $type);
250
251                 // And set it here
252                 $this->setIndexInstance($indexInstance);
253
254                 // Trace message
255                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
256         }
257
258         /**
259          * Adds a value to given stack
260          *
261          * @param       $stackerName    Name of the stack
262          * @param       $value                  Value to add to this stacker
263          * @return      void
264          * @throws      FullStackerException    If the stack is full
265          * @throws      InvalidArgumentException        If a parameter is not valid
266          * @throws      InvalidArgumentException        Not all variable types are wanted here
267          */
268         protected function addValue (string $stackerName, $value) {
269                 // Validate parameter
270                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s,value[%s]=%s - CALLED!', $stackerName, gettype($value), print_r($value, true)));
271                 if (empty($stackerName)) {
272                         // No empty stack name
273                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
274                 } elseif ($this->isStackFull($stackerName)) {
275                         // Stacker is full
276                         throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
277                 } elseif (is_resource($value) || is_object($value)) {
278                         // Not wanted type
279                         throw new InvalidArgumentException(sprintf('value[]=%s is not supported', gettype($value)));
280                 }
281
282                 /*
283                  * Now add the value to the file stack which returns gap position, a
284                  * hash and length of the raw data.
285                  */
286                 $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
287
288                 // Add the hash and gap position to the index
289                 $this->getIndexInstance()->addHashToIndex($stackerName, $data);
290
291                 // Trace message
292                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
293         }
294
295         /**
296          * Get last value from named stacker
297          *
298          * @param       $stackerName    Name of the stack
299          * @return      $value                  Value of last added value
300          * @throws      InvalidArgumentException        If a parameter is not valid
301          * @throws      BadMethodCallException  If the stack is empty
302          */
303         protected function getLastValue (string $stackerName) {
304                 // Validate parameter
305                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
306                 if (empty($stackerName)) {
307                         // No empty stack name
308                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
309                 } elseif ($this->isStackEmpty($stackerName)) {
310                         // Throw an exception
311                         throw new BadMethodCallException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
312                 }
313
314                 // Now get the last value
315                 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
316                 $value = NULL;
317
318                 // Return it
319                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
320                 return $value;
321         }
322
323         /**
324          * Get first value from named stacker
325          *
326          * @param       $stackerName    Name of the stack
327          * @return      $value                  Value of last added value
328          * @throws      InvalidArgumentException        If a parameter is not valid
329          * @throws      BadMethodCallException  If the stack is empty
330          */
331         protected function getFirstValue (string $stackerName) {
332                 // Validate parameter
333                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
334                 if (empty($stackerName)) {
335                         // No empty stack name
336                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
337                 } elseif ($this->isStackEmpty($stackerName)) {
338                         // Throw an exception
339                         throw new BadMethodCallException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
340                 }
341
342                 // Now get the first value
343                 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
344                 $value = NULL;
345
346                 // Return it
347                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
348                 return $value;
349         }
350
351         /**
352          * "Pops" last entry from stack
353          *
354          * @param       $stackerName    Name of the stack
355          * @return      $value                  Value "poped" from array
356          * @throws      InvalidArgumentException        If a parameter is not valid
357          * @throws      BadMethodCallException  If the stack is empty
358          */
359         protected function popLast (string $stackerName) {
360                 // Validate parameter
361                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
362                 if (empty($stackerName)) {
363                         // No empty stack name
364                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
365                 } elseif ($this->isStackEmpty($stackerName)) {
366                         // Throw an exception
367                         throw new BadMethodCallException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
368                 }
369
370                 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
371                 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
372                 return NULL;
373         }
374
375         /**
376          * "Pops" first entry from stack
377          *
378          * @param       $stackerName    Name of the stack
379          * @return      $value                  Value "shifted" from array
380          * @throws      InvalidArgumentException        If a parameter is not valid
381          * @throws      BadMethodCallException  If the named stacker is empty
382          */
383         protected function popFirst (string $stackerName) {
384                 // Validate parameter
385                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
386                 if (empty($stackerName)) {
387                         // No empty stack name
388                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
389                 } elseif ($this->isStackEmpty($stackerName)) {
390                         // Throw an exception
391                         throw new BadMethodCallException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
392                 }
393
394                 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
395                 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
396                 return NULL;
397         }
398
399         /**
400          * Checks whether the given stack is full
401          *
402          * @param       $stackerName    Name of the stack
403          * @return      $isFull                 Whether the stack is full
404          * @throws      InvalidArgumentException        If a parameter is not valid
405          */
406         protected function isStackFull (string $stackerName) {
407                 // Validate parameter
408                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
409                 if (empty($stackerName)) {
410                         // No empty stack name
411                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
412                 }
413
414                 // @TODO Please implement this, returning false
415                 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
416                 $isFull = false;
417
418                 // Return result
419                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: isFull=%d - EXIT!', intval($isFull)));
420                 return $isFull;
421         }
422
423         /**
424          * Checks whether the given stack is empty
425          *
426          * @param       $stackerName            Name of the stack
427          * @return      $isEmpty                        Whether the stack is empty
428          * @throws      InvalidArgumentException        If a parameter is not valid
429          * @throws      BadMethodCallException  If given stack is missing
430          */
431         public function isStackEmpty (string $stackerName) {
432                 // Validate parameter
433                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
434                 if (empty($stackerName)) {
435                         // No empty stack name
436                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
437                 }
438
439                 // So, is the stack empty?
440                 $isEmpty = (($this->getStackCount($stackerName)) == 0);
441
442                 // Return result
443                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: isEmpty=%d - EXIT!', intval($isEmpty)));
444                 return $isEmpty;
445         }
446
447         /**
448          * Initializes given stacker
449          *
450          * @param       $stackerName    Name of the stack
451          * @param       $forceReInit    Force re-initialization
452          * @return      void
453          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
454          */
455         public function initStack (string $stackerName, bool $forceReInit = false) {
456                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
457         }
458
459         /**
460          * Initializes all stacks
461          *
462          * @return      void
463          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
464          */
465         public function initStacks (array $stacks, bool $forceReInit = false) {
466                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
467         }
468
469         /**
470          * Checks whether the given stack is initialized (set in array $stackers)
471          *
472          * @param       $stackerName    Name of the stack
473          * @return      $isInitialized  Whether the stack is initialized
474          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
475          */
476         public function isStackInitialized (string $stackerName) {
477                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
478         }
479
480         /**
481          * Determines whether the EOF has been reached
482          *
483          * @return      $isEndOfFileReached             Whether the EOF has been reached
484          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
485          */
486         public function isEndOfFileReached () {
487                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
488         }
489
490         /**
491          * Getter for size of given stack (array count)
492          *
493          * @param       $stackerName    Name of the stack
494          * @return      $count                  Size of stack (array count)
495          */
496         public function getStackCount (string $stackerName) {
497                 // Now, simply return the found count value, this must be up-to-date then!
498                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
499                 $count = $this->getIteratorInstance()->getCounter();
500
501                 // Return count
502                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: count=%d - EXIT!', $count));
503                 return $count;
504         }
505
506         /**
507          * Calculates minimum length for one entry/block
508          *
509          * @return      $length         Minimum length for one entry/block
510          */
511         public function calculateMinimumBlockLength () {
512                 // Calulcate it
513                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
514                 $length =
515                         // Length of entry group
516                         BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
517                         // Hash + value
518                         self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
519                         // Final separator
520                         strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
521
522                 // Return it
523                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: length=%d - EXIT!', $length));
524                 return $length;
525         }
526
527         /**
528          * Initializes counter for valid entries, arrays for damaged entries and
529          * an array for gap seek positions. If you call this method on your own,
530          * please re-analyze the file structure. So you are better to call
531          * analyzeFile() instead of this method.
532          *
533          * @return      void
534          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
535          */
536         public function initCountersGapsArray () {
537                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
538         }
539
540         /**
541          * Getter for header size
542          *
543          * @return      $totalEntries   Size of file header
544          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
545          */
546         public final function getHeaderSize () {
547                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
548         }
549
550         /**
551          * Setter for header size
552          *
553          * @param       $headerSize             Size of file header
554          * @return      void
555          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
556          */
557         public final function setHeaderSize (int $headerSize) {
558                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
559         }
560
561         /**
562          * Getter for header array
563          *
564          * @return      $totalEntries   Size of file header
565          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
566          */
567         public final function getHeader () {
568                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
569         }
570
571         /**
572          * Setter for header
573          *
574          * @param       $header         Array for a file header
575          * @return      void
576          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
577          */
578         public final function setHeader (array $header) {
579                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
580         }
581
582         /**
583          * Updates seekPosition attribute from file to avoid to much access on file.
584          *
585          * @return      void
586          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
587          */
588         public function updateSeekPosition () {
589                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
590         }
591
592         /**
593          * Getter for total entries
594          *
595          * @return      $totalEntries   Total entries in this file
596          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
597          */
598         public final function getCounter () {
599                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
600         }
601
602         /**
603          * Writes data at given position
604          *
605          * @param       $seekPosition   Seek position
606          * @param       $data                   Data to be written
607          * @param       $flushHeader    Whether to flush the header (default: flush)
608          * @return      void
609          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
610          */
611         public function writeData (int $seekPosition, string $data, bool $flushHeader = true) {
612                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: seekPosition=%s,data[]=%s,flushHeader=%d', $seekPosition, gettype($data), intval($flushHeader)));
613                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
614         }
615
616         /**
617          * Writes given value to the file and returns a hash and gap position for it
618          *
619          * @param       $groupId        Group identifier
620          * @param       $value          Value to be added to the stack
621          * @return      $data           Hash and gap position
622          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
623          */
624         public function writeValueToFile (string $groupId, $value) {
625                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,value[%s]=%s', $groupId, gettype($value), print_r($value, true)));
626                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
627         }
628
629         /**
630          * Searches for next suitable gap the given length of data can fit in
631          * including padding bytes.
632          *
633          * @param       $length                 Length of raw data
634          * @return      $seekPosition   Found next gap's seek position
635          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
636          */
637         public function searchNextGap (int $length) {
638                 // Not supported here
639                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: length=%d - CALLED!', $length));
640                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
641         }
642
643         /**
644          * "Getter" for file size
645          *
646          * @return      $fileSize       Size of currently loaded file
647          */
648         public function getFileSize () {
649                 // Call iterator's method
650                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
651                 $size = $this->getIteratorInstance()->getFileSize();
652
653                 // Return size
654                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: size=%d - EXIT!', $size));
655                 return $size;
656         }
657
658         /**
659          * Writes given raw data to the file and returns a gap position and length
660          *
661          * @param       $groupId        Group identifier
662          * @param       $hash           Hash from encoded value
663          * @param       $encoded        Encoded value to be written to the file
664          * @return      $data           Gap position and length of the raw data
665          */
666         public function writeDataToFreeGap (string $groupId, string $hash, string $encoded) {
667                 // Raw data been written to the file
668                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,encoded()=%d - CALLED!', $groupId, $hash, strlen($encoded)));
669                 $rawData = sprintf('%s%s%s%s%s',
670                         $groupId,
671                         BaseBinaryFile::SEPARATOR_GROUP_HASH,
672                         hex2bin($hash),
673                         BaseBinaryFile::SEPARATOR_HASH_VALUE,
674                         $encoded
675                 );
676
677                 // Search for next free gap
678                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,rawData()=%d', $groupId, $hash, strlen($rawData)));
679                 $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
680
681                 // Gap position cannot be smaller than header length + 1
682                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: gapPosition=%d', $gapPosition));
683                 if ($gapPosition <= $this->getIteratorInstance()->getHeaderSize()) {
684                         // Improper gap position
685                         throw new UnexpectedValueException(sprintf('gapPosition[%s]=%d is not larger than headerSize=%d',
686                                 gettype($gapPosition),
687                                 $gapPosition,
688                                 $this->getIteratorInstance()->getHeaderSize()
689                         ));
690                 }
691
692                 // Then write the data at that gap
693                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,gapPosition=%s', $groupId, $hash, $gapPosition));
694                 $this->getIteratorInstance()->writeData($gapPosition, $rawData);
695
696                 // Return gap position, hash and length of raw data
697                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,rawData()=%d - EXIT!', $groupId, $hash, strlen($rawData)));
698                 return [
699                         self::ARRAY_NAME_GAP_POSITION => $gapPosition,
700                         self::ARRAY_NAME_HASH         => $hash,
701                         self::ARRAY_NAME_DATA_LENGTH  => strlen($rawData),
702                 ];
703         }
704
705 }