I don't remember anymore what's the best/right way...
# javascript
e
I don't remember anymore what's the best/right way to convert a Node.js
Buffer
to a Kotlin
ByteArray
v
I guess
buffer._asList_()._toByteArray_()
, but I have no idea actually. 🙂
e
I'd expect
.unsafeCast<ByteArray>()
to work, but actually since
Buffer
extends
UInt8Array
and not
Int8Array
it might have weird behavior without wrapping… haven't tested
(e.g.
Int8Array(buffer).unsafeCast<ByteArray>()
)
t
Draft (from gist)
Copy code
val uint8 = Uint8Array(arrayOf(1,2))

// conversion
val int8 = Int8Array(uint8.buffer)
val ba = int8.asByteArray()
asByteArray()
extension - fine PR :)
e
@turansky depends if the byte representation changes with
Copy code
Int8Array(uint8.buffer)
Would
asByteArray
simply
unsafeCast
?
t
Would
asByteArray
simply
unsafeCast
?
Yes
e
gratitude thank you 1
e
Byte representation seems to remain the same. So it would be a matter of adding
asByteArray
e
Uint8ClampedArray
will clamp values outside of range, as its name implies, other JS TypedArray types will reinterpret the bits
e
will reinterpret the bits
As a "view" over those bits tho, right? If you transform a
Int8Array
to a
UInt8Array
you get back the correct result
e
yes, and ditto if you go through
Int32Array
etc. too (assuming you have a correct multiple number of bytes)
v
Btw. is there anything bad with my suggestion?
e
copy
v
swimmingpool
e
@Vampire I guess I don't really like the additional
buffer._asList_()
But that's it, nothing wrong with it
e
.toByteArray
makes a copy while the
*TypedArray
constructors and
unsafeCast
don't
e
Well, apart from the copying every single byte
e
whether that matters is situational of course, but if you're using
Buffer
to begin with…
✔️ 1
v
Ah, I see, thx
t
@Edoardo Luppi What is your use case? Do you need
ByteArray
for Kotlin library? cc @Sergei Grishchenko
e
@turansky sorry didn't get pinged. I need to expose a
ByteArray
in common code, thus I need to convert the JS
Buffer
to said
ByteArray