046ec73613b8910e413be723767eff1d7ae4a2d8
[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
59         /**
60          * Reads the file header
61          *
62          * @return      void
63          */
64         private function readFileHeader () {
65                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
66
67                 // First rewind to beginning as the header sits at the beginning ...
68                 $this->getIteratorInstance()->rewind();
69
70                 // Then read it (see constructor for calculation)
71                 $data = $this->getIteratorInstance()->read($this->headerSize);
72                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->headerSize));
73
74                 // Have all requested bytes been read?
75                 assert(strlen($data) == $this->headerSize);
76                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
77
78                 // Last character must be the separator
79                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
80                 assert(substr($data, -1, 1) == chr(self::SEPARATOR_HEADER_ENTRIES));
81                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
82
83                 // Okay, then remove it
84                 $data = substr($data, 0, -1);
85
86                 // And update seek position
87                 $this->updateSeekPosition();
88
89                 /*
90                  * Now split it:
91                  *
92                  * 0 => magic
93                  * 1 => total entries
94                  */
95                 $this->header = explode(chr(self::SEPARATOR_HEADER_DATA), $data);
96
97                 // Check if the array has only 3 elements
98                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($this->header), print_r($this->header, TRUE)));
99                 assert(count($this->header) == 2);
100                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
101
102                 // Check magic
103                 assert($this->header[0] == self::INDEX_MAGIC);
104                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
105
106                 // Check length of count
107                 assert(strlen($this->header[1]) == self::LENGTH_COUNT);
108                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
109
110                 // Decode count
111                 $this->header[1] = hex2bin($this->header[1]);
112
113                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
114         }
115
116         /**
117          * Checks whether the file header is initialized
118          *
119          * @return      $isInitialized  Whether the file header is initialized
120          */
121         private function isFileHeaderInitialized () {
122                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
123                 // Default is not initialized
124                 $isInitialized = FALSE;
125
126                 // Is the file initialized?
127                 if ($this->isFileInitialized()) {
128                         // Some bytes has been written, so rewind to start of it.
129                         $rewindStatus = $this->getIteratorInstance()->rewind();
130                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] rewindStatus=%s', __METHOD__, __LINE__, $rewindStatus));
131
132                         // Is the rewind() call successfull?
133                         if ($rewindStatus != 1) {
134                                 // Something bad happened
135                                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Could not rewind().', __METHOD__, __LINE__));
136                         } // END - if
137
138                         // Read file header
139                         $this->readFileHeader();
140
141                         // The above method does already check the header
142                         $isInitialized = TRUE;
143                 } // END - if
144
145                 // Return result
146                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
147                 return $isInitialized;
148         }
149
150         /**
151          * Flushes the file header
152          *
153          * @return      void
154          */
155         private function flushFileHeader () {
156                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
157
158                 // Put all informations together
159                 $header = sprintf('%s%s',
160                         // Magic
161                         self::INDEX_MAGIC,
162
163                         // Separator position<->entries
164                         chr(self::SEPARATOR_HEADER_ENTRIES)
165                 );
166
167                 // Write it to disk (header is always at seek position 0)
168                 $this->writeData(0, $header);
169
170                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
171         }
172
173         /**
174          * Analyzes entries in index file. This will count all found (and valid)
175          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
176          * only gaps are found, the file is considered as "virgin" (no entries).
177          *
178          * @return      void
179          */
180         private function analyzeFile () {
181                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
182
183                 // Make sure the file is initialized
184                 assert($this->isFileInitialized());
185
186                 // Init counters and gaps array
187                 $this->initGapsArray();
188
189                 // Output message (as this may take some time)
190                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
191
192                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
193         }
194
195         /**
196          * Initializes this index
197          *
198          * @param       $fileName       File name of this index
199          * @return      void
200          */
201         protected function initIndex ($fileName) {
202                 // Get a file i/o pointer instance for index file
203                 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileName));
204
205                 // Get iterator instance
206                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_io_iterator_class', array($pointerInstance));
207
208                 // Is the instance implementing the right interface?
209                 assert($iteratorInstance instanceof SeekableWritableFileIterator);
210
211                 // Set iterator here
212                 $this->setIteratorInstance($iteratorInstance);
213
214                 // Is the file's header initialized?
215                 if (!$this->isFileHeaderInitialized()) {
216                         // No, then create it (which may pre-allocate the index)
217                         $this->createFileHeader();
218
219                         // And pre-allocate a bit
220                         $this->preAllocateFile('index');
221                 } // END - if
222
223                 // Load the file header
224                 $this->readFileHeader();
225
226                 // Count all entries in file
227                 $this->analyzeFile();
228         }
229 }
230
231 // [EOF]
232 ?>