website icon indicating copy to clipboard operation
website copied to clipboard

[docs] Missing `bytesLength` from Array

Open inkeliz opened this issue 3 years ago • 3 comments

Currently, on Array documentation, doesn't mention the existence of bytesLength:

https://github.com/AssemblyScript/website/blob/50cc6b21347455969321b68d0dd2595d6a79c8e7/src/stdlib/array.md?plain=1#L36-L43

However, it's possible to use array.bytesLength.

inkeliz avatar Apr 17 '22 16:04 inkeliz

The property is private on normal Arrays, though this restriction is currently not enforced. Accessing it nonetheless is technically possible but considered unsafe. Within the standard library, we'd do something like

changetype<ArrayBufferView>(theArray).byteLength

or

load<i32>(changetype<usize>(theArray), offsetof<ArrayBufferView>("byteLength"))

to make the nature of the operation clear. Its's mostly an implementation detail in AS to have it on Arrays as well, while in JS only ArrayBufferViews (basically the typed arrays like Int32Array etc.) have it.

dcodeIO avatar Apr 17 '22 16:04 dcodeIO

Oh... The byteLength is the capacity of ArrayBuffer, not the size... So, running:

    let x = new Array<u32>(10)
    x.length = 1

    console.log(x.byteLength.toString())

Returns 40 instead of 4. There's any way to get the "`array.byteLength" (that is actually the length, not the capacity)?

inkeliz avatar Apr 17 '22 17:04 inkeliz

The solution is to use sizeof<valueof<T>>() (assuming T is Array<u64>, for instance). Then, it's possible to use array.length * sizeof<valueof<T>>().

However, both array.byteLength (for capacity) and valueof is missing from Docs. 🤔

inkeliz avatar Apr 17 '22 17:04 inkeliz