3 namespace Org\Mxchange\CoreFramework\Index\File;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
7 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
8 use Org\Mxchange\CoreFramework\Index\BaseIndex;
9 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
12 use \OutOfBoundsException;
14 use \UnexpectedValueException;
17 * A general file-based 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 BaseFileIndex extends BaseIndex implements FileIndexer {
40 * Protected constructor
44 protected function __construct () {
45 // Call parent constructor
46 parent::__construct(__CLASS__);
50 * Reads the file header
53 * @throws UnexpectedValueException If header length or count of elements is invalid
55 public function readIndexHeader () {
56 // First rewind to beginning as the header sits at the beginning ...
57 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
58 $this->getIteratorInstance()->rewind();
60 // Then read it (see constructor for calculation)
61 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
63 // Have all requested bytes been read?
64 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getHeaderSize()));
65 if (strlen($data) != $this->getIteratorInstance()->getHeaderSize()) {
66 // Invalid header length
67 throw new UnexpectedValueException(sprintf('data(%d)=%s is not expected length %d',
70 $this->getIteratorInstance()->getHeaderSize()
72 } elseif (empty(trim($data, chr(0)))) {
74 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: File header is empty - EXIT!');
76 } elseif (substr($data, -1, 1) != chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)) {
78 throw new UnexpectedValueException(sprintf('data=%s does not end with "%s"',
80 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
84 // Okay, then remove it
85 $data = substr($data, 0, -1);
87 // And update seek position
88 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->updateSeekPosition() ...');
89 $this->getIteratorInstance()->updateSeekPosition();
97 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
99 // Check if the array has only 3 elements
100 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: header()=%d', count($header)));
101 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: header(%d)=%s', count($header), print_r($header, true)));
102 if (count($header) != 2) {
104 throw new UnexpectedValueException(sprintf('header()=%d is not expected value 2', count($header)));
105 } elseif ($header[0] !== Indexable::INDEX_MAGIC) {
106 // Magic must be in first element
107 throw new UnexpectedValueException(sprintf('header[0]=%s is not the expected magic (%s)', $header[0], Indexable::INDEX_MAGIC));
108 } elseif (strlen($header[1]) != BaseBinaryFile::LENGTH_COUNT) {
109 // Length of total entries not matching
110 throw new UnexpectedValueException(sprintf('header[1](%d)=%s does not have expected length %d', strlen($header[1]), $header[1], BaseBinaryFile::LENGTH_COUNT));
114 $header[1] = hex2bin($header[1]);
117 $this->getIteratorInstance()->setHeader($header);
120 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
124 * Flushes the file header
128 public function flushFileHeader () {
129 // Put all informations together
130 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
131 $header = sprintf('%s%s%s%s',
133 Indexable::INDEX_MAGIC,
135 // Separator header data
136 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
139 str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
141 // Separator header<->entries
142 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
145 // Write it to disk (header is always at seek position 0)
146 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Calling this->iteratorInstance->writeAtPosition(0, header=%s) ...', $header));
147 $this->getIteratorInstance()->writeAtPosition(0, $header);
150 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
154 * Initializes this index
156 * @param $fileInfoInstance An instance of a SplFileInfo class
158 * @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.
160 protected function initIndex (SplFileInfo $fileInfoInstance) {
161 // Get a file i/o pointer instance for index file
162 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
163 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileInfoInstance, $this));
165 // Get iterator instance
166 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', [$fileInstance]);
169 $this->setIteratorInstance($iteratorInstance);
171 // Calculate header size
173 strlen(Indexable::INDEX_MAGIC) +
174 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
175 BaseBinaryFile::LENGTH_COUNT +
176 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
180 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Setting headerSize=%d ...', $headerSize));
181 $this->getIteratorInstance()->setHeaderSize($headerSize);
183 // Init counters and gaps array
184 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->initCountersGapsArray() ...');
185 $this->getIteratorInstance()->initCountersGapsArray();
187 // Default is not created
190 // Is the file's header initialized?
191 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
192 // First pre-allocate a bit
193 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->preAllocateFile(index) ...');
194 $this->getIteratorInstance()->preAllocateFile('index');
196 // Then write file header
197 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->createFileHeader() ...');
198 $this->getIteratorInstance()->createFileHeader();
200 // Mark as freshly created
204 // Load the file header
205 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->readIndexHeader() ...');
206 $this->readIndexHeader();
209 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: created=%d', intval($created)));
211 // Analyze file structure
212 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->analyzeFileStructure() ...');
213 $this->getIteratorInstance()->analyzeFileStructure();
217 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
221 * Calculates minimum length for one entry/block
223 * @return $length Minimum length for one entry/block
225 public function calculateMinimumBlockLength () {
227 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
228 if (self::$minimumBlockLength == 0) {
230 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calculating ...');
231 self::$minimumBlockLength = (
233 BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) +
235 BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES))
240 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: self::minimumBlockLength=%d - EXIT!', self::$minimumBlockLength));
241 return self::$minimumBlockLength;
245 * "Getter" for file size
247 * @return $fileSize Size of currently loaded file
249 public function getFileSize () {
250 // Call iterator's method
251 return $this->getIteratorInstance()->getFileSize();
255 * Searches for next suitable gap the given length of data can fit in
256 * including padding bytes.
258 * @param $length Length of raw data
259 * @return $seekPosition Found next gap's seek position
260 * @throws InvalidArgumentException If the parameter is not valid
261 * @todo Unfinished work
263 public function searchNextGap (int $length) {
264 // Validate parameter
265 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: length=%d - CALLED!', $length));
268 throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
272 $this->partialStub('length=' . $length);
276 * Writes at given position by seeking to it.
278 * @param $seekPosition Seek position in file
279 * @param $dataStream Data to be written
280 * @return mixed Number of writes bytes or false on error
281 * @throws OutOfBoundsException If the position is not seekable
282 * @throws InvalidArgumentException If a parameter is not valid
284 public function writeAtPosition (int $seekPosition, string $dataStream) {
285 // Validate parameter
286 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
287 if ($seekPosition < 0) {
288 // Invalid seek position
289 throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
290 } elseif (empty($dataStream)) {
292 throw new InvalidArgumentException('Parameter "dataStream" is empty');
295 // Call iterated object's method
296 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Calling this->iteratorInstance->writeAtPosition(%d, %s) ...', $seekPosition, $dataStream));
297 $status = $this->getIteratorInstance()->writeAtPosition($seekPosition, $dataStream);
300 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: status[%s]=%d - EXIT!', gettype($status), $status));
305 * Checks if this index has been fully and properly loaded.
307 * @return $isLoaded Whether this index has been loaded
309 public function isIndexLoaded () {
311 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
312 /* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this=%s', __METHOD__, __LINE__, print_r($this, true)));