MCPcopy Create free account
hub / github.com/bewcloud/bewcloud / utf8ToBytes

Function utf8ToBytes

lib/models/dav.js:3526–3604  ·  view source on GitHub ↗
(string, units)

Source from the content-addressed store, hash-verified

3524}
3525
3526function utf8ToBytes (string, units) {
3527 units = units || Infinity;
3528 var codePoint;
3529 var length = string.length;
3530 var leadSurrogate = null;
3531 var bytes = [];
3532
3533 for (var i = 0; i < length; ++i) {
3534 codePoint = string.charCodeAt(i);
3535
3536 // is surrogate component
3537 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3538 // last char was a lead
3539 if (!leadSurrogate) {
3540 // no lead yet
3541 if (codePoint > 0xDBFF) {
3542 // unexpected trail
3543 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3544 continue
3545 } else if (i + 1 === length) {
3546 // unpaired lead
3547 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3548 continue
3549 }
3550
3551 // valid lead
3552 leadSurrogate = codePoint;
3553
3554 continue
3555 }
3556
3557 // 2 leads in a row
3558 if (codePoint < 0xDC00) {
3559 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3560 leadSurrogate = codePoint;
3561 continue
3562 }
3563
3564 // valid surrogate pair
3565 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
3566 } else if (leadSurrogate) {
3567 // valid bmp char, but last char was a lead
3568 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3569 }
3570
3571 leadSurrogate = null;
3572
3573 // encode utf8
3574 if (codePoint < 0x80) {
3575 if ((units -= 1) < 0) break
3576 bytes.push(codePoint);
3577 } else if (codePoint < 0x800) {
3578 if ((units -= 2) < 0) break
3579 bytes.push(
3580 codePoint >> 0x6 | 0xC0,
3581 codePoint & 0x3F | 0x80
3582 );
3583 } else if (codePoint < 0x10000) {

Callers 3

byteLengthFunction · 0.85
utf8WriteFunction · 0.85
dav.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected