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