]> git.mxchange.org Git - core.git/blob - framework/main/classes/index/class_BaseIndex.php
Some updates:
[core.git] / framework / main / classes / index / class_BaseIndex.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Index;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
7 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
8 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
9 use Org\Mxchange\CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
10 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
11
12 // Import SPL stuff
13 use \SplFileInfo;
14
15 /**
16  * A general index class
17  *
18  * @author              Roland Haeder <webmaster@ship-simu.org>
19  * @version             0.0.0
20 <<<<<<< HEAD:framework/main/classes/index/class_BaseIndex.php
21  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
22 =======
23  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
24 >>>>>>> Some updates::inc/main/classes/index/class_BaseIndex.php
25  * @license             GNU GPL 3.0 or any newer version
26  * @link                http://www.ship-simu.org
27  *
28  * This program is free software: you can redistribute it and/or modify
29  * it under the terms of the GNU General Public License as published by
30  * the Free Software Foundation, either version 3 of the License, or
31  * (at your option) any later version.
32  *
33  * This program is distributed in the hope that it will be useful,
34  * but WITHOUT ANY WARRANTY; without even the implied warranty of
35  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
36  * GNU General Public License for more details.
37  *
38  * You should have received a copy of the GNU General Public License
39  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
40  */
41 abstract class BaseIndex extends BaseFrameworkSystem {
42         /**
43          * Magic for this index
44          */
45         const INDEX_MAGIC = 'INDEXv0.1';
46
47         /**
48          * Separator group->hash
49          */
50         const SEPARATOR_GROUP_HASH = 0x01;
51
52         /**
53          * Separator hash->gap position
54          */
55         const SEPARATOR_HASH_GAP_POSITION = 0x02;
56
57         /**
58          * Separator gap position->length
59          */
60         const SEPARATOR_GAP_LENGTH = 0x03;
61
62         /**
63          * Protected constructor
64          *
65          * @param       $className      Name of the class
66          * @return      void
67          */
68         protected function __construct ($className) {
69                 // Call parent constructor
70                 parent::__construct($className);
71         }
72
73         /**
74          * Reads the file header
75          *
76          * @return      void
77          */
78         public function readFileHeader () {
79                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
80
81                 // First rewind to beginning as the header sits at the beginning ...
82                 $this->getIteratorInstance()->rewind();
83
84                 // Then read it (see constructor for calculation)
85                 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
86                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
87
88                 // Have all requested bytes been read?
89                 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
90                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
91
92                 // Last character must be the separator
93                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
94                 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
95                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
96
97                 // Okay, then remove it
98                 $data = substr($data, 0, -1);
99
100                 // And update seek position
101                 $this->getIteratorInstance()->updateSeekPosition();
102
103                 /*
104                  * Now split it:
105                  *
106                  * 0 => magic
107                  * 1 => total entries
108                  */
109                 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
110
111                 // Set it here
112                 $this->getIteratorInstance()->setHeader($header);
113
114                 // Check if the array has only 3 elements
115                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, true)));
116                 assert(count($header) == 2);
117                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
118
119                 // Check magic
120                 assert($header[0] == self::INDEX_MAGIC);
121                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
122
123                 // Check length of count
124                 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
125                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
126
127                 // Decode count
128                 $header[1] = hex2bin($header[1]);
129
130                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
131         }
132
133         /**
134          * Flushes the file header
135          *
136          * @return      void
137          */
138         public function flushFileHeader () {
139                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
140
141                 // Put all informations together
142                 $header = sprintf('%s%s%s%s',
143                         // Magic
144                         self::INDEX_MAGIC,
145
146                         // Separator header data
147                         chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
148
149                         // Total entries
150                         str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
151
152                         // Separator header<->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__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
160         }
161
162         /**
163          * Initializes this index
164          *
165          * @param       $fileInfoInstance       An instance of a SplFileInfo class
166          * @return      void
167          * @todo        Currently the index file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole index file.
168          */
169         protected function initIndex (SplFileInfo $fileInfoInstance) {
170                 // Get a file i/o pointer instance for index file
171                 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileInfoInstance, $this));
172
173                 // Get iterator instance
174                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
175
176                 // Is the instance implementing the right interface?
177                 assert($iteratorInstance instanceof SeekableWritableFileIterator);
178
179                 // Set iterator here
180                 $this->setIteratorInstance($iteratorInstance);
181
182                 // Calculate header size
183                 $this->getIteratorInstance()->setHeaderSize(
184                         strlen(self::INDEX_MAGIC) +
185                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
186                         BaseBinaryFile::LENGTH_COUNT +
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 index)
196                         $this->getIteratorInstance()->createFileHeader();
197
198                         // And pre-allocate a bit
199                         $this->getIteratorInstance()->preAllocateFile('index');
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         /**
210          * Calculates minimum length for one entry/block
211          *
212          * @return      $length         Minimum length for one entry/block
213          */
214         public function calculateMinimumBlockLength () {
215                 // Calulcate it
216                 $length = BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) + BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
217
218                 // Return it
219                 return $length;
220         }
221
222         /**
223          * Determines whether the EOF has been reached
224          *
225          * @return      $isEndOfFileReached             Whether the EOF has been reached
226          * @throws      UnsupportedOperationException   If this method is called
227          */
228         public function isEndOfFileReached () {
229                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
230         }
231
232         /**
233          * Initializes counter for valid entries, arrays for damaged entries and
234          * an array for gap seek positions. If you call this method on your own,
235          * please re-analyze the file structure. So you are better to call
236          * analyzeFile() instead of this method.
237          *
238          * @return      void
239          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
240          */
241         public function initCountersGapsArray () {
242                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
243         }
244
245         /**
246          * Getter for header size
247          *
248          * @return      $totalEntries   Size of file header
249          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
250          */
251         public final function getHeaderSize () {
252                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
253         }
254
255         /**
256          * Setter for header size
257          *
258          * @param       $headerSize             Size of file header
259          * @return      void
260          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
261          */
262         public final function setHeaderSize ($headerSize) {
263                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
264         }
265
266         /**
267          * Getter for header array
268          *
269          * @return      $totalEntries   Size of file header
270          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
271          */
272         public final function getHeader () {
273                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
274         }
275
276         /**
277          * Setter for header
278          *
279          * @param       $header         Array for a file header
280          * @return      void
281          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
282          */
283         public final function setHeader (array $header) {
284                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
285         }
286
287         /**
288          * Updates seekPosition attribute from file to avoid to much access on file.
289          *
290          * @return      void
291          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
292          */
293         public function updateSeekPosition () {
294                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
295         }
296
297         /**
298          * Getter for total entries
299          *
300          * @return      $totalEntries   Total entries in this file
301          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
302          */
303         public final function getCounter () {
304                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
305         }
306
307         /**
308          * "Getter" for file size
309          *
310          * @return      $fileSize       Size of currently loaded file
311          */
312         public function getFileSize () {
313                 // Call iterator's method
314                 return $this->getIteratorInstance()->getFileSize();
315         }
316
317         /**
318          * Writes data at given position
319          *
320          * @param       $seekPosition   Seek position
321          * @param       $data                   Data to be written
322          * @param       $flushHeader    Whether to flush the header (default: flush)
323          * @return      void
324          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
325          */
326         public function writeData ($seekPosition, $data, $flushHeader = true) {
327                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
328                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
329         }
330
331         /**
332          * Writes given value to the file and returns a hash and gap position for it
333          *
334          * @param       $groupId        Group identifier
335          * @param       $value          Value to be added to the stack
336          * @return      $data           Hash and gap position
337          * @throws      UnsupportedOperationException   If this method is called
338          */
339         public function writeValueToFile ($groupId, $value) {
340                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',value[' . gettype($value) . ']=' . print_r($value, true));
341                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
342         }
343
344         /**
345          * Writes given raw data to the file and returns a gap position and length
346          *
347          * @param       $groupId        Group identifier
348          * @param       $hash           Hash from encoded value
349          * @param       $encoded        Encoded value to be written to the file
350          * @return      $data           Gap position and length of the raw data
351          */
352         public function writeDataToFreeGap ($groupId, $hash, $encoded) {
353                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
354                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
355         }
356
357 }