proposal-arraybuffer-base64 icon indicating copy to clipboard operation
proposal-arraybuffer-base64 copied to clipboard

[SUGGESTION]: setFromBase64/Hex `offset` argument

Open lifaon74 opened this issue 9 months ago • 4 comments

Hi,

I'm playing with this new api, and I thing it could be great to have an offset argument on the setFromBase64/Hex methods:

Issue: on mdn

const uint8Array = new Uint8Array(8);
// Start writing at offset 2
const result = uint8Array.subarray(2).setFromHex("cafed00d");

In my opinion, this feels sub-optimal.

Proposal:

We could mimic the .set method.

interface Uint8Array {
  setFromHex(input: string, offset?: number): { read: number; written: number; };
}
const uint8Array = new Uint8Array(8);
uint8Array.setFromHex("cafed00d", 2);

What do you think ?

lifaon74 avatar Mar 05 '25 07:03 lifaon74

See https://github.com/tc39/proposal-arraybuffer-base64/pull/33#issuecomment-1853453315 / https://github.com/tc39/proposal-arraybuffer-base64/pull/34. This was discussed but left out to match the very similar TextEncoder.prototype.encodeInto, which doesn't have such a parameter.

bakkot avatar Mar 05 '25 14:03 bakkot

I expected it to have an offset parameter to match TypedArray.prototype.set . Isn't that more natural than to align with TextEncoder?

tjconcept avatar Mar 06 '25 20:03 tjconcept

Well, set is directly attached to Uint8Array where TextEncoder.encodeInto is not. So I don't thing we should compare or align both . Moreover the necessity to perform a trick on TextEncoder.encodeInto feels... wrong.

Writing data at specific a position is a common practice with encoders/decoders, and I think we should keep simplicity and efficiency when possible.

lifaon74 avatar Mar 07 '25 08:03 lifaon74

For the record, I’m sympathetic to this intuition. There’s no world where working around this limitation with a subarray allocation would be faster than passing an offset. I like having the option.

kriskowal avatar Mar 07 '25 18:03 kriskowal