1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 /** 6 * Defines functions for translating between JavaScript strings and UTF8 strings 7 * stored in ArrayBuffers. There is much room for optimization in this code if 8 * it proves necessary. 9 */ 10 define("mojo/public/js/unicode", function() { 11 /** 12 * Decodes the UTF8 string from the given buffer. 13 * @param {ArrayBufferView} buffer The buffer containing UTF8 string data. 14 * @return {string} The corresponding JavaScript string. 15 */ 16 function decodeUtf8String(buffer) { 17 return decodeURIComponent(escape(String.fromCharCode.apply(null, buffer))); 18 } 19 20 /** 21 * Encodes the given JavaScript string into UTF8. 22 * @param {string} str The string to encode. 23 * @param {ArrayBufferView} outputBuffer The buffer to contain the result. 24 * Should be pre-allocated to hold enough space. Use |utf8Length| to determine 25 * how much space is required. 26 * @return {number} The number of bytes written to |outputBuffer|. 27 */ 28 function encodeUtf8String(str, outputBuffer) { 29 var utf8String = unescape(encodeURIComponent(str)); 30 if (outputBuffer.length < utf8String.length) 31 throw new Error("Buffer too small for encodeUtf8String"); 32 for (var i = 0; i < outputBuffer.length && i < utf8String.length; i++) 33 outputBuffer[i] = utf8String.charCodeAt(i); 34 return i; 35 } 36 37 /** 38 * Returns the number of bytes that a UTF8 encoding of the JavaScript string 39 * |str| would occupy. 40 */ 41 function utf8Length(str) { 42 var utf8String = unescape(encodeURIComponent(str)); 43 return utf8String.length; 44 } 45 46 var exports = {}; 47 exports.decodeUtf8String = decodeUtf8String; 48 exports.encodeUtf8String = encodeUtf8String; 49 exports.utf8Length = utf8Length; 50 return exports; 51 }); 52