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