Path: blob/master/node_modules/@protobufjs/utf8/index.js
1129 views
"use strict";12/**3* A minimal UTF8 implementation for number arrays.4* @memberof util5* @namespace6*/7var utf8 = exports;89/**10* Calculates the UTF8 byte length of a string.11* @param {string} string String12* @returns {number} Byte length13*/14utf8.length = function utf8_length(string) {15var len = 0,16c = 0;17for (var i = 0; i < string.length; ++i) {18c = string.charCodeAt(i);19if (c < 128)20len += 1;21else if (c < 2048)22len += 2;23else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {24++i;25len += 4;26} else27len += 3;28}29return len;30};3132/**33* Reads UTF8 bytes as a string.34* @param {Uint8Array} buffer Source buffer35* @param {number} start Source start36* @param {number} end Source end37* @returns {string} String read38*/39utf8.read = function utf8_read(buffer, start, end) {40var len = end - start;41if (len < 1)42return "";43var parts = null,44chunk = [],45i = 0, // char offset46t; // temporary47while (start < end) {48t = buffer[start++];49if (t < 128)50chunk[i++] = t;51else if (t > 191 && t < 224)52chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;53else if (t > 239 && t < 365) {54t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;55chunk[i++] = 0xD800 + (t >> 10);56chunk[i++] = 0xDC00 + (t & 1023);57} else58chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;59if (i > 8191) {60(parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));61i = 0;62}63}64if (parts) {65if (i)66parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));67return parts.join("");68}69return String.fromCharCode.apply(String, chunk.slice(0, i));70};7172/**73* Writes a string as UTF8 bytes.74* @param {string} string Source string75* @param {Uint8Array} buffer Destination buffer76* @param {number} offset Destination offset77* @returns {number} Bytes written78*/79utf8.write = function utf8_write(string, buffer, offset) {80var start = offset,81c1, // character 182c2; // character 283for (var i = 0; i < string.length; ++i) {84c1 = string.charCodeAt(i);85if (c1 < 128) {86buffer[offset++] = c1;87} else if (c1 < 2048) {88buffer[offset++] = c1 >> 6 | 192;89buffer[offset++] = c1 & 63 | 128;90} else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {91c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);92++i;93buffer[offset++] = c1 >> 18 | 240;94buffer[offset++] = c1 >> 12 & 63 | 128;95buffer[offset++] = c1 >> 6 & 63 | 128;96buffer[offset++] = c1 & 63 | 128;97} else {98buffer[offset++] = c1 >> 12 | 224;99buffer[offset++] = c1 >> 6 & 63 | 128;100buffer[offset++] = c1 & 63 | 128;101}102}103return offset - start;104};105106107