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

A rewrite of my last example, using @annevk's proposed IDL.

```javascript
function convertString(buffer, input, callback) {
  let bufferSize = 256;
  let bufferStart = malloc(buffer, bufferSize);
  let bytesWritten = 0;
  let offset = 0;
  while (true) {
    const {outputOffset, inputOffset} = cachedEncoder.encodeInto(
        new Uint8Array(
            buffer, bytesStart + bytesWritten, bufferSize - bytesWritten),
        input, offset);
    offset = inputOffset;
    bytesWritten += outputOffset;
    if (offset === input.length) {
      callback(bufferStart, bytesWritten);
      free(buffer, bufferStart);
      return;
    }

    bufferSize *= 2;
    bufferStart = realloc(buffer, bufferStart, bufferSize);
  }
}
```
I think it's nice and clear. It might be a bit clunkier than it needs to be because I kept the malloc/free/realloc semantics from my last version.

-- 
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-435001143

Received on Thursday, 1 November 2018 10:38:35 UTC