aboutsummaryrefslogtreecommitdiff
path: root/mojo/public/js/new_bindings/unicode.js
blob: 6ed8839c3fbe5fcf29f0a2cb245b227b8ad77681 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Defines functions for translating between JavaScript strings and UTF8 strings
 * stored in ArrayBuffers. There is much room for optimization in this code if
 * it proves necessary.
 */
(function() {
  var internal = mojo.internal;

  /**
   * Decodes the UTF8 string from the given buffer.
   * @param {ArrayBufferView} buffer The buffer containing UTF8 string data.
   * @return {string} The corresponding JavaScript string.
   */
  function decodeUtf8String(buffer) {
    return decodeURIComponent(escape(String.fromCharCode.apply(null, buffer)));
  }

  /**
   * Encodes the given JavaScript string into UTF8.
   * @param {string} str The string to encode.
   * @param {ArrayBufferView} outputBuffer The buffer to contain the result.
   * Should be pre-allocated to hold enough space. Use |utf8Length| to determine
   * how much space is required.
   * @return {number} The number of bytes written to |outputBuffer|.
   */
  function encodeUtf8String(str, outputBuffer) {
    var utf8String = unescape(encodeURIComponent(str));
    if (outputBuffer.length < utf8String.length)
      throw new Error("Buffer too small for encodeUtf8String");
    for (var i = 0; i < outputBuffer.length && i < utf8String.length; i++)
      outputBuffer[i] = utf8String.charCodeAt(i);
    return i;
  }

  /**
   * Returns the number of bytes that a UTF8 encoding of the JavaScript string
   * |str| would occupy.
   */
  function utf8Length(str) {
    var utf8String = unescape(encodeURIComponent(str));
    return utf8String.length;
  }

  internal.decodeUtf8String = decodeUtf8String;
  internal.encodeUtf8String = encodeUtf8String;
  internal.utf8Length = utf8Length;
})();