3 namespace CoreFramework\Index;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Filesystem\File\BaseBinaryFile;
8 use CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
9 use CoreFramework\Object\BaseFrameworkSystem;
12 * A general index class
14 * @author Roland Haeder <webmaster@ship-simu.org>
16 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
17 * @license GNU GPL 3.0 or any newer version
18 * @link http://www.ship-simu.org
20 * This program is free software: you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation, either version 3 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <http://www.gnu.org/licenses/>.
33 class BaseIndex extends BaseFrameworkSystem {
35 * Magic for this index
37 const INDEX_MAGIC = 'INDEXv0.1';
40 * Separator group->hash
42 const SEPARATOR_GROUP_HASH = 0x01;
45 * Separator hash->gap position
47 const SEPARATOR_HASH_GAP_POSITION = 0x02;
50 * Separator gap position->length
52 const SEPARATOR_GAP_LENGTH = 0x03;
55 * Protected constructor
57 * @param $className Name of the class
60 protected function __construct ($className) {
61 // Call parent constructor
62 parent::__construct($className);
66 * Reads the file header
70 public function readFileHeader () {
71 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
73 // First rewind to beginning as the header sits at the beginning ...
74 $this->getIteratorInstance()->rewind();
76 // Then read it (see constructor for calculation)
77 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
78 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
80 // Have all requested bytes been read?
81 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
82 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
84 // Last character must be the separator
85 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
86 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
87 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
89 // Okay, then remove it
90 $data = substr($data, 0, -1);
92 // And update seek position
93 $this->getIteratorInstance()->updateSeekPosition();
101 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
104 $this->getIteratorInstance()->setHeader($header);
106 // Check if the array has only 3 elements
107 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
108 assert(count($header) == 2);
109 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
112 assert($header[0] == self::INDEX_MAGIC);
113 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
115 // Check length of count
116 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
117 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
120 $header[1] = hex2bin($header[1]);
122 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
126 * Flushes the file header
130 public function flushFileHeader () {
131 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
133 // Put all informations together
134 $header = sprintf('%s%s%s%s',
138 // Separator header data
139 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
142 str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
144 // Separator header<->entries
145 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
148 // Write it to disk (header is always at seek position 0)
149 $this->getIteratorInstance()->writeData(0, $header, FALSE);
151 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
155 * Initializes this index
157 * @param $fileName File name of this index
159 * @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.
161 protected function initIndex ($fileName) {
162 // Append index file extension
163 $fileName .= $this->getConfigInstance()->getConfigEntry('index_extension');
165 // Get a file i/o pointer instance for index file
166 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileName, $this));
168 // Get iterator instance
169 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
171 // Is the instance implementing the right interface?
172 assert($iteratorInstance instanceof SeekableWritableFileIterator);
175 $this->setIteratorInstance($iteratorInstance);
177 // Calculate header size
178 $this->getIteratorInstance()->setHeaderSize(
179 strlen(self::INDEX_MAGIC) +
180 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
181 BaseBinaryFile::LENGTH_COUNT +
182 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
185 // Init counters and gaps array
186 $this->getIteratorInstance()->initCountersGapsArray();
188 // Is the file's header initialized?
189 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
190 // No, then create it (which may pre-allocate the index)
191 $this->getIteratorInstance()->createFileHeader();
193 // And pre-allocate a bit
194 $this->getIteratorInstance()->preAllocateFile('index');
197 // Load the file header
198 $this->readFileHeader();
200 // Count all entries in file
201 $this->getIteratorInstance()->analyzeFile();
205 * Calculates minimum length for one entry/block
207 * @return $length Minimum length for one entry/block
209 public function calculateMinimumBlockLength () {
211 $length = BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) + BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
218 * Determines whether the EOF has been reached
220 * @return $isEndOfFileReached Whether the EOF has been reached
221 * @throws UnsupportedOperationException If this method is called
223 public function isEndOfFileReached () {
224 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
228 * Getter for file name
230 * @return $fileName The current file name
231 * @throws UnsupportedOperationException If this method is called
233 public function getFileName () {
234 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
238 * Initializes counter for valid entries, arrays for damaged entries and
239 * an array for gap seek positions. If you call this method on your own,
240 * please re-analyze the file structure. So you are better to call
241 * analyzeFile() instead of this method.
244 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
246 public function initCountersGapsArray () {
247 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
251 * Getter for header size
253 * @return $totalEntries Size of file header
254 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
256 public final function getHeaderSize () {
257 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
261 * Setter for header size
263 * @param $headerSize Size of file header
265 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
267 public final function setHeaderSize ($headerSize) {
268 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
272 * Getter for header array
274 * @return $totalEntries Size of file header
275 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
277 public final function getHeader () {
278 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
284 * @param $header Array for a file header
286 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
288 public final function setHeader (array $header) {
289 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
293 * Updates seekPosition attribute from file to avoid to much access on file.
296 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
298 public function updateSeekPosition () {
299 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
303 * Getter for total entries
305 * @return $totalEntries Total entries in this file
306 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
308 public final function getCounter () {
309 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
313 * "Getter" for file size
315 * @return $fileSize Size of currently loaded file
317 public function getFileSize () {
318 // Call iterator's method
319 return $this->getIteratorInstance()->getFileSize();
323 * Writes data at given position
325 * @param $seekPosition Seek position
326 * @param $data Data to be written
327 * @param $flushHeader Whether to flush the header (default: flush)
329 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
331 public function writeData ($seekPosition, $data, $flushHeader = TRUE) {
332 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
333 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
337 * Writes given value to the file and returns a hash and gap position for it
339 * @param $groupId Group identifier
340 * @param $value Value to be added to the stack
341 * @return $data Hash and gap position
342 * @throws UnsupportedOperationException If this method is called
344 public function writeValueToFile ($groupId, $value) {
345 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
346 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
350 * Writes given raw data to the file and returns a gap position and length
352 * @param $groupId Group identifier
353 * @param $hash Hash from encoded value
354 * @param $encoded Encoded value to be written to the file
355 * @return $data Gap position and length of the raw data
357 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
358 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
359 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);