1
0
Fork 0

Codechange: Store start and end position in RandomAccessFile.

This allows callers to do more bounds checking.
pull/12921/head
Peter Nelson 2024-05-15 22:16:50 +01:00 committed by Peter Nelson
parent b5264a72ae
commit 719763dfcb
2 changed files with 20 additions and 1 deletions

View File

@ -24,13 +24,18 @@
*/
RandomAccessFile::RandomAccessFile(const std::string &filename, Subdirectory subdir) : filename(filename)
{
this->file_handle = FioFOpenFile(filename, "rb", subdir);
size_t file_size;
this->file_handle = FioFOpenFile(filename, "rb", subdir, &file_size);
if (this->file_handle == nullptr) UserError("Cannot open file '{}'", filename);
/* When files are in a tar-file, the begin of the file might not be at 0. */
long pos = ftell(this->file_handle);
if (pos < 0) UserError("Cannot read file '{}'", filename);
/* Make a note of start and end position for readers who check bounds. */
this->start_pos = pos;
this->end_pos = this->start_pos + file_size;
/* Store the filename without path and extension */
auto t = filename.rfind(PATHSEPCHAR);
std::string name_without_path = filename.substr(t != std::string::npos ? t + 1 : 0);
@ -76,6 +81,15 @@ size_t RandomAccessFile::GetPos() const
return this->pos + (this->buffer - this->buffer_end);
}
/**
* Test if we have reached the end of the file.
* @return True iff the current position as at or after the end of the file.
*/
bool RandomAccessFile::AtEndOfFile() const
{
return this->GetPos() >= this->GetEndPos();
}
/**
* Seek in the current file.
* @param pos New position.

View File

@ -28,6 +28,8 @@ class RandomAccessFile {
FILE *file_handle; ///< File handle of the open file.
size_t pos; ///< Position in the file of the end of the read buffer.
size_t start_pos; ///< Start position of file. May be non-zero if file is within a tar file.
size_t end_pos; ///< End position of file.
uint8_t *buffer; ///< Current position within the local buffer.
uint8_t *buffer_end; ///< Last valid byte of buffer.
@ -44,7 +46,10 @@ public:
const std::string &GetSimplifiedFilename() const;
size_t GetPos() const;
size_t GetStartPos() const { return this->start_pos; }
size_t GetEndPos() const { return this->end_pos; }
void SeekTo(size_t pos, int mode);
bool AtEndOfFile() const;
uint8_t ReadByte();
uint16_t ReadWord();