+ # Returns `self` with all characters escaped with their UTF-16 representation
+ #
+ # assert "Aรจใ๐".escape_to_utf16 == "\\u0041\\u00e8\\u3042\\ud800\\udfd3"
+ fun escape_to_utf16: String do
+ var buf = new Buffer
+ for i in chars do buf.append i.escape_to_utf16
+ return buf.to_s
+ end
+
+ # Returns the Unicode char escaped by `self`
+ #
+ # assert "\\u0041".from_utf16_escape == 'A'
+ # assert "\\ud800\\udfd3".from_utf16_escape == '๐'
+ # assert "\\u00e8".from_utf16_escape == 'รจ'
+ # assert "\\u3042".from_utf16_escape == 'ใ'
+ fun from_utf16_escape(pos, ln: nullable Int): Char do
+ if pos == null then pos = 0
+ if ln == null then ln = length - pos
+ if ln < 6 then return 0xFFFD.code_point
+ var cp = from_utf16_digit(pos + 2)
+ if cp < 0xD800 then return cp.code_point
+ if cp > 0xDFFF then return cp.code_point
+ if cp > 0xDBFF then return 0xFFFD.code_point
+ if ln == 6 then return 0xFFFD.code_point
+ if ln < 12 then return 0xFFFD.code_point
+ cp <<= 16
+ cp += from_utf16_digit(pos + 8)
+ var cplo = cp & 0xFFFF
+ if cplo < 0xDC00 then return 0xFFFD.code_point
+ if cplo > 0xDFFF then return 0xFFFD.code_point
+ return cp.from_utf16_surr.code_point
+ end
+
+ # Returns a UTF-16 escape value
+ #
+ # var s = "\\ud800\\udfd3"
+ # assert s.from_utf16_digit(2) == 0xD800
+ # assert s.from_utf16_digit(8) == 0xDFD3
+ fun from_utf16_digit(pos: nullable Int): Int do
+ if pos == null then pos = 0
+ return to_hex(pos, 4)
+ end
+