| 1 |
/** |
| 2 |
* @suppress |
| 3 |
*/ |
| 4 |
public object FfiConverterString: FfiConverter<String, RustBuffer.ByValue> { |
| 5 |
// Note: we don't inherit from FfiConverterRustBuffer, because we use a |
| 6 |
// special encoding when lowering/lifting. We can use `RustBuffer.len` to |
| 7 |
// store our length and avoid writing it out to the buffer. |
| 8 |
override fun lift(value: RustBuffer.ByValue): String { |
| 9 |
try { |
| 10 |
val byteArr = ByteArray(value.len.toInt()) |
| 11 |
value.asByteBuffer()!!.get(byteArr) |
| 12 |
return byteArr.toString(Charsets.UTF_8) |
| 13 |
} finally { |
| 14 |
RustBuffer.free(value) |
| 15 |
} |
| 16 |
} |
| 17 |
|
| 18 |
override fun read(buf: ByteBuffer): String { |
| 19 |
val len = buf.getInt() |
| 20 |
val byteArr = ByteArray(len) |
| 21 |
buf.get(byteArr) |
| 22 |
return byteArr.toString(Charsets.UTF_8) |
| 23 |
} |
| 24 |
|
| 25 |
fun toUtf8(value: String): ByteBuffer { |
| 26 |
// Make sure we don't have invalid UTF-16, check for lone surrogates. |
| 27 |
return Charsets.UTF_8.newEncoder().run { |
| 28 |
onMalformedInput(CodingErrorAction.REPORT) |
| 29 |
encode(CharBuffer.wrap(value)) |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
override fun lower(value: String): RustBuffer.ByValue { |
| 34 |
val byteBuf = toUtf8(value) |
| 35 |
// Ideally we'd pass these bytes to `ffi_bytebuffer_from_bytes`, but doing so would require us |
| 36 |
// to copy them into a JNA `Memory`. So we might as well directly copy them into a `RustBuffer`. |
| 37 |
val rbuf = RustBuffer.alloc(byteBuf.limit().toULong()) |
| 38 |
rbuf.asByteBuffer()!!.put(byteBuf) |
| 39 |
return rbuf |
| 40 |
} |
| 41 |
|
| 42 |
// We aren't sure exactly how many bytes our string will be once it's UTF-8 |
| 43 |
// encoded. Allocate 3 bytes per UTF-16 code unit which will always be |
| 44 |
// enough. |
| 45 |
override fun allocationSize(value: String): ULong { |
| 46 |
val sizeForLength = 4UL |
| 47 |
val sizeForString = value.length.toULong() * 3UL |
| 48 |
return sizeForLength + sizeForString |
| 49 |
} |
| 50 |
|
| 51 |
override fun write(value: String, buf: ByteBuffer) { |
| 52 |
val byteBuf = toUtf8(value) |
| 53 |
buf.putInt(byteBuf.limit()) |
| 54 |
buf.put(byteBuf) |
| 55 |
} |
| 56 |
} |