Is there a way to convert ArrayBuffer to a ByteArr...
# javascript
g
Is there a way to convert ArrayBuffer to a ByteArray?
d
Copy the contents
s
You can create Int8Array around the buffer and then unsafe cast it to ByteArray
d
Oh that's cool
g
Thank you so much !!!!! It worked ! For days I am trying to get a file to upload correctly to a backend through ktor-client !
Copy code
@Suppress("CAST_NEVER_SUCCEEDS")
fun ArrayBuffer?.asByteArray(): ByteArray? = this?.run { Int8Array(this) as ByteArray }
s
Great! We highly appreciate feedback. Please let us know if you have any inconveniences.
g
I’d like that function to be part of kotlin/js by default
👍 1
Would have been useful
s
Since we know for sure that
ByteArray
and
Int8Array
are the same things on runtime we can use:
Copy code
fun ArrayBuffer?.asByteArray(): ByteArray? =
   this?.run { Int8Array(this).unsafeCast<ByteArray>() }
This will eliminate unnecesary type check and we don't have to use
@Suppress
Generated code for
unsafeCast
would be:
Copy code
return $receiver != null ? new Int8Array($receiver) : null;
compared to
as
version:
Copy code
var tmp$;
    if ($receiver != null) {
      var tmp$_0;
      tmp$ = Kotlin.isByteArray(tmp$_0 = new Int8Array($receiver)) ? tmp$_0 : throwCCE();
    }
     else
      tmp$ = null;
    return tmp$;
I’d like that function to be part of kotlin/js by default
Could you file a feature request at kotl.in/issue?
g
Nice I will use that then
Yes I will submit a feature request
I didn’t know about unsafeCast, I am going to apply it everywhere needed now
s
unsafeCast
has downsides, if cast fails your program will fail the JavaScript way: usually farther down the execution with ambiguous error message 😁
g
ahah
300 Views