(string, units)
| 1730 | } |
| 1731 | |
| 1732 | function utf8ToBytes (string, units) { |
| 1733 | units = units || Infinity |
| 1734 | var codePoint |
| 1735 | var length = string.length |
| 1736 | var leadSurrogate = null |
| 1737 | var bytes = [] |
| 1738 | |
| 1739 | for (var i = 0; i < length; ++i) { |
| 1740 | codePoint = string.charCodeAt(i) |
| 1741 | |
| 1742 | // is surrogate component |
| 1743 | if (codePoint > 0xD7FF && codePoint < 0xE000) { |
| 1744 | // last char was a lead |
| 1745 | if (!leadSurrogate) { |
| 1746 | // no lead yet |
| 1747 | if (codePoint > 0xDBFF) { |
| 1748 | // unexpected trail |
| 1749 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) |
| 1750 | continue |
| 1751 | } else if (i + 1 === length) { |
| 1752 | // unpaired lead |
| 1753 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) |
| 1754 | continue |
| 1755 | } |
| 1756 | |
| 1757 | // valid lead |
| 1758 | leadSurrogate = codePoint |
| 1759 | |
| 1760 | continue |
| 1761 | } |
| 1762 | |
| 1763 | // 2 leads in a row |
| 1764 | if (codePoint < 0xDC00) { |
| 1765 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) |
| 1766 | leadSurrogate = codePoint |
| 1767 | continue |
| 1768 | } |
| 1769 | |
| 1770 | // valid surrogate pair |
| 1771 | codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 |
| 1772 | } else if (leadSurrogate) { |
| 1773 | // valid bmp char, but last char was a lead |
| 1774 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) |
| 1775 | } |
| 1776 | |
| 1777 | leadSurrogate = null |
| 1778 | |
| 1779 | // encode utf8 |
| 1780 | if (codePoint < 0x80) { |
| 1781 | if ((units -= 1) < 0) break |
| 1782 | bytes.push(codePoint) |
| 1783 | } else if (codePoint < 0x800) { |
| 1784 | if ((units -= 2) < 0) break |
| 1785 | bytes.push( |
| 1786 | codePoint >> 0x6 | 0xC0, |
| 1787 | codePoint & 0x3F | 0x80 |
| 1788 | ) |
| 1789 | } else if (codePoint < 0x10000) { |
no test coverage detected
searching dependent graphs…