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