Skip to content

Should charCodeAt be used for binary IO? #308

@ejgallego

Description

@ejgallego

charCodeAt is pervasively used in the javascript library to read a byte from a string.

However, such use is may be inconsistent when strings are used in OCAML to contain binary data, as charCodeAt may return values higher than 256. For instance:

> var str = "ℕlala"
> var utf8 = unescape(encodeURIComponent(str));
> var arr = [];
> for (var i = 0; i < utf8.length; i++) { arr.push(utf8.charCodeAt(i)); };
> arr
[ 226, 132, 149, 108, 97, 108, 97 ]
> utf8
'�lala'
> str.charCodeAt(1);
108
> utf8.charCodeAt(1);
132
> arr[1];
132

This may break some binary reading done in Ocaml, like in dynlink.ml, etc...

After a bit of thinking about Ocaml strings, it is not clear to me what should be the best choice here. One option is to implement strings always as byte arrays in JS, replacing charCodeAt by regular array access.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions