Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP. Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write. Parameters: str: the Javascript string to copy. outPtr: Byte address in Emscripten HEAP where to write the string to. maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else. maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator. Returns the number of bytes written, EXCLUDING the null terminator.
function stringToUTF16(str, outPtr, maxBytesToWrite) {
  assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
  // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
  if (maxBytesToWrite === undefined) {
    maxBytesToWrite = 0x7FFFFFFF;
  }
  if (maxBytesToWrite < 2) return 0;
  maxBytesToWrite -= 2; // Null terminator.
  var startPtr = outPtr;
  var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length;
  for (var i = 0; i < numCharsToWrite; ++i) {
    // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
    var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
    HEAP16[((outPtr)>>1)]=codeUnit;
    outPtr += 2;
  }
  // Null-terminate the pointer to the HEAP.
  HEAP16[((outPtr)>>1)]=0;
  return outPtr - startPtr;
}