Skip to content

Commit

Permalink
Seeking before beginning of file should fail
Browse files Browse the repository at this point in the history
When seeking in a file to a location before the beginning of the file,
the operation seems to succeed. While if i try to do the same with a
"real" file then the seek command will return an error.

So i changed the seek method to return false if the offset is less
than 0. This seems to solve my problem and behaves in the same
way as seeking in a real file. However I do not know if there are
situations where seeking before the beginning of the file could be
a valid use case. testing with fseek on unix fs always returns -1
when seeking past the beginning of the file. Added five test
assertions to validate this behavior.
  • Loading branch information
merijnvdk committed Jul 26, 2017
1 parent 03c1427 commit 44348c5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/main/php/org/bovigo/vfs/content/SeekableFileContent.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,24 +52,30 @@ protected abstract function doRead($offset, $count);
*/
public function seek($offset, $whence)
{
$old_offset = $this->offset;
switch ($whence) {
case SEEK_CUR:
$this->offset += $offset;
return true;
break;

case SEEK_END:
$this->offset = $this->size() + $offset;
return true;
break;

case SEEK_SET:
$this->offset = $offset;
return true;
break;

default:
return false;
}

if ($this->offset<0) {
$this->offset = $old_offset;
return false;
}

return false;
return true;
}

/**
Expand Down
5 changes: 5 additions & 0 deletions src/test/php/org/bovigo/vfs/vfsStreamFileTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ public function seekEmptyFile()
$this->assertEquals(0, $this->file->getBytesRead());
$this->assertTrue($this->file->seek(2, SEEK_END));
$this->assertEquals(2, $this->file->getBytesRead());
$this->assertFalse($this->file->seek(-1, SEEK_SET),'Seek before beginning of file');
$this->assertEquals(2, $this->file->getBytesRead());
}

/**
Expand Down Expand Up @@ -158,6 +160,9 @@ public function seekRead()
$this->assertTrue($this->file->seek(2, SEEK_END));
$this->assertEquals('', $this->file->readUntilEnd());
$this->assertEquals(11, $this->file->getBytesRead());
$this->assertFalse($this->file->seek(-35, SEEK_SET),'Seek before beginning of file');
$this->assertEquals('', $this->file->readUntilEnd());
$this->assertEquals(11, $this->file->getBytesRead());
}

/**
Expand Down

0 comments on commit 44348c5

Please sign in to comment.