MCPcopy Create free account
hub / github.com/bitpay/bitcore-message / utf8ToBytes

Function utf8ToBytes

bitcore-message.js:1960–2038  ·  view source on GitHub ↗
(string, units)

Source from the content-addressed store, hash-verified

1958}
1959
1960function utf8ToBytes (string, units) {
1961 units = units || Infinity
1962 var codePoint
1963 var length = string.length
1964 var leadSurrogate = null
1965 var bytes = []
1966
1967 for (var i = 0; i < length; ++i) {
1968 codePoint = string.charCodeAt(i)
1969
1970 // is surrogate component
1971 if (codePoint > 0xD7FF && codePoint < 0xE000) {
1972 // last char was a lead
1973 if (!leadSurrogate) {
1974 // no lead yet
1975 if (codePoint > 0xDBFF) {
1976 // unexpected trail
1977 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1978 continue
1979 } else if (i + 1 === length) {
1980 // unpaired lead
1981 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1982 continue
1983 }
1984
1985 // valid lead
1986 leadSurrogate = codePoint
1987
1988 continue
1989 }
1990
1991 // 2 leads in a row
1992 if (codePoint < 0xDC00) {
1993 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1994 leadSurrogate = codePoint
1995 continue
1996 }
1997
1998 // valid surrogate pair
1999 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2000 } else if (leadSurrogate) {
2001 // valid bmp char, but last char was a lead
2002 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2003 }
2004
2005 leadSurrogate = null
2006
2007 // encode utf8
2008 if (codePoint < 0x80) {
2009 if ((units -= 1) < 0) break
2010 bytes.push(codePoint)
2011 } else if (codePoint < 0x800) {
2012 if ((units -= 2) < 0) break
2013 bytes.push(
2014 codePoint >> 0x6 | 0xC0,
2015 codePoint & 0x3F | 0x80
2016 )
2017 } else if (codePoint < 0x10000) {

Callers 3

byteLengthFunction · 0.85
utf8WriteFunction · 0.85
bitcore-message.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected