Re: [whatwg/encoding] TextEncoder#encode - write to existing Uint8Array (#69)

> Sorry if I'm missing something obvious but how does the caller of encodeInto learn how many bytes were written into the BufferSource?

Okay, that's embarrassing :rofl:. I did say it was a strawman :smile:.

So, you're proposing something like `encodeInto(bufferSource, bufferOffset, byteLength, string, stringOffset)`?

Example (trying to be more realistic to avoid the trap I fell into last time):
```javascript
function convertString(bufferSource, string, callback) {
  let bufferSize = 256;
  let bufferStart = malloc(bufferSource, bufferSize);
  let bytesWritten = 0;
  let stringOffset = 0;
  while (true) {
    try {
      bytesWritten += cachedEncoder.encodeInto(bufferSource, bufferStart + bytesWritten, bufferSize, string, stringOffset);
      callback(bufferStart, bytesWritten);
      free(bufferSource, bufferStart);
      break;
    } catch (e) {
      if (e instanceof TextEncoderBufferOverflowError) {
        stringOffset += e.codeUnitsConsumed;
        bytesWritten += e.bytesWritten;
        bufferSize *= 2;
        bufferStart = realloc(bufferSource, bufferStart, bufferSize);
      } else {
        free(bufferSource, bufferStart);
        throw e;
      }
    }
  }
}
```
I think `encodeInto()` having 5 arguments is unwieldy, but since the API is aimed at advanced users it may be acceptable.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/encoding/issues/69#issuecomment-434539796

Received on Wednesday, 31 October 2018 02:33:20 UTC