MCPcopy Create free account
hub / github.com/reactjs/react-rails / utf8ToBytes

Function utf8ToBytes

lib/assets/javascripts/JSXTransformer.js:1645–1724  ·  view source on GitHub ↗
(string, units)

Source from the content-addressed store, hash-verified

1643}
1644
1645function utf8ToBytes (string, units) {
1646 units = units || Infinity
1647 var codePoint
1648 var length = string.length
1649 var leadSurrogate = null
1650 var bytes = []
1651 var i = 0
1652
1653 for (; i < length; i++) {
1654 codePoint = string.charCodeAt(i)
1655
1656 // is surrogate component
1657 if (codePoint > 0xD7FF && codePoint < 0xE000) {
1658 // last char was a lead
1659 if (leadSurrogate) {
1660 // 2 leads in a row
1661 if (codePoint < 0xDC00) {
1662 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1663 leadSurrogate = codePoint
1664 continue
1665 } else {
1666 // valid surrogate pair
1667 codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
1668 leadSurrogate = null
1669 }
1670 } else {
1671 // no lead yet
1672
1673 if (codePoint > 0xDBFF) {
1674 // unexpected trail
1675 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1676 continue
1677 } else if (i + 1 === length) {
1678 // unpaired lead
1679 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1680 continue
1681 } else {
1682 // valid lead
1683 leadSurrogate = codePoint
1684 continue
1685 }
1686 }
1687 } else if (leadSurrogate) {
1688 // valid bmp char, but last char was a lead
1689 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1690 leadSurrogate = null
1691 }
1692
1693 // encode utf8
1694 if (codePoint < 0x80) {
1695 if ((units -= 1) < 0) break
1696 bytes.push(codePoint)
1697 } else if (codePoint < 0x800) {
1698 if ((units -= 2) < 0) break
1699 bytes.push(
1700 codePoint >> 0x6 | 0xC0,
1701 codePoint & 0x3F | 0x80
1702 )

Callers 2

JSXTransformer.jsFile · 0.85
utf8WriteFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected