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 */
| 845 | * -1 error |
| 846 | */ |
| 847 | static int json_append_unicode_escape(json_parse_t *json) |
| 848 | { |
| 849 | char utf8[4]; /* Surrogate pairs require 4 UTF-8 bytes */ |
| 850 | int codepoint; |
| 851 | int surrogate_low; |
| 852 | int len; |
| 853 | int escape_len = 6; |
| 854 | |
| 855 | /* Fetch UTF-16 code unit */ |
| 856 | codepoint = decode_hex4(json->ptr + 2); |
| 857 | if (codepoint < 0) |
| 858 | return -1; |
| 859 | |
| 860 | /* UTF-16 surrogate pairs take the following 2 byte form: |
| 861 | * 11011 x yyyyyyyyyy |
| 862 | * When x = 0: y is the high 10 bits of the codepoint |
| 863 | * x = 1: y is the low 10 bits of the codepoint |
| 864 | * |
| 865 | * Check for a surrogate pair (high or low) */ |
| 866 | if ((codepoint & 0xF800) == 0xD800) { |
| 867 | /* Error if the 1st surrogate is not high */ |
| 868 | if (codepoint & 0x400) |
| 869 | return -1; |
| 870 | |
| 871 | /* Ensure the next code is a unicode escape */ |
| 872 | if (*(json->ptr + escape_len) != '\\' || |
| 873 | *(json->ptr + escape_len + 1) != 'u') { |
| 874 | return -1; |
| 875 | } |
| 876 | |
| 877 | /* Fetch the next codepoint */ |
| 878 | surrogate_low = decode_hex4(json->ptr + 2 + escape_len); |
| 879 | if (surrogate_low < 0) |
| 880 | return -1; |
| 881 | |
| 882 | /* Error if the 2nd code is not a low surrogate */ |
| 883 | if ((surrogate_low & 0xFC00) != 0xDC00) |
| 884 | return -1; |
| 885 | |
| 886 | /* Calculate Unicode codepoint */ |
| 887 | codepoint = (codepoint & 0x3FF) << 10; |
| 888 | surrogate_low &= 0x3FF; |
| 889 | codepoint = (codepoint | surrogate_low) + 0x10000; |
| 890 | escape_len = 12; |
| 891 | } |
| 892 | |
| 893 | /* Convert codepoint to UTF-8 */ |
| 894 | len = codepoint_to_utf8(utf8, codepoint); |
| 895 | if (!len) |
| 896 | return -1; |
| 897 | |
| 898 | /* Append bytes and advance parse index */ |
| 899 | strbuf_append_mem_unsafe(json->tmp, utf8, len); |
| 900 | json->ptr += escape_len; |
| 901 | |
| 902 | return 0; |
| 903 | } |
| 904 |
no test coverage detected