Called when index pointing to beginning of UTF-16 code escape: \uXXXX * \u is guaranteed to exist, but the remaining hex characters may be * missing. * Translate to UTF-8 and append to temporary token string. * Must advance index to the next character to be processed. * Returns: 0 success * -1 error */
| 817 | * -1 error |
| 818 | */ |
| 819 | static int json_append_unicode_escape(json_parse_t *json) |
| 820 | { |
| 821 | char utf8[4]; /* Surrogate pairs require 4 UTF-8 bytes */ |
| 822 | int codepoint; |
| 823 | int surrogate_low; |
| 824 | int len; |
| 825 | int escape_len = 6; |
| 826 | |
| 827 | /* Fetch UTF-16 code unit */ |
| 828 | codepoint = decode_hex4(json->ptr + 2); |
| 829 | if (codepoint < 0) |
| 830 | return -1; |
| 831 | |
| 832 | /* UTF-16 surrogate pairs take the following 2 byte form: |
| 833 | * 11011 x yyyyyyyyyy |
| 834 | * When x = 0: y is the high 10 bits of the codepoint |
| 835 | * x = 1: y is the low 10 bits of the codepoint |
| 836 | * |
| 837 | * Check for a surrogate pair (high or low) */ |
| 838 | if ((codepoint & 0xF800) == 0xD800) { |
| 839 | /* Error if the 1st surrogate is not high */ |
| 840 | if (codepoint & 0x400) |
| 841 | return -1; |
| 842 | |
| 843 | /* Ensure the next code is a unicode escape */ |
| 844 | if (*(json->ptr + escape_len) != '\\' || |
| 845 | *(json->ptr + escape_len + 1) != 'u') { |
| 846 | return -1; |
| 847 | } |
| 848 | |
| 849 | /* Fetch the next codepoint */ |
| 850 | surrogate_low = decode_hex4(json->ptr + 2 + escape_len); |
| 851 | if (surrogate_low < 0) |
| 852 | return -1; |
| 853 | |
| 854 | /* Error if the 2nd code is not a low surrogate */ |
| 855 | if ((surrogate_low & 0xFC00) != 0xDC00) |
| 856 | return -1; |
| 857 | |
| 858 | /* Calculate Unicode codepoint */ |
| 859 | codepoint = (codepoint & 0x3FF) << 10; |
| 860 | surrogate_low &= 0x3FF; |
| 861 | codepoint = (codepoint | surrogate_low) + 0x10000; |
| 862 | escape_len = 12; |
| 863 | } |
| 864 | |
| 865 | /* Convert codepoint to UTF-8 */ |
| 866 | len = codepoint_to_utf8(utf8, codepoint); |
| 867 | if (!len) |
| 868 | return -1; |
| 869 | |
| 870 | /* Append bytes and advance parse index */ |
| 871 | strbuf_append_mem_unsafe(json->tmp, utf8, len); |
| 872 | json->ptr += escape_len; |
| 873 | |
| 874 | return 0; |
| 875 | } |
| 876 |
no test coverage detected