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