3 namespace Org\Mxchange\CoreFramework\Index\File;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
7 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
9 use Org\Mxchange\CoreFramework\Index\BaseIndex;
10 use Org\Mxchange\CoreFramework\Index\Indexable;
11 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
14 use \OutOfBoundsException;
16 use \UnexpectedValueException;
19 * A general file-based index class
21 * @author Roland Haeder <webmaster@ship-simu.org>
23 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
24 * @license GNU GPL 3.0 or any newer version
25 * @link http://www.ship-simu.org
27 * This program is free software: you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation, either version 3 of the License, or
30 * (at your option) any later version.
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
37 * You should have received a copy of the GNU General Public License
38 * along with this program. If not, see <http://www.gnu.org/licenses/>.
40 abstract class BaseFileIndex extends BaseIndex implements FileIndexer {
42 * Minimum block length
44 private static $minimumBlockLength = 0;
47 * Protected constructor
51 private function __construct () {
52 // Call parent constructor
53 parent::__construct(__CLASS__);
57 * Reads the file header
60 * @throws UnexpectedValueException If header length or count of elements is invalid
62 public function readIndexHeader () {
63 // First rewind to beginning as the header sits at the beginning ...
64 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
65 $this->getIteratorInstance()->rewind();
67 // Then read it (see constructor for calculation)
68 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
70 // Have all requested bytes been read?
71 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getHeaderSize()));
72 if (strlen($data) != $this->getIteratorInstance()->getHeaderSize()) {
73 // Invalid header length
74 throw new UnexpectedValueException(sprintf('data(%d)=%s is not expected length %d',
77 $this->getIteratorInstance()->getHeaderSize()
79 } elseif (empty(trim($data, chr(0)))) {
81 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: File header is empty - EXIT!');
83 } elseif (substr($data, -1, 1) != chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)) {
85 throw new UnexpectedValueException(sprintf('data=%s does not end with "%s"',
87 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
91 // Okay, then remove it
92 $data = substr($data, 0, -1);
94 // And update seek position
95 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->updateSeekPosition() ...');
96 $this->getIteratorInstance()->updateSeekPosition();
104 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
106 // Check if the array has only 3 elements
107 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: header()=%d', count($header)));
108 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: header(%d)=%s', count($header), print_r($header, true)));
109 if (count($header) != 2) {
111 throw new UnexpectedValueException(sprintf('header()=%d is not expected value 2', count($header)));
112 } elseif ($header[0] !== Indexable::INDEX_MAGIC) {
113 // Magic must be in first element
114 throw new UnexpectedValueException(sprintf('header[0]=%s is not the expected magic (%s)', $header[0], Indexable::INDEX_MAGIC));
115 } elseif (strlen($header[1]) != BaseBinaryFile::LENGTH_COUNT) {
116 // Length of total entries not matching
117 throw new UnexpectedValueException(sprintf('header[1](%d)=%s does not have expected length %d', strlen($header[1]), $header[1], BaseBinaryFile::LENGTH_COUNT));
121 $header[1] = hex2bin($header[1]);
124 $this->getIteratorInstance()->setHeader($header);
127 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
131 * Flushes the file header
135 public function flushFileHeader () {
136 // Put all informations together
137 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
138 $header = sprintf('%s%s%s%s',
140 Indexable::INDEX_MAGIC,
142 // Separator header data
143 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
146 str_pad(StringUtils::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 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Calling this->iteratorInstance->writeAtPosition(0, header=%s) ...', $header));
154 $this->getIteratorInstance()->writeAtPosition(0, $header);
157 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
161 * Initializes this index
163 * @param $fileInfoInstance An instance of a SplFileInfo class
165 * @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.
167 protected function initIndex (SplFileInfo $fileInfoInstance) {
168 // Get a file i/o pointer instance for index file
169 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
170 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileInfoInstance, $this));
172 // Get iterator instance
173 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', [$fileInstance]);
176 $this->setIteratorInstance($iteratorInstance);
178 // Calculate header size
180 strlen(Indexable::INDEX_MAGIC) +
181 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
182 BaseBinaryFile::LENGTH_COUNT +
183 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
187 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Setting headerSize=%d ...', $headerSize));
188 $this->getIteratorInstance()->setHeaderSize($headerSize);
190 // Init counters and gaps array
191 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->initCountersGapsArray() ...');
192 $this->getIteratorInstance()->initCountersGapsArray();
194 // Default is not created
197 // Is the file's header initialized?
198 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
199 // First pre-allocate a bit
200 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->preAllocateFile(index) ...');
201 $this->getIteratorInstance()->preAllocateFile('index');
203 // Then write file header
204 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->createFileHeader() ...');
205 $this->getIteratorInstance()->createFileHeader();
207 // Mark as freshly created
211 // Load the file header
212 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->readIndexHeader() ...');
213 $this->readIndexHeader();
216 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: created=%d', intval($created)));
218 // Analyze file structure
219 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->analyzeFileStructure() ...');
220 $this->getIteratorInstance()->analyzeFileStructure();
224 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
228 * Calculates minimum length for one entry/block
230 * @return $length Minimum length for one entry/block
232 public function calculateMinimumBlockLength () {
234 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
235 if (self::$minimumBlockLength == 0) {
237 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calculating ...');
238 self::$minimumBlockLength = (
240 BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) +
242 BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES))
247 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: self::minimumBlockLength=%d - EXIT!', self::$minimumBlockLength));
248 return self::$minimumBlockLength;
252 * "Getter" for file size
254 * @return $fileSize Size of currently loaded file
256 public function getFileSize () {
257 // Call iterator's method
258 return $this->getIteratorInstance()->getFileSize();
262 * Searches for next suitable gap the given length of data can fit in
263 * including padding bytes.
265 * @param $length Length of raw data
266 * @return $seekPosition Found next gap's seek position
267 * @throws InvalidArgumentException If the parameter is not valid
268 * @todo Unfinished work
270 public function searchNextGap (int $length) {
271 // Validate parameter
272 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: length=%d - CALLED!', $length));
275 throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
279 $this->partialStub('length=' . $length);
283 * Writes at given position by seeking to it.
285 * @param $seekPosition Seek position in file
286 * @param $dataStream Data to be written
287 * @return mixed Number of writes bytes or false on error
288 * @throws OutOfBoundsException If the position is not seekable
289 * @throws InvalidArgumentException If a parameter is not valid
291 public function writeAtPosition (int $seekPosition, string $dataStream) {
292 // Validate parameter
293 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
294 if ($seekPosition < 0) {
295 // Invalid seek position
296 throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
297 } elseif (empty($dataStream)) {
299 throw new InvalidArgumentException('Parameter "dataStream" is empty');
302 // Call iterated object's method
303 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Calling this->iteratorInstance->writeAtPosition(%d, %s) ...', $seekPosition, $dataStream));
304 $status = $this->getIteratorInstance()->writeAtPosition($seekPosition, $dataStream);
307 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: status[%s]=%d - EXIT!', gettype($status), $status));
312 * Checks if this index has been fully and properly loaded.
314 * @return $isLoaded Whether this index has been loaded
316 public function isIndexLoaded () {
318 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
319 /* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this=%s', __METHOD__, __LINE__, print_r($this, true)));