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