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(function() { 11 var internal = mojo.internal; 12 var textDecoder = new TextDecoder('utf-8'); 13 var textEncoder = new TextEncoder('utf-8'); 14 15 /** 16 * Decodes the UTF8 string from the given buffer. 17 * @param {ArrayBufferView} buffer The buffer containing UTF8 string data. 18 * @return {string} The corresponding JavaScript string. 19 */ 20 function decodeUtf8String(buffer) { 21 return textDecoder.decode(buffer); 22 } 23 24 /** 25 * Encodes the given JavaScript string into UTF8. 26 * @param {string} str The string to encode. 27 * @param {ArrayBufferView} outputBuffer The buffer to contain the result. 28 * Should be pre-allocated to hold enough space. Use |utf8Length| to determine 29 * how much space is required. 30 * @return {number} The number of bytes written to |outputBuffer|. 31 */ 32 function encodeUtf8String(str, outputBuffer) { 33 const utf8Buffer = textEncoder.encode(str); 34 if (outputBuffer.length < utf8Buffer.length) 35 throw new Error("Buffer too small for encodeUtf8String"); 36 outputBuffer.set(utf8Buffer); 37 return utf8Buffer.length; 38 } 39 40 /** 41 * Returns the number of bytes that a UTF8 encoding of the JavaScript string 42 * |str| would occupy. 43 */ 44 function utf8Length(str) { 45 return textEncoder.encode(str).length; 46 } 47 48 internal.decodeUtf8String = decodeUtf8String; 49 internal.encodeUtf8String = encodeUtf8String; 50 internal.utf8Length = utf8Length; 51})(); 52