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;
11 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
17 * A general index class
19 * @author Roland Haeder <webmaster@ship-simu.org>
21 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
22 * @license GNU GPL 3.0 or any newer version
23 * @link http://www.ship-simu.org
25 * This program is free software: you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation, either version 3 of the License, or
28 * (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <http://www.gnu.org/licenses/>.
38 abstract class BaseIndex extends BaseFrameworkSystem {
40 * Magic for this index
42 const INDEX_MAGIC = 'INDEXv0.1';
45 * Separator group->hash
47 const SEPARATOR_GROUP_HASH = 0x01;
50 * Separator hash->gap position
52 const SEPARATOR_HASH_GAP_POSITION = 0x02;
55 * Separator gap position->length
57 const SEPARATOR_GAP_LENGTH = 0x03;
60 * Protected constructor
62 * @param $className Name of the class
65 protected function __construct (string $className) {
66 // Call parent constructor
67 parent::__construct($className);
71 * Reads the file header
75 public function readFileHeader () {
76 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
78 // First rewind to beginning as the header sits at the beginning ...
79 $this->getIteratorInstance()->rewind();
81 // Then read it (see constructor for calculation)
82 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
83 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
85 // Have all requested bytes been read?
86 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
87 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
89 // Last character must be the separator
90 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
91 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
92 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
94 // Okay, then remove it
95 $data = substr($data, 0, -1);
97 // And update seek position
98 $this->getIteratorInstance()->updateSeekPosition();
106 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
109 $this->getIteratorInstance()->setHeader($header);
111 // Check if the array has only 3 elements
112 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, true)));
113 assert(count($header) == 2);
114 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
117 assert($header[0] == self::INDEX_MAGIC);
118 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
120 // Check length of count
121 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
122 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
125 $header[1] = hex2bin($header[1]);
127 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
131 * Flushes the file header
135 public function flushFileHeader () {
136 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
138 // Put all informations together
139 $header = sprintf('%s%s%s%s',
143 // Separator header data
144 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
147 str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
149 // Separator header<->entries
150 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
153 // Write it to disk (header is always at seek position 0)
154 $this->getIteratorInstance()->writeData(0, $header, false);
156 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
160 * Initializes this index
162 * @param $fileInfoInstance An instance of a SplFileInfo class
164 * @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.
166 protected function initIndex (SplFileInfo $fileInfoInstance) {
167 // Get a file i/o pointer instance for index file
168 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileInfoInstance, $this));
170 // Get iterator instance
171 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
173 // Is the instance implementing the right interface?
174 assert($iteratorInstance instanceof SeekableWritableFileIterator);
177 $this->setIteratorInstance($iteratorInstance);
179 // Calculate header size
180 $this->getIteratorInstance()->setHeaderSize(
181 strlen(self::INDEX_MAGIC) +
182 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
183 BaseBinaryFile::LENGTH_COUNT +
184 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
187 // Init counters and gaps array
188 $this->getIteratorInstance()->initCountersGapsArray();
190 // Is the file's header initialized?
191 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
192 // No, then create it (which may pre-allocate the index)
193 $this->getIteratorInstance()->createFileHeader();
195 // And pre-allocate a bit
196 $this->getIteratorInstance()->preAllocateFile('index');
199 // Load the file header
200 $this->readFileHeader();
202 // Count all entries in file
203 $this->getIteratorInstance()->analyzeFile();
207 * Calculates minimum length for one entry/block
209 * @return $length Minimum length for one entry/block
211 public function calculateMinimumBlockLength () {
213 $length = BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) + BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
220 * Determines whether the EOF has been reached
222 * @return $isEndOfFileReached Whether the EOF has been reached
223 * @throws UnsupportedOperationException If this method is called
225 public function isEndOfFileReached () {
226 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
230 * Initializes counter for valid entries, arrays for damaged entries and
231 * an array for gap seek positions. If you call this method on your own,
232 * please re-analyze the file structure. So you are better to call
233 * analyzeFile() instead of this method.
236 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
238 public function initCountersGapsArray () {
239 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
243 * Getter for header size
245 * @return $totalEntries Size of file header
246 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
248 public final function getHeaderSize () {
249 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
253 * Setter for header size
255 * @param $headerSize Size of file header
257 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
259 public final function setHeaderSize ($headerSize) {
260 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
264 * Getter for header array
266 * @return $totalEntries Size of file header
267 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
269 public final function getHeader () {
270 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
276 * @param $header Array for a file header
278 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
280 public final function setHeader (array $header) {
281 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
285 * Updates seekPosition attribute from file to avoid to much access on file.
288 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
290 public function updateSeekPosition () {
291 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
295 * Getter for total entries
297 * @return $totalEntries Total entries in this file
298 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
300 public final function getCounter () {
301 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
305 * "Getter" for file size
307 * @return $fileSize Size of currently loaded file
309 public function getFileSize () {
310 // Call iterator's method
311 return $this->getIteratorInstance()->getFileSize();
315 * Writes data at given position
317 * @param $seekPosition Seek position
318 * @param $data Data to be written
319 * @param $flushHeader Whether to flush the header (default: flush)
321 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
323 public function writeData ($seekPosition, $data, $flushHeader = true) {
324 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
325 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
329 * Writes given value to the file and returns a hash and gap position for it
331 * @param $groupId Group identifier
332 * @param $value Value to be added to the stack
333 * @return $data Hash and gap position
334 * @throws UnsupportedOperationException If this method is called
336 public function writeValueToFile ($groupId, $value) {
337 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',value[' . gettype($value) . ']=' . print_r($value, true));
338 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
342 * Writes given raw data to the file and returns a gap position and length
344 * @param $groupId Group identifier
345 * @param $hash Hash from encoded value
346 * @param $encoded Encoded value to be written to the file
347 * @return $data Gap position and length of the raw data
349 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
350 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
351 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);