Skip to content

Commit

Permalink
Codechange: Store start and end position in RandomAccessFile.
Browse files Browse the repository at this point in the history
This allows callers to do more bounds checking.
  • Loading branch information
PeterN committed Aug 24, 2024
1 parent b5264a7 commit 719763d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/random_access_file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions src/random_access_file_type.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -44,7 +46,10 @@ class RandomAccessFile {
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();
Expand Down

0 comments on commit 719763d

Please sign in to comment.