1f83f37ba96146b092101346989bfe6201dd8fc8
[core.git] / inc / classes / main / index / class_BaseIndex.php
1 <?php
2 /**
3  * A general index class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Core Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24 class BaseIndex extends BaseFrameworkSystem {
25         /**
26          * Magic for this index
27          */
28         const INDEX_MAGIC = 'INDEXv0.1';
29
30         /**
31          * Separator for header data
32          */
33         const SEPARATOR_HEADER_DATA = 0x01;
34
35         /**
36          * Separator header->entries
37          */
38         const SEPARATOR_HEADER_ENTRIES = 0x02;
39
40         /**
41          * Protected constructor
42          *
43          * @param       $className      Name of the class
44          * @return      void
45          */
46         protected function __construct ($className) {
47                 // Call parent constructor
48                 parent::__construct($className);
49
50                 // Calculate header size
51                 $this->setHeaderSize(
52                         strlen(self::INDEX_MAGIC) +
53                         strlen(self::SEPARATOR_HEADER_DATA) +
54                         self::LENGTH_COUNT +
55                         strlen(self::SEPARATOR_HEADER_ENTRIES)
56                 );
57
58                 // Init counters and gaps array
59                 $this->initCountersGapsArray();
60         }
61
62         /**
63          * Reads the file header
64          *
65          * @return      void
66          */
67         private 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->headerSize);
75                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->headerSize));
76
77                 // Have all requested bytes been read?
78                 assert(strlen($data) == $this->headerSize);
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(self::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->updateSeekPosition();
91
92                 /*
93                  * Now split it:
94                  *
95                  * 0 => magic
96                  * 1 => total entries
97                  */
98                 $this->header = explode(chr(self::SEPARATOR_HEADER_DATA), $data);
99
100                 // Check if the array has only 3 elements
101                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($this->header), print_r($this->header, TRUE)));
102                 assert(count($this->header) == 2);
103                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
104
105                 // Check magic
106                 assert($this->header[0] == self::INDEX_MAGIC);
107                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
108
109                 // Check length of count
110                 assert(strlen($this->header[1]) == self::LENGTH_COUNT);
111                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
112
113                 // Decode count
114                 $this->header[1] = hex2bin($this->header[1]);
115
116                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
117         }
118
119         /**
120          * Checks whether the file header is initialized
121          *
122          * @return      $isInitialized  Whether the file header is initialized
123          */
124         private function isFileHeaderInitialized () {
125                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
126                 // Default is not initialized
127                 $isInitialized = FALSE;
128
129                 // Is the file initialized?
130                 if ($this->isFileInitialized()) {
131                         // Some bytes has been written, so rewind to start of it.
132                         $rewindStatus = $this->getIteratorInstance()->rewind();
133                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] rewindStatus=%s', __METHOD__, __LINE__, $rewindStatus));
134
135                         // Is the rewind() call successfull?
136                         if ($rewindStatus != 1) {
137                                 // Something bad happened
138                                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Could not rewind().', __METHOD__, __LINE__));
139                         } // END - if
140
141                         // Read file header
142                         $this->readFileHeader();
143
144                         // The above method does already check the header
145                         $isInitialized = TRUE;
146                 } // END - if
147
148                 // Return result
149                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
150                 return $isInitialized;
151         }
152
153         /**
154          * Flushes the file header
155          *
156          * @return      void
157          */
158         private function flushFileHeader () {
159                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
160
161                 // Put all informations together
162                 $header = sprintf('%s%s',
163                         // Magic
164                         self::INDEX_MAGIC,
165
166                         // Separator position<->entries
167                         chr(self::SEPARATOR_HEADER_ENTRIES)
168                 );
169
170                 // Write it to disk (header is always at seek position 0)
171                 $this->writeData(0, $header);
172
173                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
174         }
175
176         /**
177          * Analyzes entries in index file. This will count all found (and valid)
178          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
179          * only gaps are found, the file is considered as "virgin" (no entries).
180          *
181          * @return      void
182          */
183         private function analyzeFile () {
184                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
185
186                 // Make sure the file is initialized
187                 assert($this->isFileInitialized());
188
189                 // Init counters and gaps array
190                 $this->initGapsArray();
191
192                 // Output message (as this may take some time)
193                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
194
195                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
196         }
197
198         /**
199          * Initializes this index
200          *
201          * @param       $fileName       File name of this index
202          * @return      void
203          */
204         protected function initIndex ($fileName) {
205                 // Get a file i/o pointer instance for index file
206                 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileName));
207
208                 // Get iterator instance
209                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_io_iterator_class', array($pointerInstance));
210
211                 // Is the instance implementing the right interface?
212                 assert($iteratorInstance instanceof SeekableWritableFileIterator);
213
214                 // Set iterator here
215                 $this->setIteratorInstance($iteratorInstance);
216
217                 // Is the file's header initialized?
218                 if (!$this->isFileHeaderInitialized()) {
219                         // No, then create it (which may pre-allocate the index)
220                         $this->createFileHeader();
221
222                         // And pre-allocate a bit
223                         $this->preAllocateFile('index');
224                 } // END - if
225
226                 // Load the file header
227                 $this->readFileHeader();
228
229                 // Count all entries in file
230                 $this->analyzeFile();
231         }
232 }
233
234 // [EOF]
235 ?>