Skip to content

Commit

Permalink
fix(stdlib): Prevent addBytesSlice throwing error on empty buffer (#1394
Browse files Browse the repository at this point in the history
)
  • Loading branch information
spotandjake committed Aug 2, 2022
1 parent 3e7c147 commit bdd4be4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 23 deletions.
8 changes: 7 additions & 1 deletion compiler/test/stdlib/buffer.test.gr
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,10 @@ Buffer.addBytesSlice(0, 0, bytes, buf)
assert Buffer.toBytes(buf) == Bytes.empty
Buffer.addBytesSlice(0, Bytes.length(bytes), bytes, buf)
assert Buffer.toBytes(buf) == bytes
let emptyBytes = Bytes.make(0)
let emptyBuffer = Buffer.make(0)
Buffer.addBytesSlice(0, 0, emptyBytes, emptyBuffer)
assert emptyBuffer == Buffer.make(0)

// addString / toString
let str = "Let's get this 🍞"
Expand Down Expand Up @@ -268,7 +272,9 @@ Buffer.addString("✨", buf2)
Buffer.addBuffer(buf1, buf0)
Buffer.addBuffer(buf2, buf0)
assert Buffer.toString(buf0) == "✨🍩✨"

let emptyBuffer = Buffer.make(0)
Buffer.addBuffer(Buffer.make(0), emptyBuffer)
assert emptyBuffer == Buffer.make(0)
// addBufferSlice
let buf0 = Buffer.make(0)
let buf1 = Buffer.make(0)
Expand Down
46 changes: 24 additions & 22 deletions stdlib/buffer.gr
Original file line number Diff line number Diff line change
Expand Up @@ -339,32 +339,34 @@ export let addBytesSlice =
bytes: Bytes,
buffer: Buffer,
) => {
let (-) = WasmI32.sub
let (<) = WasmI32.ltS
let (>) = WasmI32.gtS
let (>=) = WasmI32.geS

// bounds check start
let bytelen = WasmI32.load(WasmI32.fromGrain(bytes), 4n)
let srcOff = coerceNumberToWasmI32(start)
if (srcOff < 0n || srcOff >= bytelen) {
throw Exception.IndexOutOfBounds
}
if (length != 0) {
let (-) = WasmI32.sub
let (<) = WasmI32.ltS
let (>) = WasmI32.gtS
let (>=) = WasmI32.geS

// bounds check start
let bytelen = WasmI32.load(WasmI32.fromGrain(bytes), 4n)
let srcOff = coerceNumberToWasmI32(start)
if (srcOff < 0n || srcOff >= bytelen) {
throw Exception.IndexOutOfBounds
}

// bounds check length
let len = coerceNumberToWasmI32(length)
if (len < 0n || len > bytelen - srcOff) {
throw Exception.IndexOutOfBounds
}
// bounds check length
let len = coerceNumberToWasmI32(length)
if (len < 0n || len > bytelen - srcOff) {
throw Exception.IndexOutOfBounds
}

autogrow(length, buffer)
autogrow(length, buffer)

let dstOff = coerceNumberToWasmI32(buffer.len)
let src = WasmI32.fromGrain(bytes)
let dst = WasmI32.fromGrain(buffer.data)
appendBytes(srcOff, dstOff, len, src, dst)
let dstOff = coerceNumberToWasmI32(buffer.len)
let src = WasmI32.fromGrain(bytes)
let dst = WasmI32.fromGrain(buffer.data)
appendBytes(srcOff, dstOff, len, src, dst)

buffer.len += length
buffer.len += length
}
}

/**
Expand Down

0 comments on commit bdd4be4

Please sign in to comment.