]> git.mxchange.org Git - core.git/blob - inc/main/classes/index/class_BaseIndex.php
c6be82903147f1642cee54b4b8a5447754df433f
[core.git] / inc / main / classes / index / class_BaseIndex.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Index;
4
5 // Import framework stuff
6 use CoreFramework\Object\BaseFrameworkSystem;
7
8 /**
9  * A general index 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 BaseIndex extends BaseFrameworkSystem {
31         /**
32          * Magic for this index
33          */
34         const INDEX_MAGIC = 'INDEXv0.1';
35
36         /**
37          * Separator group->hash
38          */
39         const SEPARATOR_GROUP_HASH = 0x01;
40
41         /**
42          * Separator hash->gap position
43          */
44         const SEPARATOR_HASH_GAP_POSITION = 0x02;
45
46         /**
47          * Separator gap position->length
48          */
49         const SEPARATOR_GAP_LENGTH = 0x03;
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          */
67         public function readFileHeader () {
68                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
69
70                 // First rewind to beginning as the header sits at the beginning ...
71                 $this->getIteratorInstance()->rewind();
72
73                 // Then read it (see constructor for calculation)
74                 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
75                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
76
77                 // Have all requested bytes been read?
78                 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
79                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
80
81                 // Last character must be the separator
82                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
83                 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
84                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
85
86                 // Okay, then remove it
87                 $data = substr($data, 0, -1);
88
89                 // And update seek position
90                 $this->getIteratorInstance()->updateSeekPosition();
91
92                 /*
93                  * Now split it:
94                  *
95                  * 0 => magic
96                  * 1 => total entries
97                  */
98                 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
99
100                 // Set it here
101                 $this->getIteratorInstance()->setHeader($header);
102
103                 // Check if the array has only 3 elements
104                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
105                 assert(count($header) == 2);
106                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
107
108                 // Check magic
109                 assert($header[0] == self::INDEX_MAGIC);
110                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
111
112                 // Check length of count
113                 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
114                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
115
116                 // Decode count
117                 $header[1] = hex2bin($header[1]);
118
119                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
120         }
121
122         /**
123          * Flushes the file header
124          *
125          * @return      void
126          */
127         public function flushFileHeader () {
128                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
129
130                 // Put all informations together
131                 $header = sprintf('%s%s%s%s',
132                         // Magic
133                         self::INDEX_MAGIC,
134
135                         // Separator header data
136                         chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
137
138                         // Total entries
139                         str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
140
141                         // Separator header<->entries
142                         chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
143                 );
144
145                 // Write it to disk (header is always at seek position 0)
146                 $this->getIteratorInstance()->writeData(0, $header, FALSE);
147
148                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
149         }
150
151         /**
152          * Initializes this index
153          *
154          * @param       $fileName       File name of this index
155          * @return      void
156          * @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.
157          */
158         protected function initIndex ($fileName) {
159                 // Append index file extension
160                 $fileName .= $this->getConfigInstance()->getConfigEntry('index_extension');
161
162                 // Get a file i/o pointer instance for index file
163                 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileName, $this));
164
165                 // Get iterator instance
166                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
167
168                 // Is the instance implementing the right interface?
169                 assert($iteratorInstance instanceof SeekableWritableFileIterator);
170
171                 // Set iterator here
172                 $this->setIteratorInstance($iteratorInstance);
173
174                 // Calculate header size
175                 $this->getIteratorInstance()->setHeaderSize(
176                         strlen(self::INDEX_MAGIC) +
177                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
178                         BaseBinaryFile::LENGTH_COUNT +
179                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
180                 );
181
182                 // Init counters and gaps array
183                 $this->getIteratorInstance()->initCountersGapsArray();
184
185                 // Is the file's header initialized?
186                 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
187                         // No, then create it (which may pre-allocate the index)
188                         $this->getIteratorInstance()->createFileHeader();
189
190                         // And pre-allocate a bit
191                         $this->getIteratorInstance()->preAllocateFile('index');
192                 } // END - if
193
194                 // Load the file header
195                 $this->readFileHeader();
196
197                 // Count all entries in file
198                 $this->getIteratorInstance()->analyzeFile();
199         }
200
201         /**
202          * Calculates minimum length for one entry/block
203          *
204          * @return      $length         Minimum length for one entry/block
205          */
206         public function calculateMinimumBlockLength () {
207                 // Calulcate it
208                 $length = BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) + BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
209
210                 // Return it
211                 return $length;
212         }
213
214         /**
215          * Determines whether the EOF has been reached
216          *
217          * @return      $isEndOfFileReached             Whether the EOF has been reached
218          * @throws      UnsupportedOperationException   If this method is called
219          */
220         public function isEndOfFileReached () {
221                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
222         }
223
224         /**
225          * Getter for file name
226          *
227          * @return      $fileName       The current file name
228          * @throws      UnsupportedOperationException   If this method is called
229          */
230         public function getFileName () {
231                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
232         }
233
234         /**
235          * Initializes counter for valid entries, arrays for damaged entries and
236          * an array for gap seek positions. If you call this method on your own,
237          * please re-analyze the file structure. So you are better to call
238          * analyzeFile() instead of this method.
239          *
240          * @return      void
241          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
242          */
243         public function initCountersGapsArray () {
244                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
245         }
246
247         /**
248          * Getter for header size
249          *
250          * @return      $totalEntries   Size of file header
251          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
252          */
253         public final function getHeaderSize () {
254                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
255         }
256
257         /**
258          * Setter for header size
259          *
260          * @param       $headerSize             Size of file header
261          * @return      void
262          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
263          */
264         public final function setHeaderSize ($headerSize) {
265                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
266         }
267
268         /**
269          * Getter for header array
270          *
271          * @return      $totalEntries   Size of file header
272          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
273          */
274         public final function getHeader () {
275                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
276         }
277
278         /**
279          * Setter for header
280          *
281          * @param       $header         Array for a file header
282          * @return      void
283          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
284          */
285         public final function setHeader (array $header) {
286                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
287         }
288
289         /**
290          * Updates seekPosition attribute from file to avoid to much access on file.
291          *
292          * @return      void
293          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
294          */
295         public function updateSeekPosition () {
296                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
297         }
298
299         /**
300          * Getter for total entries
301          *
302          * @return      $totalEntries   Total entries in this file
303          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
304          */
305         public final function getCounter () {
306                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
307         }
308
309         /**
310          * "Getter" for file size
311          *
312          * @return      $fileSize       Size of currently loaded file
313          */
314         public function getFileSize () {
315                 // Call iterator's method
316                 return $this->getIteratorInstance()->getFileSize();
317         }
318
319         /**
320          * Writes data at given position
321          *
322          * @param       $seekPosition   Seek position
323          * @param       $data                   Data to be written
324          * @param       $flushHeader    Whether to flush the header (default: flush)
325          * @return      void
326          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
327          */
328         public function writeData ($seekPosition, $data, $flushHeader = TRUE) {
329                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
330                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
331         }
332
333         /**
334          * Writes given value to the file and returns a hash and gap position for it
335          *
336          * @param       $groupId        Group identifier
337          * @param       $value          Value to be added to the stack
338          * @return      $data           Hash and gap position
339          * @throws      UnsupportedOperationException   If this method is called
340          */
341         public function writeValueToFile ($groupId, $value) {
342                 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
343                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
344         }
345
346         /**
347          * Writes given raw data to the file and returns a gap position and length
348          *
349          * @param       $groupId        Group identifier
350          * @param       $hash           Hash from encoded value
351          * @param       $encoded        Encoded value to be written to the file
352          * @return      $data           Gap position and length of the raw data
353          */
354         public function writeDataToFreeGap ($groupId, $hash, $encoded) {
355                 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
356                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
357         }
358
359 }