3 namespace Org\Mxchange\CoreFramework\Index;
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;
16 * A general index class
18 * @author Roland Haeder <webmaster@ship-simu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.ship-simu.org
24 * This program is free software: you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation, either version 3 of the License, or
27 * (at your option) any later version.
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 abstract class BaseIndex extends BaseFrameworkSystem {
39 * Magic for this index
41 const INDEX_MAGIC = 'INDEXv0.1';
44 * Separator group->hash
46 const SEPARATOR_GROUP_HASH = 0x01;
49 * Separator hash->gap position
51 const SEPARATOR_HASH_GAP_POSITION = 0x02;
54 * Separator gap position->length
56 const SEPARATOR_GAP_LENGTH = 0x03;
59 * Protected constructor
61 * @param $className Name of the class
64 protected function __construct ($className) {
65 // Call parent constructor
66 parent::__construct($className);
70 * Reads the file header
74 public function readFileHeader () {
75 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
77 // First rewind to beginning as the header sits at the beginning ...
78 $this->getIteratorInstance()->rewind();
80 // Then read it (see constructor for calculation)
81 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
82 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
84 // Have all requested bytes been read?
85 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
86 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
88 // Last character must be the separator
89 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
90 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
91 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
93 // Okay, then remove it
94 $data = substr($data, 0, -1);
96 // And update seek position
97 $this->getIteratorInstance()->updateSeekPosition();
105 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
108 $this->getIteratorInstance()->setHeader($header);
110 // Check if the array has only 3 elements
111 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, true)));
112 assert(count($header) == 2);
113 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
116 assert($header[0] == self::INDEX_MAGIC);
117 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
119 // Check length of count
120 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
121 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
124 $header[1] = hex2bin($header[1]);
126 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
130 * Flushes the file header
134 public function flushFileHeader () {
135 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
137 // Put all informations together
138 $header = sprintf('%s%s%s%s',
142 // Separator header data
143 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
146 str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
148 // Separator header<->entries
149 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
152 // Write it to disk (header is always at seek position 0)
153 $this->getIteratorInstance()->writeData(0, $header, false);
155 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
159 * Initializes this index
161 * @param $fileInfoInstance An instance of a SplFileInfo class
163 * @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 protected function initIndex (SplFileInfo $fileInfoInstance) {
166 // Get a file i/o pointer instance for index file
167 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileInfoInstance, $this));
169 // Get iterator instance
170 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
172 // Is the instance implementing the right interface?
173 assert($iteratorInstance instanceof SeekableWritableFileIterator);
176 $this->setIteratorInstance($iteratorInstance);
178 // Calculate header size
179 $this->getIteratorInstance()->setHeaderSize(
180 strlen(self::INDEX_MAGIC) +
181 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
182 BaseBinaryFile::LENGTH_COUNT +
183 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
186 // Init counters and gaps array
187 $this->getIteratorInstance()->initCountersGapsArray();
189 // Is the file's header initialized?
190 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
191 // No, then create it (which may pre-allocate the index)
192 $this->getIteratorInstance()->createFileHeader();
194 // And pre-allocate a bit
195 $this->getIteratorInstance()->preAllocateFile('index');
198 // Load the file header
199 $this->readFileHeader();
201 // Count all entries in file
202 $this->getIteratorInstance()->analyzeFile();
206 * Calculates minimum length for one entry/block
208 * @return $length Minimum length for one entry/block
210 public function calculateMinimumBlockLength () {
212 $length = BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) + BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
219 * Determines whether the EOF has been reached
221 * @return $isEndOfFileReached Whether the EOF has been reached
222 * @throws UnsupportedOperationException If this method is called
224 public function isEndOfFileReached () {
225 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
229 * Initializes counter for valid entries, arrays for damaged entries and
230 * an array for gap seek positions. If you call this method on your own,
231 * please re-analyze the file structure. So you are better to call
232 * analyzeFile() instead of this method.
235 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
237 public function initCountersGapsArray () {
238 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
242 * Getter for header size
244 * @return $totalEntries Size of file header
245 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
247 public final function getHeaderSize () {
248 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
252 * Setter for header size
254 * @param $headerSize Size of file header
256 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
258 public final function setHeaderSize ($headerSize) {
259 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
263 * Getter for header array
265 * @return $totalEntries Size of file header
266 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
268 public final function getHeader () {
269 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
275 * @param $header Array for a file header
277 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
279 public final function setHeader (array $header) {
280 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
284 * Updates seekPosition attribute from file to avoid to much access on file.
287 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
289 public function updateSeekPosition () {
290 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
294 * Getter for total entries
296 * @return $totalEntries Total entries in this file
297 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
299 public final function getCounter () {
300 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
304 * "Getter" for file size
306 * @return $fileSize Size of currently loaded file
308 public function getFileSize () {
309 // Call iterator's method
310 return $this->getIteratorInstance()->getFileSize();
314 * Writes data at given position
316 * @param $seekPosition Seek position
317 * @param $data Data to be written
318 * @param $flushHeader Whether to flush the header (default: flush)
320 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
322 public function writeData ($seekPosition, $data, $flushHeader = true) {
323 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
324 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
328 * Writes given value to the file and returns a hash and gap position for it
330 * @param $groupId Group identifier
331 * @param $value Value to be added to the stack
332 * @return $data Hash and gap position
333 * @throws UnsupportedOperationException If this method is called
335 public function writeValueToFile ($groupId, $value) {
336 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',value[' . gettype($value) . ']=' . print_r($value, true));
337 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
341 * Writes given raw data to the file and returns a gap position and length
343 * @param $groupId Group identifier
344 * @param $hash Hash from encoded value
345 * @param $encoded Encoded value to be written to the file
346 * @return $data Gap position and length of the raw data
348 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
349 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
350 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);