I'm trying to port some JVM code to native code, a...
# multiplatform
e
I'm trying to port some JVM code to native code, and I need to replicate some
ByteBuffer
code. I'm using ktor-io but there's something that I'm not doing correctly. Code in 🧵
Here's what I'm porting:
Copy code
if (byteBuffer.position() == 0) {
  return;
}
byteBuffer.flip();
try {
  builder.append(decoder.decode(byteBuffer));
} catch (CharacterCodingException e) {
  if (throwOnFailure) {
    throw new IllegalArgumentException(e);
  } else {
    builder.append(INVALID_INPUT_CHARACTER);
  }
} finally {
  // Use the byte buffer to write again.
  byteBuffer.flip();
  byteBuffer.limit(byteBuffer.capacity());
}
Here's my code (an extension function on
Buffer
):
Copy code
if(writePosition == 0) return

resetForRead()

try {
  builder.append(readBytes().decodeToString())
}
catch(e: Exception) {
  if(throwOnFailure) {
    throw IllegalArgumentException(e)
  }
  else {
    builder.append(INVALID_INPUT_CHARACTER)
  }
}
finally {
  reset()
}
The problem is that a bunch of 0s are showing up when I call
readBytes
(this is after writing 1 byte to the buffer then calling my function, then writing 3 bytes to the buffer then calling my function, then writing 3 bytes to the buffer then calling my function):
Copy code
47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-60, -126, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-32, -95, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
e
you should probably indicate which
Buffer
you're using. doesn't seem to be okio.Buffer
if it's io.ktor.utils.io.core.Buffer, I've no experience with it but
resetForRead()
doesn't seem to be equivalent to `flip()`: it marks the whole buffer as readable, not just the part up to the write position
e
It's ktor's
Buffer
but my IDE is having issues resolving dependencies, so it's hard to step through it to see how it works. I'm assuming there's a way to do it with
okio.Buffer
as well?
e
with okio there's usually enough helpers build on (Buffered)Source, (Buffered)Sink, Pipe, etc. that there's no need to work on Buffer directly
e
Although looking at the problem again after some sleep I can probably make a simple wrapper around a byte array for this use case.