Skip to content

Commit

Permalink
fix: allow writing starting at offset beyond file length (ipfs#71)
Browse files Browse the repository at this point in the history
There was a test for this but it didn't check the contents of the
entire file, only starting from the difference between the offset
and the file length.  Oops.

Fixes ipfs#53
  • Loading branch information
achingbrain authored Jan 10, 2020
1 parent 5747297 commit 68bd372
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
11 changes: 10 additions & 1 deletion src/core/write.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ const write = async (context, source, destination, options) => {

// pad start of file if necessary
if (options.offset > 0) {
if (destination.unixfs && destination.unixfs.fileSize() > options.offset) {
if (destination.unixfs) {
log(`Writing first ${options.offset} bytes of original file`)

sources.push(
Expand All @@ -139,6 +139,15 @@ const write = async (context, source, destination, options) => {
})
}
)

if (destination.unixfs.fileSize() < options.offset) {
const extra = options.offset - destination.unixfs.fileSize()

log(`Writing zeros for extra ${extra} bytes`)
sources.push(
asyncZeroes(extra)
)
}
} else {
log(`Writing zeros for first ${options.offset} bytes`)
sources.push(
Expand Down
10 changes: 6 additions & 4 deletions test/core/write.js
Original file line number Diff line number Diff line change
Expand Up @@ -373,11 +373,13 @@ describe('write', () => {
const stats = await mfs.stat(path)
expect(stats.size).to.equal(newContent.length + offset)

const buffer = Buffer.concat(await all(mfs.read(path, {
offset: offset - 5
})))
const buffer = Buffer.concat(await all(mfs.read(path)))

if (content[Symbol.asyncIterator]) {
content = Buffer.concat(await all(content))
}

expect(buffer).to.deep.equal(Buffer.concat([Buffer.from([0, 0, 0, 0, 0]), newContent]))
expect(buffer).to.deep.equal(Buffer.concat([content, Buffer.from([0, 0, 0, 0, 0]), newContent]))
})
})

Expand Down

0 comments on commit 68bd372

Please sign in to comment.