Skip to content

Commit

Permalink
Document why we use NUL terminated strings (#1318)
Browse files Browse the repository at this point in the history
  • Loading branch information
squarejesse authored Jul 31, 2023
1 parent c7e7ad3 commit 3e30feb
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions okio-wasifilesystem/src/wasmMain/kotlin/okio/internal/Wasi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ internal fun fdClose(fd: fd) {
internal fun Pointer.readString(byteCount: Int): String {
if (byteCount == 0) return ""

// Drop the last byte if it's \0.
// TODO: confirm this is necessary in practice.
// Drop the last byte if it's 0. At least in NodeJS' implementation, strings are returned with
// a trailing NUL byte.
val lastByte = (this + byteCount - 1).loadByte()
val byteArray = when {
lastByte.toInt() == 0 -> readByteArray(byteCount - 1)
Expand Down Expand Up @@ -61,6 +61,9 @@ internal fun MemoryAllocator.write(
string: String,
): Pair<Pointer, size> {
val bytes = string.encodeToByteArray()

// Append a trailing NUL byte. This shouldn't be necessary, but it reduces crashes in practice,
// at least on NodeJS 20.0. https://github.com/WebAssembly/WASI/issues/492
val result = allocate(bytes.size + 1)
var pos = result
for (element in bytes) {
Expand Down

0 comments on commit 3e30feb

Please sign in to comment.