Skip to content

Commit

Permalink
Make #resize able to increase size
Browse files Browse the repository at this point in the history
  • Loading branch information
spuun committed Feb 7, 2025
1 parent 024adec commit 4467795
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
22 changes: 22 additions & 0 deletions spec/mfile_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,26 @@ describe MFile do
file.delete
end
end

describe "#resize" do
it "can increase size" do
file = File.tempfile "mfile_spec"
file.print "hello world"
file.flush
data = "foo"
initial_size = file.size
MFile.open(file.path, initial_size) do |mfile|
mfile.capacity.should eq initial_size
expect_raises(IO::EOFError) { mfile.write data.to_slice }
mfile.resize(mfile.size + data.bytesize)
mfile.write data.to_slice
mfile.capacity.should eq(initial_size + data.bytesize)
end
file.size.should eq(initial_size + data.bytesize)
data = File.read(file.path)
data.should eq "hello worldfoo"
ensure
file.try &.delete
end
end
end
14 changes: 11 additions & 3 deletions src/lavinmq/mfile.cr
Original file line number Diff line number Diff line change
Expand Up @@ -271,9 +271,17 @@ class MFile < IO
end

def resize(new_size : Int) : Nil
raise ArgumentError.new("Can't expand file larger than capacity, use truncate") if new_size > @capacity
@size = new_size.to_i64
@pos = new_size.to_i64 if @pos > new_size
if new_size > @capacity
raise File::Error.new("Can't resize readonly file", file: @path) if @readonly
unsafe_unmap
@capacity = new_size.to_i64
code = LibC.ftruncate(@fd, @capacity)
raise File::Error.from_errno("Error truncating file", file: @path) if code < 0
@buffer = mmap
else
@size = new_size.to_i64
@pos = new_size.to_i64 if @pos > new_size
end
end

# Read from a specific position in the file
Expand Down

0 comments on commit 4467795

Please sign in to comment.