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
49 * @param $className Name of class
52 protected function __construct (string $className) {
53 // Call parent constructor
54 parent::__construct($className);
58 * Reads the file header
61 * @throws UnexpectedValueException If header length or count of elements is invalid
63 public function readIndexHeader () {
64 // First rewind to beginning as the header sits at the beginning ...
65 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
66 $this->getIteratorInstance()->rewind();
68 // Then read it (see constructor for calculation)
69 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
71 // Have all requested bytes been read?
72 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getHeaderSize()));
73 if (strlen($data) != $this->getIteratorInstance()->getHeaderSize()) {
74 // Invalid header length
75 throw new UnexpectedValueException(sprintf('data(%d)=%s is not expected length %d',
78 $this->getIteratorInstance()->getHeaderSize()
80 } elseif (empty(trim($data, chr(0)))) {
82 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: File header is empty - EXIT!');
84 } elseif (substr($data, -1, 1) != chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)) {
86 throw new UnexpectedValueException(sprintf('data=%s does not end with "%s"',
88 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
92 // Okay, then remove it
93 $data = substr($data, 0, -1);
95 // And update seek position
96 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->updateSeekPosition() ...');
97 $this->getIteratorInstance()->updateSeekPosition();
105 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
107 // Check if the array has only 3 elements
108 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: header()=%d', count($header)));
109 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: header(%d)=%s', count($header), print_r($header, true)));
110 if (count($header) != 2) {
112 throw new UnexpectedValueException(sprintf('header()=%d is not expected value 2', count($header)));
113 } elseif ($header[0] !== Indexable::INDEX_MAGIC) {
114 // Magic must be in first element
115 throw new UnexpectedValueException(sprintf('header[0]=%s is not the expected magic (%s)', $header[0], Indexable::INDEX_MAGIC));
116 } elseif (strlen($header[1]) != BaseBinaryFile::LENGTH_COUNT) {
117 // Length of total entries not matching
118 throw new UnexpectedValueException(sprintf('header[1](%d)=%s does not have expected length %d', strlen($header[1]), $header[1], BaseBinaryFile::LENGTH_COUNT));
122 $header[1] = hex2bin($header[1]);
125 $this->getIteratorInstance()->setHeader($header);
128 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
132 * Flushes the file header
136 public function flushFileHeader () {
137 // Put all informations together
138 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
139 $header = sprintf('%s%s%s%s',
141 Indexable::INDEX_MAGIC,
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 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Calling this->iteratorInstance->writeAtPosition(0, header=%s) ...', $header));
155 $this->getIteratorInstance()->writeAtPosition(0, $header);
158 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
162 * Initializes this index
164 * @param $fileInfoInstance An instance of a SplFileInfo class
166 * @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.
168 protected function initIndex (SplFileInfo $fileInfoInstance) {
169 // Get a file i/o pointer instance for index file
170 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
171 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileInfoInstance, $this));
173 // Get iterator instance
174 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', [$fileInstance]);
177 $this->setIteratorInstance($iteratorInstance);
179 // Calculate header size
181 strlen(Indexable::INDEX_MAGIC) +
182 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
183 BaseBinaryFile::LENGTH_COUNT +
184 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
188 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Setting headerSize=%d ...', $headerSize));
189 $this->getIteratorInstance()->setHeaderSize($headerSize);
191 // Init counters and gaps array
192 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->initCountersGapsArray() ...');
193 $this->getIteratorInstance()->initCountersGapsArray();
195 // Default is not created
198 // Is the file's header initialized?
199 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
200 // First pre-allocate a bit
201 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->preAllocateFile(index) ...');
202 $this->getIteratorInstance()->preAllocateFile('index');
204 // Then write file header
205 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->createFileHeader() ...');
206 $this->getIteratorInstance()->createFileHeader();
208 // Mark as freshly created
212 // Load the file header
213 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->readIndexHeader() ...');
214 $this->readIndexHeader();
217 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: created=%d', intval($created)));
219 // Analyze file structure
220 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->analyzeFileStructure() ...');
221 $this->getIteratorInstance()->analyzeFileStructure();
225 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
229 * Calculates minimum length for one entry/block
231 * @return $length Minimum length for one entry/block
233 public function calculateMinimumBlockLength () {
235 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
236 if (self::$minimumBlockLength == 0) {
238 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calculating ...');
239 self::$minimumBlockLength = (
241 BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) +
243 BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES))
248 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: self::minimumBlockLength=%d - EXIT!', self::$minimumBlockLength));
249 return self::$minimumBlockLength;
253 * "Getter" for file size
255 * @return $fileSize Size of currently loaded file
257 public function getFileSize () {
258 // Call iterator's method
259 return $this->getIteratorInstance()->getFileSize();
263 * Searches for next suitable gap the given length of data can fit in
264 * including padding bytes.
266 * @param $length Length of raw data
267 * @return $seekPosition Found next gap's seek position
268 * @throws InvalidArgumentException If the parameter is not valid
269 * @todo Unfinished work
271 public function searchNextGap (int $length) {
272 // Validate parameter
273 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: length=%d - CALLED!', $length));
276 throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
280 $this->partialStub('length=' . $length);
284 * Writes at given position by seeking to it.
286 * @param $seekPosition Seek position in file
287 * @param $dataStream Data to be written
288 * @return mixed Number of writes bytes or false on error
289 * @throws OutOfBoundsException If the position is not seekable
290 * @throws InvalidArgumentException If a parameter is not valid
292 public function writeAtPosition (int $seekPosition, string $dataStream) {
293 // Validate parameter
294 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
295 if ($seekPosition < 0) {
296 // Invalid seek position
297 throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
298 } elseif (empty($dataStream)) {
300 throw new InvalidArgumentException('Parameter "dataStream" is empty');
303 // Call iterated object's method
304 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Calling this->iteratorInstance->writeAtPosition(%d, %s) ...', $seekPosition, $dataStream));
305 $status = $this->getIteratorInstance()->writeAtPosition($seekPosition, $dataStream);
308 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: status[%s]=%d - EXIT!', gettype($status), $status));
313 * Checks if this index has been fully and properly loaded.
315 * @return $isLoaded Whether this index has been loaded
317 public function isIndexLoaded () {
319 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
320 /* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this=%s', __METHOD__, __LINE__, print_r($this, true)));