1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
// REQUIRES: rdar49634697
// REQUIRES: rdar55727144
#if canImport(TestSupport)
import TestSupport
#endif // canImport(TestSupport)
#if canImport(FoundationEssentials)
@_spi(SwiftCorelibsFoundation)
@testable import FoundationEssentials
#endif
#if FOUNDATION_FRAMEWORK
@testable import Foundation
#endif
// MARK: - Test Suite
final class JSONEncoderTests : XCTestCase {
// MARK: - Encoding Top-Level Empty Types
func testEncodingTopLevelEmptyStruct() {
let empty = EmptyStruct()
_testRoundTrip(of: empty, expectedJSON: _jsonEmptyDictionary)
}
func testEncodingTopLevelEmptyClass() {
let empty = EmptyClass()
_testRoundTrip(of: empty, expectedJSON: _jsonEmptyDictionary)
}
// MARK: - Encoding Top-Level Single-Value Types
func testEncodingTopLevelSingleValueEnum() {
_testRoundTrip(of: Switch.off)
_testRoundTrip(of: Switch.on)
}
func testEncodingTopLevelSingleValueStruct() {
_testRoundTrip(of: Timestamp(3141592653))
}
func testEncodingTopLevelSingleValueClass() {
_testRoundTrip(of: Counter())
}
// MARK: - Encoding Top-Level Structured Types
func testEncodingTopLevelStructuredStruct() {
// Address is a struct type with multiple fields.
let address = Address.testValue
_testRoundTrip(of: address)
}
func testEncodingTopLevelStructuredSingleStruct() {
// Numbers is a struct which encodes as an array through a single value container.
let numbers = Numbers.testValue
_testRoundTrip(of: numbers)
}
func testEncodingTopLevelStructuredSingleClass() {
// Mapping is a class which encodes as a dictionary through a single value container.
let mapping = Mapping.testValue
_testRoundTrip(of: mapping)
}
func testEncodingTopLevelDeepStructuredType() {
// Company is a type with fields which are Codable themselves.
let company = Company.testValue
_testRoundTrip(of: company)
}
func testEncodingClassWhichSharesEncoderWithSuper() {
// Employee is a type which shares its encoder & decoder with its superclass, Person.
let employee = Employee.testValue
_testRoundTrip(of: employee)
}
func testEncodingTopLevelNullableType() {
// EnhancedBool is a type which encodes either as a Bool or as nil.
_testRoundTrip(of: EnhancedBool.true, expectedJSON: "true".data(using: String._Encoding.utf8)!)
_testRoundTrip(of: EnhancedBool.false, expectedJSON: "false".data(using: String._Encoding.utf8)!)
_testRoundTrip(of: EnhancedBool.fileNotFound, expectedJSON: "null".data(using: String._Encoding.utf8)!)
}
func testEncodingTopLevelArrayOfInt() {
let a = [1,2,3]
let result1 = String(data: try! JSONEncoder().encode(a), encoding: String._Encoding.utf8)
XCTAssertEqual(result1, "[1,2,3]")
let b : [Int] = []
let result2 = String(data: try! JSONEncoder().encode(b), encoding: String._Encoding.utf8)
XCTAssertEqual(result2, "[]")
}
@available(FoundationPreview 0.1, *)
func testEncodingTopLevelWithConfiguration() throws {
// CodableTypeWithConfiguration is a struct that conforms to CodableWithConfiguration
let value = CodableTypeWithConfiguration.testValue
let encoder = JSONEncoder()
let decoder = JSONDecoder()
var decoded = try decoder.decode(CodableTypeWithConfiguration.self, from: try encoder.encode(value, configuration: .init(1)), configuration: .init(1))
XCTAssertEqual(decoded, value)
decoded = try decoder.decode(CodableTypeWithConfiguration.self, from: try encoder.encode(value, configuration: CodableTypeWithConfiguration.ConfigProviding.self), configuration: CodableTypeWithConfiguration.ConfigProviding.self)
XCTAssertEqual(decoded, value)
}
#if false // FIXME: XCTest doesn't support crash tests yet rdar://20195010&22387653
func testEncodingConflictedTypeNestedContainersWithTheSameTopLevelKey() {
struct Model : Encodable, Equatable {
let first: String
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: TopLevelCodingKeys.self)
var firstNestedContainer = container.nestedContainer(keyedBy: FirstNestedCodingKeys.self, forKey: .top)
try firstNestedContainer.encode(self.first, forKey: .first)
// The following line would fail as it attempts to re-encode into already encoded container is invalid. This will always fail
var secondNestedContainer = container.nestedUnkeyedContainer(forKey: .top)
try secondNestedContainer.encode("second")
}
init(first: String) {
self.first = first
}
static var testValue: Model {
return Model(first: "Johnny Appleseed")
}
enum TopLevelCodingKeys : String, CodingKey {
case top
}
enum FirstNestedCodingKeys : String, CodingKey {
case first
}
}
let model = Model.testValue
// This following test would fail as it attempts to re-encode into already encoded container is invalid. This will always fail
expectCrashLater()
_testEncodeFailure(of: model)
}
#endif
// MARK: - Date Strategy Tests
func testEncodingDateSecondsSince1970() {
// Cannot encode an arbitrary number of seconds since we've lost precision since 1970.
let seconds = 1000.0
let expectedJSON = "1000".data(using: String._Encoding.utf8)!
_testRoundTrip(of: Date(timeIntervalSince1970: seconds),
expectedJSON: expectedJSON,
dateEncodingStrategy: .secondsSince1970,
dateDecodingStrategy: .secondsSince1970)
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(Date(timeIntervalSince1970: seconds)),
expectedJSON: expectedJSON,
dateEncodingStrategy: .secondsSince1970,
dateDecodingStrategy: .secondsSince1970)
}
func testEncodingDateMillisecondsSince1970() {
// Cannot encode an arbitrary number of seconds since we've lost precision since 1970.
let seconds = 1000.0
let expectedJSON = "1000000".data(using: String._Encoding.utf8)!
_testRoundTrip(of: Date(timeIntervalSince1970: seconds),
expectedJSON: expectedJSON,
dateEncodingStrategy: .millisecondsSince1970,
dateDecodingStrategy: .millisecondsSince1970)
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(Date(timeIntervalSince1970: seconds)),
expectedJSON: expectedJSON,
dateEncodingStrategy: .millisecondsSince1970,
dateDecodingStrategy: .millisecondsSince1970)
}
func testEncodingDateCustom() {
let timestamp = Date()
// We'll encode a number instead of a date.
let encode = { @Sendable (_ data: Date, _ encoder: Encoder) throws -> Void in
var container = encoder.singleValueContainer()
try container.encode(42)
}
let decode = { @Sendable (_: Decoder) throws -> Date in return timestamp }
let expectedJSON = "42".data(using: String._Encoding.utf8)!
_testRoundTrip(of: timestamp,
expectedJSON: expectedJSON,
dateEncodingStrategy: .custom(encode),
dateDecodingStrategy: .custom(decode))
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .custom(encode),
dateDecodingStrategy: .custom(decode))
}
func testEncodingDateCustomEmpty() {
let timestamp = Date()
// Encoding nothing should encode an empty keyed container ({}).
let encode = { @Sendable (_: Date, _: Encoder) throws -> Void in }
let decode = { @Sendable (_: Decoder) throws -> Date in return timestamp }
let expectedJSON = "{}".data(using: String._Encoding.utf8)!
_testRoundTrip(of: timestamp,
expectedJSON: expectedJSON,
dateEncodingStrategy: .custom(encode),
dateDecodingStrategy: .custom(decode))
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .custom(encode),
dateDecodingStrategy: .custom(decode))
}
// MARK: - Data Strategy Tests
func testEncodingData() {
let data = Data([0xDE, 0xAD, 0xBE, 0xEF])
let expectedJSON = "[222,173,190,239]".data(using: String._Encoding.utf8)!
_testRoundTrip(of: data,
expectedJSON: expectedJSON,
dataEncodingStrategy: .deferredToData,
dataDecodingStrategy: .deferredToData)
// Optional data should encode the same way.
_testRoundTrip(of: Optional(data),
expectedJSON: expectedJSON,
dataEncodingStrategy: .deferredToData,
dataDecodingStrategy: .deferredToData)
}
func testEncodingDataCustom() {
// We'll encode a number instead of data.
let encode = { @Sendable (_ data: Data, _ encoder: Encoder) throws -> Void in
var container = encoder.singleValueContainer()
try container.encode(42)
}
let decode = { @Sendable (_: Decoder) throws -> Data in return Data() }
let expectedJSON = "42".data(using: String._Encoding.utf8)!
_testRoundTrip(of: Data(),
expectedJSON: expectedJSON,
dataEncodingStrategy: .custom(encode),
dataDecodingStrategy: .custom(decode))
// Optional data should encode the same way.
_testRoundTrip(of: Optional(Data()),
expectedJSON: expectedJSON,
dataEncodingStrategy: .custom(encode),
dataDecodingStrategy: .custom(decode))
}
func testEncodingDataCustomEmpty() {
// Encoding nothing should encode an empty keyed container ({}).
let encode = { @Sendable (_: Data, _: Encoder) throws -> Void in }
let decode = { @Sendable (_: Decoder) throws -> Data in return Data() }
let expectedJSON = "{}".data(using: String._Encoding.utf8)!
_testRoundTrip(of: Data(),
expectedJSON: expectedJSON,
dataEncodingStrategy: .custom(encode),
dataDecodingStrategy: .custom(decode))
// Optional Data should encode the same way.
_testRoundTrip(of: Optional(Data()),
expectedJSON: expectedJSON,
dataEncodingStrategy: .custom(encode),
dataDecodingStrategy: .custom(decode))
}
// MARK: - Non-Conforming Floating Point Strategy Tests
func testEncodingNonConformingFloats() {
_testEncodeFailure(of: Float.infinity)
_testEncodeFailure(of: Float.infinity)
_testEncodeFailure(of: -Float.infinity)
_testEncodeFailure(of: Float.nan)
_testEncodeFailure(of: Double.infinity)
_testEncodeFailure(of: -Double.infinity)
_testEncodeFailure(of: Double.nan)
// Optional Floats/Doubles should encode the same way.
_testEncodeFailure(of: Float.infinity)
_testEncodeFailure(of: -Float.infinity)
_testEncodeFailure(of: Float.nan)
_testEncodeFailure(of: Double.infinity)
_testEncodeFailure(of: -Double.infinity)
_testEncodeFailure(of: Double.nan)
}
func testEncodingNonConformingFloatStrings() {
let encodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "INF", negativeInfinity: "-INF", nan: "NaN")
let decodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "INF", negativeInfinity: "-INF", nan: "NaN")
_testRoundTrip(of: Float.infinity,
expectedJSON: "\"INF\"".data(using: String._Encoding.utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: -Float.infinity,
expectedJSON: "\"-INF\"".data(using: String._Encoding.utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
// Since Float.nan != Float.nan, we have to use a placeholder that'll encode NaN but actually round-trip.
_testRoundTrip(of: FloatNaNPlaceholder(),
expectedJSON: "\"NaN\"".data(using: String._Encoding.utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: Double.infinity,
expectedJSON: "\"INF\"".data(using: String._Encoding.utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: -Double.infinity,
expectedJSON: "\"-INF\"".data(using: String._Encoding.utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
// Since Double.nan != Double.nan, we have to use a placeholder that'll encode NaN but actually round-trip.
_testRoundTrip(of: DoubleNaNPlaceholder(),
expectedJSON: "\"NaN\"".data(using: String._Encoding.utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
// Optional Floats and Doubles should encode the same way.
_testRoundTrip(of: Optional(Float.infinity),
expectedJSON: "\"INF\"".data(using: String._Encoding.utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: Optional(-Float.infinity),
expectedJSON: "\"-INF\"".data(using: String._Encoding.utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: Optional(Double.infinity),
expectedJSON: "\"INF\"".data(using: String._Encoding.utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: Optional(-Double.infinity),
expectedJSON: "\"-INF\"".data(using: String._Encoding.utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
}
// MARK: - Key Strategy Tests
private struct EncodeMe : Encodable {
var keyName: String
func encode(to coder: Encoder) throws {
var c = coder.container(keyedBy: _TestKey.self)
try c.encode("test", forKey: _TestKey(stringValue: keyName)!)
}
}
func testEncodingKeyStrategyCustom() {
let expected = "{\"QQQhello\":\"test\"}"
let encoded = EncodeMe(keyName: "hello")
let encoder = JSONEncoder()
let customKeyConversion = { @Sendable (_ path : [CodingKey]) -> CodingKey in
let key = _TestKey(stringValue: "QQQ" + path.last!.stringValue)!
return key
}
encoder.keyEncodingStrategy = .custom(customKeyConversion)
let resultData = try! encoder.encode(encoded)
let resultString = String(bytes: resultData, encoding: String._Encoding.utf8)
XCTAssertEqual(expected, resultString)
}
private struct EncodeFailure : Encodable {
var someValue: Double
}
private struct EncodeFailureNested : Encodable {
var nestedValue: EncodeFailure
}
private struct EncodeNested : Encodable {
let nestedValue: EncodeMe
}
private struct EncodeNestedNested : Encodable {
let outerValue: EncodeNested
}
func testEncodingKeyStrategyPath() {
// Make sure a more complex path shows up the way we want
// Make sure the path reflects keys in the Swift, not the resulting ones in the JSON
let expected = "{\"QQQouterValue\":{\"QQQnestedValue\":{\"QQQhelloWorld\":\"test\"}}}"
let encoded = EncodeNestedNested(outerValue: EncodeNested(nestedValue: EncodeMe(keyName: "helloWorld")))
let encoder = JSONEncoder()
// We only will mutate this from one thread as we call the encoder synchronously
nonisolated(unsafe) var callCount = 0
let customKeyConversion = { @Sendable (_ path : [CodingKey]) -> CodingKey in
// This should be called three times:
// 1. to convert 'outerValue' to something
// 2. to convert 'nestedValue' to something
// 3. to convert 'helloWorld' to something
callCount = callCount + 1
if path.count == 0 {
XCTFail("The path should always have at least one entry")
} else if path.count == 1 {
XCTAssertEqual(["outerValue"], path.map { $0.stringValue })
} else if path.count == 2 {
XCTAssertEqual(["outerValue", "nestedValue"], path.map { $0.stringValue })
} else if path.count == 3 {
XCTAssertEqual(["outerValue", "nestedValue", "helloWorld"], path.map { $0.stringValue })
} else {
XCTFail("The path mysteriously had more entries")
}
let key = _TestKey(stringValue: "QQQ" + path.last!.stringValue)!
return key
}
encoder.keyEncodingStrategy = .custom(customKeyConversion)
let resultData = try! encoder.encode(encoded)
let resultString = String(bytes: resultData, encoding: String._Encoding.utf8)
XCTAssertEqual(expected, resultString)
XCTAssertEqual(3, callCount)
}
private struct DecodeMe : Decodable {
let found: Bool
init(from coder: Decoder) throws {
let c = try coder.container(keyedBy: _TestKey.self)
// Get the key that we expect to be passed in (camel case)
let camelCaseKey = try c.decode(String.self, forKey: _TestKey(stringValue: "camelCaseKey")!)
// Use the camel case key to decode from the JSON. The decoder should convert it to snake case to find it.
found = try c.decode(Bool.self, forKey: _TestKey(stringValue: camelCaseKey)!)
}
}
private struct DecodeMe2 : Decodable { var hello: String }
func testDecodingKeyStrategyCustom() {
let input = "{\"----hello\":\"test\"}".data(using: String._Encoding.utf8)!
let decoder = JSONDecoder()
let customKeyConversion = { @Sendable (_ path: [CodingKey]) -> CodingKey in
// This converter removes the first 4 characters from the start of all string keys, if it has more than 4 characters
let string = path.last!.stringValue
guard string.count > 4 else { return path.last! }
let newString = String(string.dropFirst(4))
return _TestKey(stringValue: newString)!
}
decoder.keyDecodingStrategy = .custom(customKeyConversion)
let result = try! decoder.decode(DecodeMe2.self, from: input)
XCTAssertEqual("test", result.hello)
}
func testDecodingDictionaryStringKeyConversionUntouched() {
let input = "{\"leave_me_alone\":\"test\"}".data(using: String._Encoding.utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try! decoder.decode([String: String].self, from: input)
XCTAssertEqual(["leave_me_alone": "test"], result)
}
func testDecodingDictionaryFailureKeyPath() {
let input = "{\"leave_me_alone\":\"test\"}".data(using: String._Encoding.utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
_ = try decoder.decode([String: Int].self, from: input)
} catch DecodingError.typeMismatch(_, let context) {
XCTAssertEqual(1, context.codingPath.count)
XCTAssertEqual("leave_me_alone", context.codingPath[0].stringValue)
} catch {
XCTFail("Unexpected error: \(String(describing: error))")
}
}
private struct DecodeFailure : Decodable {
var intValue: Int
}
private struct DecodeFailureNested : Decodable {
var nestedValue: DecodeFailure
}
private struct DecodeMe3 : Codable {
var thisIsCamelCase : String
}
func testKeyStrategyDuplicateKeys() {
// This test is mostly to make sure we don't assert on duplicate keys
struct DecodeMe5 : Codable {
var oneTwo : String
var numberOfKeys : Int
enum CodingKeys : String, CodingKey {
case oneTwo
case oneTwoThree
}
init() {
oneTwo = "test"
numberOfKeys = 0
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
oneTwo = try container.decode(String.self, forKey: .oneTwo)
numberOfKeys = container.allKeys.count
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(oneTwo, forKey: .oneTwo)
try container.encode("test2", forKey: .oneTwoThree)
}
}
let customKeyConversion = { @Sendable (_ path: [CodingKey]) -> CodingKey in
// All keys are the same!
return _TestKey(stringValue: "oneTwo")!
}
// Decoding
// This input has a dictionary with two keys, but only one will end up in the container
let input = "{\"unused key 1\":\"test1\",\"unused key 2\":\"test2\"}".data(using: String._Encoding.utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom(customKeyConversion)
let decodingResult = try! decoder.decode(DecodeMe5.self, from: input)
// There will be only one result for oneTwo.
XCTAssertEqual(1, decodingResult.numberOfKeys)
// While the order in which these values should be taken is NOT defined by the JSON spec in any way, the historical behavior has been to select the *first* value for a given key.
XCTAssertEqual(decodingResult.oneTwo, "test1")
// Encoding
let encoded = DecodeMe5()
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .custom(customKeyConversion)
let decodingResultData = try! encoder.encode(encoded)
let decodingResultString = String(bytes: decodingResultData, encoding: String._Encoding.utf8)
// There will be only one value in the result (the second one encoded)
XCTAssertEqual("{\"oneTwo\":\"test2\"}", decodingResultString)
}
// MARK: - Encoder Features
func testNestedContainerCodingPaths() {
let encoder = JSONEncoder()
do {
let _ = try encoder.encode(NestedContainersTestType())
} catch let error as NSError {
XCTFail("Caught error during encoding nested container types: \(error)")
}
}
func testSuperEncoderCodingPaths() {
let encoder = JSONEncoder()
do {
let _ = try encoder.encode(NestedContainersTestType(testSuperEncoder: true))
} catch let error as NSError {
XCTFail("Caught error during encoding nested container types: \(error)")
}
}
// MARK: - Type coercion
func testTypeCoercion() {
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Int].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Int8].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Int16].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Int32].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Int64].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt8].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt16].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt32].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt64].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Float].self)
_testRoundTripTypeCoercionFailure(of: [false, true], as: [Double].self)
_testRoundTripTypeCoercionFailure(of: [0, 1] as [Int], as: [Bool].self)
_testRoundTripTypeCoercionFailure(of: [0, 1] as [Int8], as: [Bool].self)
_testRoundTripTypeCoercionFailure(of: [0, 1] as [Int16], as: [Bool].self)
_testRoundTripTypeCoercionFailure(of: [0, 1] as [Int32], as: [Bool].self)
_testRoundTripTypeCoercionFailure(of: [0, 1] as [Int64], as: [Bool].self)
_testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt], as: [Bool].self)
_testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt8], as: [Bool].self)
_testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt16], as: [Bool].self)
_testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt32], as: [Bool].self)
_testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt64], as: [Bool].self)
if #available(macOS 15.0, *) {
_testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt128], as: [Bool].self)
}
_testRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Float], as: [Bool].self)
_testRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Double], as: [Bool].self)
}
func testDecodingConcreteTypeParameter() {
let encoder = JSONEncoder()
guard let json = try? encoder.encode(Employee.testValue) else {
XCTFail("Unable to encode Employee.")
return
}
let decoder = JSONDecoder()
guard let decoded = try? decoder.decode(Employee.self as Person.Type, from: json) else {
XCTFail("Failed to decode Employee as Person from JSON.")
return
}
expectEqual(type(of: decoded), Employee.self, "Expected decoded value to be of type Employee; got \(type(of: decoded)) instead.")
}
// MARK: - Encoder State
// SR-6078
func testEncoderStateThrowOnEncode() {
struct ReferencingEncoderWrapper<T : Encodable> : Encodable {
let value: T
init(_ value: T) { self.value = value }
func encode(to encoder: Encoder) throws {
// This approximates a subclass calling into its superclass, where the superclass encodes a value that might throw.
// The key here is that getting the superEncoder creates a referencing encoder.
var container = encoder.unkeyedContainer()
let superEncoder = container.superEncoder()
// Pushing a nested container on leaves the referencing encoder with multiple containers.
var nestedContainer = superEncoder.unkeyedContainer()
try nestedContainer.encode(value)
}
}
// The structure that would be encoded here looks like
//
// [[[Float.infinity]]]
//
// The wrapper asks for an unkeyed container ([^]), gets a super encoder, and creates a nested container into that ([[^]]).
// We then encode an array into that ([[[^]]]), which happens to be a value that causes us to throw an error.
//
// The issue at hand reproduces when you have a referencing encoder (superEncoder() creates one) that has a container on the stack (unkeyedContainer() adds one) that encodes a value going through box_() (Array does that) that encodes something which throws (Float.infinity does that).
// When reproducing, this will cause a test failure via fatalError().
_ = try? JSONEncoder().encode(ReferencingEncoderWrapper([Float.infinity]))
}
func testEncoderStateThrowOnEncodeCustomDate() {
// This test is identical to testEncoderStateThrowOnEncode, except throwing via a custom Date closure.
struct ReferencingEncoderWrapper<T : Encodable> : Encodable {
let value: T
init(_ value: T) { self.value = value }
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
let superEncoder = container.superEncoder()
var nestedContainer = superEncoder.unkeyedContainer()
try nestedContainer.encode(value)
}
}
// The closure needs to push a container before throwing an error to trigger.
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .custom({ _, encoder in
let _ = encoder.unkeyedContainer()
enum CustomError : Error { case foo }
throw CustomError.foo
})
_ = try? encoder.encode(ReferencingEncoderWrapper(Date()))
}
func testEncoderStateThrowOnEncodeCustomData() {
// This test is identical to testEncoderStateThrowOnEncode, except throwing via a custom Data closure.
struct ReferencingEncoderWrapper<T : Encodable> : Encodable {
let value: T
init(_ value: T) { self.value = value }
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
let superEncoder = container.superEncoder()
var nestedContainer = superEncoder.unkeyedContainer()
try nestedContainer.encode(value)
}
}
// The closure needs to push a container before throwing an error to trigger.
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .custom({ _, encoder in
let _ = encoder.unkeyedContainer()
enum CustomError : Error { case foo }
throw CustomError.foo
})
_ = try? encoder.encode(ReferencingEncoderWrapper(Data()))
}
func test_106506794() throws {
struct Level1: Codable, Equatable {
let level2: Level2
enum CodingKeys: String, CodingKey {
case level2
}
func encode(to encoder: Encoder) throws {
var keyed = encoder.container(keyedBy: Self.CodingKeys.self)
var nested = keyed.nestedUnkeyedContainer(forKey: .level2)
try nested.encode(level2)
}
init(from decoder: Decoder) throws {
let keyed = try decoder.container(keyedBy: Self.CodingKeys.self)
var nested = try keyed.nestedUnkeyedContainer(forKey: .level2)
self.level2 = try nested.decode(Level2.self)
}
struct Level2: Codable, Equatable {
let name : String
}
init(level2: Level2) {
self.level2 = level2
}
}
let value = Level1.init(level2: .init(name: "level2"))
let data = try JSONEncoder().encode(value)
do {
let decodedValue = try JSONDecoder().decode(Level1.self, from: data)
XCTAssertEqual(value, decodedValue)
} catch {
XCTFail("Decode should not have failed with error: \(error))")
}
}
// MARK: - Decoder State
// SR-6048
func testDecoderStateThrowOnDecode() {
// The container stack here starts as [[1,2,3]]. Attempting to decode as [String] matches the outer layer (Array), and begins decoding the array.
// Once Array decoding begins, 1 is pushed onto the container stack ([[1,2,3], 1]), and 1 is attempted to be decoded as String. This throws a .typeMismatch, but the container is not popped off the stack.
// When attempting to decode [Int], the container stack is still ([[1,2,3], 1]), and 1 fails to decode as [Int].
let json = "[1,2,3]".data(using: String._Encoding.utf8)!
let _ = try! JSONDecoder().decode(EitherDecodable<[String], [Int]>.self, from: json)
}
func testDecoderStateThrowOnDecodeCustomDate() {
// This test is identical to testDecoderStateThrowOnDecode, except we're going to fail because our closure throws an error, not because we hit a type mismatch.
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom({ decoder in
enum CustomError : Error { case foo }
throw CustomError.foo
})
let json = "1".data(using: String._Encoding.utf8)!
let _ = try! decoder.decode(EitherDecodable<Date, Int>.self, from: json)
}
func testDecoderStateThrowOnDecodeCustomData() {
// This test is identical to testDecoderStateThrowOnDecode, except we're going to fail because our closure throws an error, not because we hit a type mismatch.
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .custom({ decoder in
enum CustomError : Error { case foo }
throw CustomError.foo
})
let json = "1".data(using: String._Encoding.utf8)!
let _ = try! decoder.decode(EitherDecodable<Data, Int>.self, from: json)
}
func testDecodingFailure() {
struct DecodeFailure : Decodable {
var invalid: String
}
let toDecode = "{\"invalid\": json}";
_testDecodeFailure(of: DecodeFailure.self, data: toDecode.data(using: String._Encoding.utf8)!)
}
func testDecodingFailureThrowInInitKeyedContainer() {
struct DecodeFailure : Decodable {
private enum CodingKeys: String, CodingKey {
case checkedString
}
private enum Error: Swift.Error {
case expectedError
}
var checkedString: String
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let string = try container.decode(String.self, forKey: .checkedString)
guard string == "foo" else {
throw Error.expectedError
}
self.checkedString = string // shouldn't happen
}
}
let toDecode = "{ \"checkedString\" : \"baz\" }"
_testDecodeFailure(of: DecodeFailure.self, data: toDecode.data(using: String._Encoding.utf8)!)
}
func testDecodingFailureThrowInInitSingleContainer() {
struct DecodeFailure : Decodable {
private enum Error: Swift.Error {
case expectedError
}
var checkedString: String
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
guard string == "foo" else {
throw Error.expectedError
}
self.checkedString = string // shouldn't happen
}
}
let toDecode = "{ \"checkedString\" : \"baz\" }"
_testDecodeFailure(of: DecodeFailure.self, data: toDecode.data(using: String._Encoding.utf8)!)
}
func testInvalidFragment() {
struct DecodeFailure: Decodable {
var foo: String
}
let toDecode = "\"foo"
_testDecodeFailure(of: DecodeFailure.self, data: toDecode.data(using: String._Encoding.utf8)!)
}
func testRepeatedFailedNilChecks() {
struct RepeatNilCheckDecodable : Decodable {
enum Failure : Error {
case badNil
case badValue(expected: Int, actual: Int)
}
init(from decoder: Decoder) throws {
var unkeyedContainer = try decoder.unkeyedContainer()
guard try unkeyedContainer.decodeNil() == false else {
throw Failure.badNil
}
guard try unkeyedContainer.decodeNil() == false else {
throw Failure.badNil
}
let value = try unkeyedContainer.decode(Int.self)
guard value == 1 else {
throw Failure.badValue(expected: 1, actual: value)
}
guard try unkeyedContainer.decodeNil() == false else {
throw Failure.badNil
}
guard try unkeyedContainer.decodeNil() == false else {
throw Failure.badNil
}
let value2 = try unkeyedContainer.decode(Int.self)
guard value2 == 2 else {
throw Failure.badValue(expected: 2, actual: value2)
}
guard try unkeyedContainer.decodeNil() == false else {
throw Failure.badNil
}
guard try unkeyedContainer.decodeNil() == false else {
throw Failure.badNil
}
let value3 = try unkeyedContainer.decode(Int.self)
guard value3 == 3 else {
throw Failure.badValue(expected: 3, actual: value3)
}
}
}
let json = "[1, 2, 3]".data(using: String._Encoding.utf8)!
XCTAssertNoThrow(try JSONDecoder().decode(RepeatNilCheckDecodable.self, from: json))
}
func testDelayedDecoding() throws {
// One variation is deferring the use of a container.
struct DelayedDecodable_ContainerVersion : Codable {
var _i : Int? = nil
init(_ i: Int) {
self._i = i
}
func encode(to encoder: Encoder) throws {
var c = encoder.unkeyedContainer()
try c.encode(_i!)
}
var cont : UnkeyedDecodingContainer? = nil
init(from decoder: Decoder) throws {
cont = try decoder.unkeyedContainer()
}
var i : Int {
get throws {
if let i = _i {
return i
}
var contCopy = cont!
return try contCopy.decode(Int.self)
}
}
}
let before = DelayedDecodable_ContainerVersion(42)
let data = try JSONEncoder().encode(before)
let decoded = try JSONDecoder().decode(DelayedDecodable_ContainerVersion.self, from: data)
XCTAssertNoThrow(try decoded.i)
// The other variant is deferring the use of the *top-level* decoder. This does NOT work for non-top level decoders.
struct DelayedDecodable_DecoderVersion : Codable {
var _i : Int? = nil
init(_ i: Int) {
self._i = i
}
func encode(to encoder: Encoder) throws {
var c = encoder.unkeyedContainer()
try c.encode(_i!)
}
var decoder : Decoder? = nil
init(from decoder: Decoder) throws {
self.decoder = decoder
}
var i : Int {
get throws {
if let i = _i {
return i
}
var unkeyed = try decoder!.unkeyedContainer()
return try unkeyed.decode(Int.self)
}
}
}
// Reuse the same data.
let decoded2 = try JSONDecoder().decode(DelayedDecodable_DecoderVersion.self, from: data)
XCTAssertNoThrow(try decoded2.i)
}
// MARK: - Helper Functions
private var _jsonEmptyDictionary: Data {
return "{}".data(using: String._Encoding.utf8)!
}
private func _testEncodeFailure<T : Encodable>(of value: T) {
do {
let _ = try JSONEncoder().encode(value)
XCTFail("Encode of top-level \(T.self) was expected to fail.")
} catch {
XCTAssertNotNil(error);
}
}
private func _testDecodeFailure<T: Decodable>(of value: T.Type, data: Data) {
do {
let _ = try JSONDecoder().decode(value, from: data)
XCTFail("Decode of top-level \(value) was expected to fail.")
} catch {
XCTAssertNotNil(error);
}
}
private func _testRoundTrip<T>(of value: T,
expectedJSON json: Data? = nil,
outputFormatting: JSONEncoder.OutputFormatting = [],
dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate,
dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate,
dataEncodingStrategy: JSONEncoder.DataEncodingStrategy = .base64,
dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .base64,
keyEncodingStrategy: JSONEncoder.KeyEncodingStrategy = .useDefaultKeys,
keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys,
nonConformingFloatEncodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .throw,
nonConformingFloatDecodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .throw) where T : Codable, T : Equatable {
var payload: Data! = nil
do {
let encoder = JSONEncoder()
encoder.outputFormatting = outputFormatting
encoder.dateEncodingStrategy = dateEncodingStrategy
encoder.dataEncodingStrategy = dataEncodingStrategy
encoder.nonConformingFloatEncodingStrategy = nonConformingFloatEncodingStrategy
encoder.keyEncodingStrategy = keyEncodingStrategy
payload = try encoder.encode(value)
} catch {
XCTFail("Failed to encode \(T.self) to JSON: \(error)")
}
if let expectedJSON = json {
let expected = String(data: expectedJSON, encoding: .utf8)!
let actual = String(data: payload, encoding: .utf8)!
XCTAssertEqual(expected, actual, "Produced JSON not identical to expected JSON.")
}
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = dateDecodingStrategy
decoder.dataDecodingStrategy = dataDecodingStrategy
decoder.nonConformingFloatDecodingStrategy = nonConformingFloatDecodingStrategy
decoder.keyDecodingStrategy = keyDecodingStrategy
let decoded = try decoder.decode(T.self, from: payload)
XCTAssertEqual(decoded, value, "\(T.self) did not round-trip to an equal value.")
} catch {
XCTFail("Failed to decode \(T.self) from JSON: \(error)")
}
}
private func _testRoundTripTypeCoercionFailure<T,U>(of value: T, as type: U.Type) where T : Codable, U : Codable {
do {
let data = try JSONEncoder().encode(value)
let _ = try JSONDecoder().decode(U.self, from: data)
XCTFail("Coercion from \(T.self) to \(U.self) was expected to fail.")
} catch {}
}
private func _test<T : Equatable & Decodable>(JSONString: String, to object: T) {
#if FOUNDATION_FRAMEWORK
let encs : [String._Encoding] = [.utf8, .utf16BigEndian, .utf16LittleEndian, .utf32BigEndian, .utf32LittleEndian]
#else
// TODO: Reenable other encoding once string.data(using:) is fully implemented.
let encs : [String._Encoding] = [.utf8, .utf16BigEndian, .utf16LittleEndian]
#endif
let decoder = JSONDecoder()
for enc in encs {
let data = JSONString.data(using: enc)!
let parsed : T
do {
parsed = try decoder.decode(T.self, from: data)
} catch {
XCTFail("Failed to decode \(JSONString) with encoding \(enc): Error: \(error)")
continue
}
XCTAssertEqual(object, parsed)
}
}
func test_JSONEscapedSlashes() {
_test(JSONString: "\"\\/test\\/path\"", to: "/test/path")
_test(JSONString: "\"\\\\/test\\\\/path\"", to: "\\/test\\/path")
}
func test_JSONEscapedForwardSlashes() {
_testRoundTrip(of: ["/":1], expectedJSON:
"""
{"\\/":1}
""".data(using: String._Encoding.utf8)!)
}
func test_JSONUnicodeCharacters() {
// UTF8:
// E9 96 86 E5 B4 AC EB B0 BA EB 80 AB E9 A2 92
// 閆崬밺뀫颒
_test(JSONString: "[\"閆崬밺뀫颒\"]", to: ["閆崬밺뀫颒"])
_test(JSONString: "[\"本日\"]", to: ["本日"])
}
func test_JSONUnicodeEscapes() throws {
let testCases = [
// e-acute and greater-than-or-equal-to
"\"\\u00e9\\u2265\"" : "é≥",
// e-acute and greater-than-or-equal-to, surrounded by 42
"\"42\\u00e942\\u226542\"" : "42é42≥42",
// e-acute with upper-case hex
"\"\\u00E9\"" : "é",
// G-clef (UTF16 surrogate pair) 0x1D11E
"\"\\uD834\\uDD1E\"" : "𝄞"
]
for (input, expectedOutput) in testCases {
_test(JSONString: input, to: expectedOutput)
}
}
func test_JSONBadUnicodeEscapes() {
let badCases = ["\\uD834", "\\uD834hello", "hello\\uD834", "\\uD834\\u1221", "\\uD8", "\\uD834x\\uDD1E"]
for str in badCases {
let data = str.data(using: String._Encoding.utf8)!
XCTAssertThrowsError(try JSONDecoder().decode(String.self, from: data))
}
}
func test_nullByte() throws {
let string = "abc\u{0000}def"
let encoder = JSONEncoder()
let decoder = JSONDecoder()
let data = try encoder.encode([string])
let decoded = try decoder.decode([String].self, from: data)
XCTAssertEqual([string], decoded)
let data2 = try encoder.encode([string:string])
let decoded2 = try decoder.decode([String:String].self, from: data2)
XCTAssertEqual([string:string], decoded2)
struct Container: Codable {
let s: String
}
let data3 = try encoder.encode(Container(s: string))
let decoded3 = try decoder.decode(Container.self, from: data3)
XCTAssertEqual(decoded3.s, string)
}
func test_superfluouslyEscapedCharacters() {
let json = "[\"\\h\\e\\l\\l\\o\"]"
XCTAssertThrowsError(try JSONDecoder().decode([String].self, from: json.data(using: String._Encoding.utf8)!))
}
func test_equivalentUTF8Sequences() {
let json =
"""
{
"caf\\u00e9" : true,
"cafe\\u0301" : false
}
""".data(using: String._Encoding.utf8)!
do {
let dict = try JSONDecoder().decode([String:Bool].self, from: json)
XCTAssertEqual(dict.count, 1)
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func test_JSONControlCharacters() {
let array = [
"\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004",
"\\u0005", "\\u0006", "\\u0007", "\\b", "\\t",
"\\n", "\\u000b", "\\f", "\\r", "\\u000e",
"\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013",
"\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018",
"\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d",
"\\u001e", "\\u001f", " "
]
for (ascii, json) in zip(0...0x20, array) {
let quotedJSON = "\"\(json)\""
let expectedResult = String(Character(UnicodeScalar(ascii)!))
_test(JSONString: quotedJSON, to: expectedResult)
}
}
func test_JSONNumberFragments() {
let array = ["0 ", "1.0 ", "0.1 ", "1e3 ", "-2.01e-3 ", "0", "1.0", "1e3", "-2.01e-3", "0e-10"]
let expected = [0, 1.0, 0.1, 1000, -0.00201, 0, 1.0, 1000, -0.00201, 0]
for (json, expected) in zip(array, expected) {
_test(JSONString: json, to: expected)
}
}
func test_invalidJSONNumbersFailAsExpected() {
let array = ["0.", "1e ", "-2.01e- ", "+", "2.01e-1234", "+2.0q", "2s", "NaN", "nan", "Infinity", "inf", "-", "0x42", "1.e2"]
for json in array {
let data = json.data(using: String._Encoding.utf8)!
XCTAssertThrowsError(try JSONDecoder().decode(Float.self, from: data), "Expected error for input \"\(json)\"")
}
}
func _checkExpectedThrownDataCorruptionUnderlyingError(contains substring: String, closure: () throws -> Void) {
do {
try closure()
XCTFail("Expected failure containing string: \"\(substring)\"")
} catch let error as DecodingError {
guard case let .dataCorrupted(context) = error else {
XCTFail("Unexpected DecodingError type: \(error)")
return
}
#if FOUNDATION_FRAMEWORK
let nsError = context.underlyingError! as NSError
XCTAssertTrue(nsError.debugDescription.contains(substring), "Description \"\(nsError.debugDescription)\" doesn't contain substring \"\(substring)\"")
#endif
} catch {
XCTFail("Unexpected error type: \(error)")
}
}
func test_topLevelFragmentsWithGarbage() {
_checkExpectedThrownDataCorruptionUnderlyingError(contains: "Unexpected character") {
let _ = try JSONDecoder().decode(Bool.self, from: "tru_".data(using: String._Encoding.utf8)!)
let _ = try json5Decoder.decode(Bool.self, from: "tru_".data(using: String._Encoding.utf8)!)
}
_checkExpectedThrownDataCorruptionUnderlyingError(contains: "Unexpected character") {
let _ = try JSONDecoder().decode(Bool.self, from: "fals_".data(using: String._Encoding.utf8)!)
let _ = try json5Decoder.decode(Bool.self, from: "fals_".data(using: String._Encoding.utf8)!)
}
_checkExpectedThrownDataCorruptionUnderlyingError(contains: "Unexpected character") {
let _ = try JSONDecoder().decode(Bool?.self, from: "nul_".data(using: String._Encoding.utf8)!)
let _ = try json5Decoder.decode(Bool?.self, from: "nul_".data(using: String._Encoding.utf8)!)
}
}
func test_topLevelNumberFragmentsWithJunkDigitCharacters() {
let fullData = "3.141596".data(using: String._Encoding.utf8)!
let partialData = fullData[0..<4]
XCTAssertEqual(3.14, try JSONDecoder().decode(Double.self, from: partialData))
}
func test_depthTraversal() {
struct SuperNestedArray : Decodable {
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
while container.count! > 0 {
container = try container.nestedUnkeyedContainer()
}
}
}
let MAX_DEPTH = 512
let jsonGood = String(repeating: "[", count: MAX_DEPTH / 2) + String(repeating: "]", count: MAX_DEPTH / 2)
let jsonBad = String(repeating: "[", count: MAX_DEPTH + 1) + String(repeating: "]", count: MAX_DEPTH + 1)
XCTAssertNoThrow(try JSONDecoder().decode(SuperNestedArray.self, from: jsonGood.data(using: String._Encoding.utf8)!))
XCTAssertThrowsError(try JSONDecoder().decode(SuperNestedArray.self, from: jsonBad.data(using: String._Encoding.utf8)!))
}
func test_JSONPermitsTrailingCommas() {
// Trailing commas aren't valid JSON and should never be emitted, but are syntactically unambiguous and are allowed by
// most parsers for ease of use.
let json = "{\"key\" : [ true, ],}"
let data = json.data(using: String._Encoding.utf8)!
let result = try! JSONDecoder().decode([String:[Bool]].self, from: data)
let expected = ["key" : [true]]
XCTAssertEqual(result, expected)
}
func test_whitespaceOnlyData() {
let data = " ".data(using: String._Encoding.utf8)!
XCTAssertThrowsError(try JSONDecoder().decode(Int.self, from: data))
}
func test_smallFloatNumber() {
_testRoundTrip(of: [["magic_number" : 7.45673334164903e-115]])
}
func test_largeIntegerNumber() {
let num : UInt64 = 6032314514195021674
let json = "{\"a\":\(num)}"
let data = json.data(using: String._Encoding.utf8)!
let result = try! JSONDecoder().decode([String:UInt64].self, from: data)
let number = result["a"]!
XCTAssertEqual(number, num)
}
func test_largeIntegerNumberIsNotRoundedToNearestDoubleWhenDecodingAsAnInteger() {
XCTAssertEqual(Double(sign: .plus, exponent: 63, significand: 1).ulp, 2048)
XCTAssertEqual(Double(sign: .plus, exponent: 64, significand: 1).ulp, 4096)
let int64s: [(String, Int64?)] = [
("-9223372036854776833", nil), // -2^63 - 1025 (Double: -2^63 - 2048)
("-9223372036854776832", nil), // -2^63 - 1024 (Double: -2^63)
("-9223372036854775809", nil), // -2^63 - 1 (Double: -2^63)
("-9223372036854775808", Int64.min), // -2^63 (Double: -2^63)
( "9223372036854775807", Int64.max), // 2^63 - 1 (Double: 2^63)
( "9223372036854775808", nil), // 2^63 (Double: 2^63)
( "9223372036854776832", nil), // 2^63 + 1024 (Double: 2^63)
( "9223372036854776833", nil), // 2^63 + 1025 (Double: 2^63 + 2048)
]
let uint64s: [(String, UInt64?)] = [
( "9223372036854775807", 1 << 63 - 0001), // 2^63 - 1 (Double: 2^63)
( "9223372036854775808", 1 << 63 + 0000), // 2^63 (Double: 2^63)
( "9223372036854776832", 1 << 63 + 1024), // 2^63 + 1024 (Double: 2^63)
( "9223372036854776833", 1 << 63 + 1025), // 2^63 + 1025 (Double: 2^63 + 2048)
("18446744073709551615", UInt64.max), // 2^64 - 1 (Double: 2^64)
("18446744073709551616", nil), // 2^64 (Double: 2^64)
("18446744073709553664", nil), // 2^64 + 2048 (Double: 2^64)
("18446744073709553665", nil), // 2^64 + 2049 (Double: 2^64 + 4096)
]
for json5 in [true, false] {
let decoder = JSONDecoder()
decoder.allowsJSON5 = json5
for (json, value) in int64s {
let result = try? decoder.decode(Int64.self, from: json.data(using: String._Encoding.utf8)!)
XCTAssertEqual(result, value, "Unexpected \(decoder) result for input \"\(json)\"")
}
for (json, value) in uint64s {
let result = try? decoder.decode(UInt64.self, from: json.data(using: String._Encoding.utf8)!)
XCTAssertEqual(result, value, "Unexpected \(decoder) result for input \"\(json)\"")
}
}
}
func test_roundTrippingExtremeValues() {
struct Numbers : Codable, Equatable {
let floats : [Float]
let doubles : [Double]
}
let testValue = Numbers(floats: [.greatestFiniteMagnitude, .leastNormalMagnitude], doubles: [.greatestFiniteMagnitude, .leastNormalMagnitude])
_testRoundTrip(of: testValue)
}
func test_roundTrippingInt128() {
if #available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *) {
let values = [
Int128.min,
Int128.min + 1,
-0x1_0000_0000_0000_0000,
0x0_8000_0000_0000_0000,
-1,
0,
0x7fff_ffff_ffff_ffff,
0x8000_0000_0000_0000,
0xffff_ffff_ffff_ffff,
0x1_0000_0000_0000_0000,
.max
]
for i128 in values {
_testRoundTrip(of: i128)
}
}
}
func test_Int128SlowPath() {
if #available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *) {
let decoder = JSONDecoder()
let work: [Int128] = [18446744073709551615, -18446744073709551615]
for value in work {
// force the slow-path by appending ".0"
let json = "\(value).0".data(using: String._Encoding.utf8)!
XCTAssertEqual(value, try? decoder.decode(Int128.self, from: json))
}
// These should work, but making them do so probably requires
// rewriting the slow path to use a dedicated parser. For now,
// we ensure that they throw instead of returning some bogus
// result.
let shouldWorkButDontYet: [Int128] = [
.min, -18446744073709551616, 18446744073709551616, .max
]
for value in shouldWorkButDontYet {
// force the slow-path by appending ".0"
let json = "\(value).0".data(using: String._Encoding.utf8)!
XCTAssertThrowsError(try decoder.decode(Int128.self, from: json))
}
}
}
func test_roundTrippingUInt128() {
if #available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *) {
let values = [
UInt128.zero,
1,
0x0000_0000_0000_0000_7fff_ffff_ffff_ffff,
0x0000_0000_0000_0000_8000_0000_0000_0000,
0x0000_0000_0000_0000_ffff_ffff_ffff_ffff,
0x0000_0000_0000_0001_0000_0000_0000_0000,
0x7fff_ffff_ffff_ffff_ffff_ffff_ffff_ffff,
0x8000_0000_0000_0000_0000_0000_0000_0000,
.max
]
for u128 in values {
_testRoundTrip(of: u128)
}
}
}
func test_UInt128SlowPath() {
if #available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *) {
let decoder = JSONDecoder()
let work: [UInt128] = [18446744073709551615]
for value in work {
// force the slow-path by appending ".0"
let json = "\(value).0".data(using: String._Encoding.utf8)!
XCTAssertEqual(value, try? decoder.decode(UInt128.self, from: json))
}
// These should work, but making them do so probably requires
// rewriting the slow path to use a dedicated parser. For now,
// we ensure that they throw instead of returning some bogus
// result.
let shouldWorkButDontYet: [UInt128] = [
18446744073709551616, .max
]
for value in shouldWorkButDontYet {
// force the slow-path by appending ".0"
let json = "\(value).0".data(using: String._Encoding.utf8)!
XCTAssertThrowsError(try decoder.decode(UInt128.self, from: json))
}
}
}
func test_roundTrippingDoubleValues() {
struct Numbers : Codable, Equatable {
let doubles : [String:Double]
let decimals : [String:Decimal]
}
let testValue = Numbers(
doubles: [
"-55.66" : -55.66,
"-9.81" : -9.81,
"-0.284" : -0.284,
"-3.4028234663852886e+38" : Double(-Float.greatestFiniteMagnitude),
"-1.1754943508222875e-38" : Double(-Float.leastNormalMagnitude),
"-1.7976931348623157e+308" : -.greatestFiniteMagnitude,
"-2.2250738585072014e-308" : -.leastNormalMagnitude,
"0.000001" : 0.000001,
],
decimals: [
"1.234567891011121314" : Decimal(string: "1.234567891011121314")!,
"-1.234567891011121314" : Decimal(string: "-1.234567891011121314")!,
"0.1234567891011121314" : Decimal(string: "0.1234567891011121314")!,
"-0.1234567891011121314" : Decimal(string: "-0.1234567891011121314")!,
"123.4567891011121314e-100" : Decimal(string: "123.4567891011121314e-100")!,
"-123.4567891011121314e-100" : Decimal(string: "-123.4567891011121314e-100")!,
"11234567891011121314e-100" : Decimal(string: "1234567891011121314e-100")!,
"-1234567891011121314e-100" : Decimal(string: "-1234567891011121314e-100")!,
"0.1234567891011121314e-100" : Decimal(string: "0.1234567891011121314e-100")!,
"-0.1234567891011121314e-100" : Decimal(string: "-0.1234567891011121314e-100")!,
"3.14159265358979323846264338327950288419" : Decimal(string: "3.14159265358979323846264338327950288419")!,
"2.71828182845904523536028747135266249775" : Decimal(string: "2.71828182845904523536028747135266249775")!,
"440474310512876335.18692524723746578303827301433673643795" : Decimal(string: "440474310512876335.18692524723746578303827301433673643795")!
]
)
_testRoundTrip(of: testValue)
}
func test_decodeLargeDoubleAsInteger() {
let data = try! JSONEncoder().encode(Double.greatestFiniteMagnitude)
XCTAssertThrowsError(try JSONDecoder().decode(UInt64.self, from: data))
}
func test_localeDecimalPolicyIndependence() {
var currentLocale: UnsafeMutablePointer<CChar>? = nil
if let localePtr = setlocale(LC_ALL, nil) {
currentLocale = strdup(localePtr)
}
defer {
if let currentLocale {
setlocale(LC_ALL, currentLocale)
free(currentLocale)
}
}
let orig = ["decimalValue" : 1.1]
do {
setlocale(LC_ALL, "fr_FR")
let data = try JSONEncoder().encode(orig)
#if os(Windows)
setlocale(LC_ALL, "en_US")
#else
setlocale(LC_ALL, "en_US_POSIX")
#endif
let decoded = try JSONDecoder().decode(type(of: orig).self, from: data)
XCTAssertEqual(orig, decoded)
} catch {
XCTFail("Error: \(error)")
}
}
func test_whitespace() {
let tests : [(json: String, expected: [String:Bool])] = [
("{\"v\"\n : true}", ["v":true]),
("{\"v\"\r\n : true}", ["v":true]),
("{\"v\"\r : true}", ["v":true])
]
for test in tests {
let data = test.json.data(using: String._Encoding.utf8)!
let decoded = try! JSONDecoder().decode([String:Bool].self, from: data)
XCTAssertEqual(test.expected, decoded)
}
}
func test_assumesTopLevelDictionary() {
let decoder = JSONDecoder()
decoder.assumesTopLevelDictionary = true
let json = "\"x\" : 42"
do {
let result = try decoder.decode([String:Int].self, from: json.data(using: String._Encoding.utf8)!)
XCTAssertEqual(result, ["x" : 42])
} catch {
XCTFail("Error thrown while decoding assumed top-level dictionary: \(error)")
}
let jsonWithBraces = "{\"x\" : 42}"
do {
let result = try decoder.decode([String:Int].self, from: jsonWithBraces.data(using: String._Encoding.utf8)!)
XCTAssertEqual(result, ["x" : 42])
} catch {
XCTFail("Error thrown while decoding assumed top-level dictionary: \(error)")
}
do {
let result = try decoder.decode([String:Int].self, from: Data())
XCTAssertEqual(result, [:])
} catch {
XCTFail("Error thrown while decoding empty assumed top-level dictionary: \(error)")
}
let jsonWithEndBraceOnly = "\"x\" : 42}"
XCTAssertThrowsError(try decoder.decode([String:Int].self, from: jsonWithEndBraceOnly.data(using: String._Encoding.utf8)!))
let jsonWithStartBraceOnly = "{\"x\" : 42"
XCTAssertThrowsError(try decoder.decode([String:Int].self, from: jsonWithStartBraceOnly.data(using: String._Encoding.utf8)!))
}
func test_BOMPrefixes() {
let json = "\"👍🏻\""
let decoder = JSONDecoder()
// UTF-8 BOM
let utf8_BOM = Data([0xEF, 0xBB, 0xBF])
XCTAssertEqual("👍🏻", try decoder.decode(String.self, from: utf8_BOM + json.data(using: String._Encoding.utf8)!))
// UTF-16 BE
let utf16_BE_BOM = Data([0xFE, 0xFF])
XCTAssertEqual("👍🏻", try decoder.decode(String.self, from: utf16_BE_BOM + json.data(using: String._Encoding.utf16BigEndian)!))
// UTF-16 LE
let utf16_LE_BOM = Data([0xFF, 0xFE])
XCTAssertEqual("👍🏻", try decoder.decode(String.self, from: utf16_LE_BOM + json.data(using: String._Encoding.utf16LittleEndian)!))
// UTF-32 BE
let utf32_BE_BOM = Data([0x0, 0x0, 0xFE, 0xFF])
XCTAssertEqual("👍🏻", try decoder.decode(String.self, from: utf32_BE_BOM + json.data(using: String._Encoding.utf32BigEndian)!))
// UTF-32 LE
let utf32_LE_BOM = Data([0xFE, 0xFF, 0, 0])
XCTAssertEqual("👍🏻", try decoder.decode(String.self, from: utf32_LE_BOM + json.data(using: String._Encoding.utf32LittleEndian)!))
// Try some mismatched BOMs
XCTAssertThrowsError(try decoder.decode(String.self, from: utf32_LE_BOM + json.data(using: String._Encoding.utf32BigEndian)!))
XCTAssertThrowsError(try decoder.decode(String.self, from: utf16_BE_BOM + json.data(using: String._Encoding.utf32LittleEndian)!))
XCTAssertThrowsError(try decoder.decode(String.self, from: utf8_BOM + json.data(using: String._Encoding.utf16BigEndian)!))
}
func test_valueNotFoundError() {
struct ValueNotFound : Decodable {
let a: Bool
let nope: String?
enum CodingKeys: String, CodingKey {
case a, nope
}
init(from decoder: Decoder) throws {
let keyed = try decoder.container(keyedBy: CodingKeys.self)
self.a = try keyed.decode(Bool.self, forKey: .a)
do {
let sup = try keyed.superDecoder(forKey: .nope)
self.nope = try sup.singleValueContainer().decode(String.self)
} catch DecodingError.valueNotFound {
// This is fine.
self.nope = nil
}
}
}
let json = "{\"a\":true}".data(using: String._Encoding.utf8)!
// The expected valueNotFound error is swalled by the init(from:) implementation.
XCTAssertNoThrow(try JSONDecoder().decode(ValueNotFound.self, from: json))
}
func test_infiniteDate() {
let date = Date(timeIntervalSince1970: .infinity)
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .deferredToDate
XCTAssertThrowsError(try encoder.encode([date]))
encoder.dateEncodingStrategy = .secondsSince1970
XCTAssertThrowsError(try encoder.encode([date]))
encoder.dateEncodingStrategy = .millisecondsSince1970
XCTAssertThrowsError(try encoder.encode([date]))
}
func test_typeEncodesNothing() {
struct EncodesNothing : Encodable {
func encode(to encoder: Encoder) throws {
// Intentionally nothing.
}
}
let enc = JSONEncoder()
XCTAssertThrowsError(try enc.encode(EncodesNothing()))
// Unknown if the following behavior is strictly correct, but it's what the prior implementation does, so this test exists to make sure we maintain compatibility.
let arrayData = try! enc.encode([EncodesNothing()])
XCTAssertEqual("[{}]", String(data: arrayData, encoding: .utf8))
let objectData = try! enc.encode(["test" : EncodesNothing()])
XCTAssertEqual("{\"test\":{}}", String(data: objectData, encoding: .utf8))
}
func test_superEncoders() {
struct SuperEncoding : Encodable {
enum CodingKeys: String, CodingKey {
case firstSuper
case secondSuper
case unkeyed
}
func encode(to encoder: Encoder) throws {
var keyed = encoder.container(keyedBy: CodingKeys.self)
let keyedSuper1 = keyed.superEncoder(forKey: .firstSuper)
let keyedSuper2 = keyed.superEncoder(forKey: .secondSuper)
var keyedSVC1 = keyedSuper1.singleValueContainer()
var keyedSVC2 = keyedSuper2.singleValueContainer()
try keyedSVC1.encode("First")
try keyedSVC2.encode("Second")
var unkeyed = keyed.nestedUnkeyedContainer(forKey: .unkeyed)
try unkeyed.encode(0)
let unkeyedSuper1 = unkeyed.superEncoder()
let unkeyedSuper2 = unkeyed.superEncoder()
try unkeyed.encode(42)
var unkeyedSVC1 = unkeyedSuper1.singleValueContainer()
var unkeyedSVC2 = unkeyedSuper2.singleValueContainer()
try unkeyedSVC1.encode("First")
try unkeyedSVC2.encode("Second")
// NOTE!!! At present, the order in which the values in the unkeyed container's superEncoders above get inserted into the resulting array depends on the order in which the superEncoders are deinit'd!! This can result in some very unexpected results, and this pattern is not recommended. This test exists just to verify compatibility.
}
}
let data = try! JSONEncoder().encode(SuperEncoding())
let string = String(data: data, encoding: .utf8)!
XCTAssertTrue(string.contains("\"firstSuper\":\"First\""))
XCTAssertTrue(string.contains("\"secondSuper\":\"Second\""))
XCTAssertTrue(string.contains("[0,\"First\",\"Second\",42]"))
}
func testRedundantKeys() {
// Last encoded key wins.
struct RedundantEncoding : Encodable {
enum ReplacedType {
case value
case keyedContainer
case unkeyedContainer
}
let replacedType: ReplacedType
let useSuperEncoder: Bool
enum CodingKeys: String, CodingKey {
case key
}
func encode(to encoder: Encoder) throws {
var keyed = encoder.container(keyedBy: CodingKeys.self)
switch replacedType {
case .value:
try keyed.encode(0, forKey: .key)
case .keyedContainer:
let _ = keyed.nestedContainer(keyedBy: CodingKeys.self, forKey: .key)
case .unkeyedContainer:
let _ = keyed.nestedUnkeyedContainer(forKey: .key)
}
if useSuperEncoder {
var svc = keyed.superEncoder(forKey: .key).singleValueContainer()
try svc.encode(42)
} else {
try keyed.encode(42, forKey: .key)
}
}
}
var data = try! JSONEncoder().encode(RedundantEncoding(replacedType: .value, useSuperEncoder: false))
XCTAssertEqual(String(data: data, encoding: .utf8), ("{\"key\":42}"))
data = try! JSONEncoder().encode(RedundantEncoding(replacedType: .value, useSuperEncoder: true))
XCTAssertEqual(String(data: data, encoding: .utf8), ("{\"key\":42}"))
data = try! JSONEncoder().encode(RedundantEncoding(replacedType: .keyedContainer, useSuperEncoder: false))
XCTAssertEqual(String(data: data, encoding: .utf8), ("{\"key\":42}"))
data = try! JSONEncoder().encode(RedundantEncoding(replacedType: .keyedContainer, useSuperEncoder: true))
XCTAssertEqual(String(data: data, encoding: .utf8), ("{\"key\":42}"))
data = try! JSONEncoder().encode(RedundantEncoding(replacedType: .unkeyedContainer, useSuperEncoder: false))
XCTAssertEqual(String(data: data, encoding: .utf8), ("{\"key\":42}"))
data = try! JSONEncoder().encode(RedundantEncoding(replacedType: .unkeyedContainer, useSuperEncoder: true))
XCTAssertEqual(String(data: data, encoding: .utf8), ("{\"key\":42}"))
}
// None of these tests can be run in our automatic test suites right now, because they are expected to hit a preconditionFailure. They can only be verified manually.
func disabled_testPreconditionFailuresForContainerReplacement() {
struct RedundantEncoding : Encodable {
enum Subcase {
case replaceValueWithKeyedContainer
case replaceValueWithUnkeyedContainer
case replaceKeyedContainerWithUnkeyed
case replaceUnkeyedContainerWithKeyed
}
let subcase : Subcase
enum CodingKeys: String, CodingKey {
case key
}
func encode(to encoder: Encoder) throws {
switch subcase {
case .replaceValueWithKeyedContainer:
var keyed = encoder.container(keyedBy: CodingKeys.self)
try keyed.encode(42, forKey: .key)
let _ = keyed.nestedContainer(keyedBy: CodingKeys.self, forKey: .key)
case .replaceValueWithUnkeyedContainer:
var keyed = encoder.container(keyedBy: CodingKeys.self)
try keyed.encode(42, forKey: .key)
let _ = keyed.nestedUnkeyedContainer(forKey: .key)
case .replaceKeyedContainerWithUnkeyed:
var keyed = encoder.container(keyedBy: CodingKeys.self)
let _ = keyed.nestedContainer(keyedBy: CodingKeys.self, forKey: .key)
let _ = keyed.nestedUnkeyedContainer(forKey: .key)
case .replaceUnkeyedContainerWithKeyed:
var keyed = encoder.container(keyedBy: CodingKeys.self)
let _ = keyed.nestedUnkeyedContainer(forKey: .key)
let _ = keyed.nestedContainer(keyedBy: CodingKeys.self, forKey: .key)
}
}
}
let _ = try! JSONEncoder().encode(RedundantEncoding(subcase: .replaceValueWithKeyedContainer))
// let _ = try! JSONEncoder().encode(RedundantEncoding(subcase: .replaceValueWithUnkeyedContainer))
// let _ = try! JSONEncoder().encode(RedundantEncoding(subcase: .replaceKeyedContainerWithUnkeyed))
// let _ = try! JSONEncoder().encode(RedundantEncoding(subcase: .replaceUnkeyedContainerWithKeyed))
}
var json5Decoder: JSONDecoder {
let decoder = JSONDecoder()
decoder.allowsJSON5 = true
return decoder
}
func test_json5Numbers() {
let decoder = json5Decoder
let successfulIntegers: [(String,Int)] = [
("1", 1),
("11", 11),
("99887766", 99887766),
("-1", -1),
("-10", -10),
("0", 0),
("+0", +0),
("-0", -0),
("+1", +1),
("+10", +10),
("0x1F", 0x1F),
("0x0000000E", 0xE),
("-0X1f", -0x1f),
("+0X1f", +0x1f),
("1.", 1),
("1.e2", 100),
("1e2", 100),
("1E2", 100),
("1e+2", 100),
("1E+2", 100),
("1e+02", 100),
("1E+02", 100),
]
for (json, expected) in successfulIntegers {
do {
let val = try decoder.decode(Int.self, from: json.data(using: String._Encoding.utf8)!)
XCTAssertEqual(val, expected, "Wrong value parsed from input \"\(json)\"")
} catch {
XCTFail("Error when parsing input \"\(json)\": \(error)")
}
}
let successfulDoubles: [(String,Double)] = [
("1", 1),
("11", 11),
("99887766", 99887766),
("-1", -1),
("-10", -10),
("0", 0),
("+0", +0),
("-0", -0),
("+1", +1),
("+10", +10),
("Infinity", Double.infinity),
("-Infinity", -Double.infinity),
("+Infinity", Double.infinity),
("-NaN", -Double.nan),
("+NaN", Double.nan),
("NaN", Double.nan),
(".1", 0.1),
("1.", 1.0),
("-.1", -0.1),
("+.1", +0.1),
("1e-2", 1e-2),
("1E-2", 1E-2),
("1e-02", 1e-02),
("1E-02", 1E-02),
("1e2", 1e2),
("1E2", 1E2),
("1e+2", 1e+2),
("1E+2", 1E+2),
("1e+02", 1e+02),
("1E+02", 1E+02),
("0x1F", Double(0x1F)),
("-0X1f", Double(-0x1f)),
("+0X1f", Double(+0x1f)),
]
for (json, expected) in successfulDoubles {
do {
let val = try decoder.decode(Double.self, from: json.data(using: String._Encoding.utf8)!)
if expected.isNaN {
XCTAssertTrue(val.isNaN, "Wrong value \(val) parsed from input \"\(json)\"")
} else {
XCTAssertEqual(val, expected, "Wrong value parsed from input \"\(json)\"")
}
} catch {
XCTFail("Error when parsing input \"\(json)\": \(error)")
}
}
let unsuccessfulIntegers = [
"-", // single -
"+", // single +
"-a", // - followed by non-digit
"+a", // + followed by non-digit
"-0x",
"+0x",
"-0x ",
"+0x ",
"-0xAFFFFFAFFFFFAFFFFFAFFFFFAFFFFFAFFFFFAFFFFFAFFFFF",
"0xABC.DEF",
"0xABCpD",
"1e",
"1E",
"1e ",
"1E ",
"+1e ",
"+1e",
"-1e ",
"-1E ",
]
for json in unsuccessfulIntegers {
do {
let _ = try decoder.decode(Int.self, from: json.data(using: String._Encoding.utf8)!)
XCTFail("Expected failure for input \"\(json)\"")
} catch { }
}
let unsuccessfulDoubles = [
"-Inf",
"-Inf ",
"+Inf",
"+Inf ",
"+Na",
"+Na ",
"-Na",
"-Na ",
"-infinity",
"-infinity ",
"+infinity",
"+infinity ",
"+NAN",
"+NA ",
"-NA",
"-NA ",
"-NAN",
"-NAN ",
"0x2.",
"0x2.2",
".e1",
"0xFFFFFFFFFFFFFFFFFFFFFF",
];
for json in unsuccessfulDoubles {
do {
let _ = try decoder.decode(Double.self, from: json.data(using: String._Encoding.utf8)!)
XCTFail("Expected failure for input \"\(json)\"")
} catch { }
}
}
func test_json5Null() {
let validJSON = "null"
let invalidJSON = [
"Null",
"nul",
"nu",
"n",
"n ",
"nu "
]
XCTAssertNoThrow(try json5Decoder.decode(NullReader.self, from: validJSON.data(using: String._Encoding.utf8)!))
for json in invalidJSON {
XCTAssertThrowsError(try json5Decoder.decode(NullReader.self, from: json.data(using: String._Encoding.utf8)!), "Expected failure while decoding input \"\(json)\"")
}
}
func test_json5EsotericErrors() {
// All of the following should fail
let arrayStrings = [
"[",
"[ ",
"[\n\n",
"['hi',",
"['hi', ",
"['hi',\n"
]
let objectStrings = [
"{",
"{ ",
"{k ",
"{k :",
"{k : ",
"{k : true",
"{k : true ",
"{k : true\n\n",
"{k : true ",
"{k : true ",
]
let objectCharacterArrays: [[UInt8]] = [
[.init(ascii: "{"), 0x80], // Invalid UTF-8: Unexpected continuation byte
[.init(ascii: "{"), 0xc0], // Invalid UTF-8: Initial byte of 2-byte sequence without continuation
[.init(ascii: "{"), 0xe0, 0x80], // Invalid UTF-8: Initial byte of 3-byte sequence with only one continuation
[.init(ascii: "{"), 0xf0, 0x80, 0x80], // Invalid UTF-8: Initial byte of 3-byte sequence with only one continuation
]
for json in arrayStrings {
XCTAssertThrowsError(try json5Decoder.decode([String].self, from: json.data(using: String._Encoding.utf8)!), "Expected error for input \"\(json)\"")
}
for json in objectStrings {
XCTAssertThrowsError(try json5Decoder.decode([String:Bool].self, from: json.data(using: String._Encoding.utf8)!), "Expected error for input \(json)")
}
for json in objectCharacterArrays {
XCTAssertThrowsError(try json5Decoder.decode([String:Bool].self, from: Data(json)), "Expected error for input \(json)")
}
}
func test_json5Strings() {
let stringsToTrues = [
"{v\n : true}",
"{v \n : true}",
"{ v \n : true,\nv\n:true,}",
"{v\r : true}",
"{v \r : true}",
"{ v \r : true,\rv\r:true,}",
"{v\r\n : true}",
"{v \r\n : true}",
"{ v \r\n : true,\r\nv\r\n:true,}",
"{v// comment \n : true}",
"{v // comment \n : true}",
"{v/* comment*/ \n : true}",
"{v/* comment */\n: true}",
"{v/* comment */:/*comment*/\ntrue}",
"{v// comment \r : true}",
"{v // comment \r : true}",
"{v/* comment*/ \r : true}",
"{v/* comment */\r: true}",
"{v/* comment */:/*comment*/\rtrue}",
"{v// comment \r\n : true}",
"{v // comment \r\n : true}",
"{v/* comment*/ \r\n : true}",
"{v/* comment */\r\n: true}",
"{v/* comment */:/*comment*/\r\ntrue}",
"// start with a comment\r\n{v:true}",
]
let stringsToStrings = [
"{v : \"hi\\x20there\"}" : "hi there",
"{v : \"hi\\xthere\"}" : nil,
"{v : \"hi\\x2there\"}" : nil,
"{v : \"hi\\0there\"}" : nil,
"{v : \"hi\\x00there\"}" : nil,
"{v : \"hi\\u0000there\"}" : nil, // disallowed in JSON5 mode only
"{v:\"hello\\uA\"}" : nil,
"{v:\"hello\\uA \"}" : nil
]
for json in stringsToTrues {
XCTAssertNoThrow(try json5Decoder.decode([String:Bool].self, from: json.data(using: String._Encoding.utf8)!), "Failed to parse \"\(json)\"")
}
for (json, expected) in stringsToStrings {
do {
let decoded = try json5Decoder.decode([String:String].self, from: json.data(using: String._Encoding.utf8)!)
XCTAssertEqual(expected, decoded["v"])
} catch {
if let expected {
XCTFail("Expected \(expected) for input \"\(json)\", but failed with \(error)")
}
}
}
}
func test_json5AssumedDictionary() {
let decoder = json5Decoder
decoder.assumesTopLevelDictionary = true
let stringsToString = [
"hello: \"world\"" : [ "hello" : "world" ],
"{hello: \"world\"}" : [ "hello" : "world" ], // Still has markers
"hello: \"world\", goodbye: \"42\"" : [ "hello" : "world", "goodbye" : "42" ], // more than one value
"hello: \"world\"," : [ "hello" : "world" ], // Trailing comma
"hello: \"world\" " : [ "hello" : "world" ], // Trailing whitespace
"hello: \"world\", " : [ "hello" : "world" ], // Trailing whitespace and comma
"hello: \"world\" , " : [ "hello" : "world" ], // Trailing whitespace and comma
" hello : \"world\" " : [ "hello" : "world" ], // Before and after whitespace
"{hello: \"world\"" : nil, // Partial dictionary 1
"hello: \"world\"}" : nil, // Partial dictionary 2
"hello: \"world\" x " : nil, // Junk at end
"hello: \"world\" x" : nil, // Junk at end
"hello: \"world\"x" : nil, // Junk at end
"" : [:], // empty but valid
" " : [:], // empty but valid
"{ }" : [:], // empty but valid
"{}" : [:], // empty but valid
"," : nil, // Invalid
" , " : nil, // Invalid
", " : nil, // Invalid
" ," : nil, // Invalid
]
for (json, expected) in stringsToString {
do {
let decoded = try decoder.decode([String:String].self, from: json.data(using: String._Encoding.utf8)!)
XCTAssertEqual(expected, decoded)
} catch {
if let expected {
XCTFail("Expected \(expected) for input \"\(json)\", but failed with \(error)")
}
}
}
struct HelloGoodbye : Decodable, Equatable {
let hello: String
let goodbye: [String:String]
}
let helloGoodbyeExpectedValue = HelloGoodbye(
hello: "world",
goodbye: ["hi" : "there"])
let stringsToNestedDictionary = [
"hello: \"world\", goodbye: {\"hi\":\"there\"}", // more than one value, nested dictionary
"hello: \"world\", goodbye: {\"hi\":\"there\"},", // more than one value, nested dictionary, trailing comma 1
"hello: \"world\", goodbye: {\"hi\":\"there\",},", // more than one value, nested dictionary, trailing comma 2
]
for json in stringsToNestedDictionary {
do {
let decoded = try decoder.decode(HelloGoodbye.self, from: json.data(using: String._Encoding.utf8)!)
XCTAssertEqual(helloGoodbyeExpectedValue, decoded)
} catch {
XCTFail("Expected \(helloGoodbyeExpectedValue) for input \"\(json)\", but failed with \(error)")
}
}
let arrayJSON = "[1,2,3]".data(using: String._Encoding.utf8)! // Assumed dictionary can't be an array
XCTAssertThrowsError(try decoder.decode([Int].self, from: arrayJSON))
let strFragmentJSON = "fragment".data(using: String._Encoding.utf8)! // Assumed dictionary can't be a fragment
XCTAssertThrowsError(try decoder.decode(String.self, from: strFragmentJSON))
let numFragmentJSON = "42".data(using: String._Encoding.utf8)! // Assumed dictionary can't be a fragment
XCTAssertThrowsError(try decoder.decode(Int.self, from: numFragmentJSON))
}
enum JSON5SpecTestType {
case json5
case json5_foundationPermissiveJSON
case json
case js
case malformed
var fileExtension : String {
switch self {
case .json5: return "json5"
case .json5_foundationPermissiveJSON: return "json5"
case .json: return "json"
case .js: return "js"
case .malformed: return "txt"
}
}
}
}
// MARK: - SnakeCase Tests
extension JSONEncoderTests {
func testDecodingKeyStrategyCamel() {
let fromSnakeCaseTests = [
("", ""), // don't die on empty string
("a", "a"), // single character
("ALLCAPS", "ALLCAPS"), // If no underscores, we leave the word as-is
("ALL_CAPS", "allCaps"), // Conversion from screaming snake case
("single", "single"), // do not capitalize anything with no underscore
("snake_case", "snakeCase"), // capitalize a character
("one_two_three", "oneTwoThree"), // more than one word
("one_2_three", "one2Three"), // numerics
("one2_three", "one2Three"), // numerics, part 2
("snake_Ćase", "snakeĆase"), // do not further modify a capitalized diacritic
("snake_ćase", "snakeĆase"), // capitalize a diacritic
("alreadyCamelCase", "alreadyCamelCase"), // do not modify already camel case
("__this_and_that", "__thisAndThat"),
("_this_and_that", "_thisAndThat"),
("this__and__that", "thisAndThat"),
("this_and_that__", "thisAndThat__"),
("this_aNd_that", "thisAndThat"),
("_one_two_three", "_oneTwoThree"),
("one_two_three_", "oneTwoThree_"),
("__one_two_three", "__oneTwoThree"),
("one_two_three__", "oneTwoThree__"),
("_one_two_three_", "_oneTwoThree_"),
("__one_two_three", "__oneTwoThree"),
("__one_two_three__", "__oneTwoThree__"),
("_test", "_test"),
("_test_", "_test_"),
("__test", "__test"),
("test__", "test__"),
("_", "_"),
("__", "__"),
("___", "___"),
("m͉̟̹y̦̳G͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖U͇̝̠R͙̻̥͓̣L̥̖͎͓̪̫ͅR̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ", "m͉̟̹y̦̳G͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖U͇̝̠R͙̻̥͓̣L̥̖͎͓̪̫ͅR̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ"), // because Itai wanted to test this
("🐧_🐟", "🐧🐟") // fishy emoji example?
]
for test in fromSnakeCaseTests {
// This JSON contains the camel case key that the test object should decode with, then it uses the snake case key (test.0) as the actual key for the boolean value.
let input = "{\"camelCaseKey\":\"\(test.1)\",\"\(test.0)\":true}".data(using: String._Encoding.utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try! decoder.decode(DecodeMe.self, from: input)
XCTAssertTrue(result.found)
}
}
func testEncodingDictionaryStringKeyConversionUntouched() {
let expected = "{\"leaveMeAlone\":\"test\"}"
let toEncode: [String: String] = ["leaveMeAlone": "test"]
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let resultData = try! encoder.encode(toEncode)
let resultString = String(bytes: resultData, encoding: String._Encoding.utf8)
XCTAssertEqual(expected, resultString)
}
func testKeyStrategySnakeGeneratedAndCustom() {
// Test that this works with a struct that has automatically generated keys
struct DecodeMe4 : Codable {
var thisIsCamelCase : String
var thisIsCamelCaseToo : String
private enum CodingKeys : String, CodingKey {
case thisIsCamelCase = "fooBar"
case thisIsCamelCaseToo
}
}
// Decoding
let input = "{\"foo_bar\":\"test\",\"this_is_camel_case_too\":\"test2\"}".data(using: String._Encoding.utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let decodingResult = try! decoder.decode(DecodeMe4.self, from: input)
XCTAssertEqual("test", decodingResult.thisIsCamelCase)
XCTAssertEqual("test2", decodingResult.thisIsCamelCaseToo)
// Encoding
let encoded = DecodeMe4(thisIsCamelCase: "test", thisIsCamelCaseToo: "test2")
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let encodingResultData = try! encoder.encode(encoded)
let encodingResultString = String(bytes: encodingResultData, encoding: String._Encoding.utf8)
XCTAssertTrue(encodingResultString!.contains("foo_bar"))
XCTAssertTrue(encodingResultString!.contains("this_is_camel_case_too"))
}
func testDecodingDictionaryFailureKeyPathNested() {
let input = "{\"top_level\": {\"sub_level\": {\"nested_value\": {\"int_value\": \"not_an_int\"}}}}".data(using: String._Encoding.utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
_ = try decoder.decode([String: [String : DecodeFailureNested]].self, from: input)
} catch DecodingError.typeMismatch(_, let context) {
XCTAssertEqual(4, context.codingPath.count)
XCTAssertEqual("top_level", context.codingPath[0].stringValue)
XCTAssertEqual("sub_level", context.codingPath[1].stringValue)
XCTAssertEqual("nestedValue", context.codingPath[2].stringValue)
XCTAssertEqual("intValue", context.codingPath[3].stringValue)
} catch {
XCTFail("Unexpected error: \(String(describing: error))")
}
}
func testDecodingKeyStrategyCamelGenerated() {
let encoded = DecodeMe3(thisIsCamelCase: "test")
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let resultData = try! encoder.encode(encoded)
let resultString = String(bytes: resultData, encoding: String._Encoding.utf8)
XCTAssertEqual("{\"this_is_camel_case\":\"test\"}", resultString)
}
func testDecodingStringExpectedType() {
let input = #"{"thisIsCamelCase": null}"#.data(using: String._Encoding.utf8)!
do {
_ = try JSONDecoder().decode(DecodeMe3.self, from: input)
} catch DecodingError.valueNotFound(let expected, _) {
XCTAssertTrue(expected == String.self)
} catch {
XCTFail("Unexpected error: \(String(describing: error))")
}
}
func testEncodingKeyStrategySnakeGenerated() {
// Test that this works with a struct that has automatically generated keys
let input = "{\"this_is_camel_case\":\"test\"}".data(using: String._Encoding.utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try! decoder.decode(DecodeMe3.self, from: input)
XCTAssertEqual("test", result.thisIsCamelCase)
}
func testEncodingDictionaryFailureKeyPath() {
let toEncode: [String: EncodeFailure] = ["key": EncodeFailure(someValue: Double.nan)]
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
do {
_ = try encoder.encode(toEncode)
} catch EncodingError.invalidValue(_, let context) {
XCTAssertEqual(2, context.codingPath.count)
XCTAssertEqual("key", context.codingPath[0].stringValue)
XCTAssertEqual("someValue", context.codingPath[1].stringValue)
} catch {
XCTFail("Unexpected error: \(String(describing: error))")
}
}
func testEncodingDictionaryFailureKeyPathNested() {
let toEncode: [String: [String: EncodeFailureNested]] = ["key": ["sub_key": EncodeFailureNested(nestedValue: EncodeFailure(someValue: Double.nan))]]
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
do {
_ = try encoder.encode(toEncode)
} catch EncodingError.invalidValue(_, let context) {
XCTAssertEqual(4, context.codingPath.count)
XCTAssertEqual("key", context.codingPath[0].stringValue)
XCTAssertEqual("sub_key", context.codingPath[1].stringValue)
XCTAssertEqual("nestedValue", context.codingPath[2].stringValue)
XCTAssertEqual("someValue", context.codingPath[3].stringValue)
} catch {
XCTFail("Unexpected error: \(String(describing: error))")
}
}
func testEncodingKeyStrategySnake() {
let toSnakeCaseTests = [
("simpleOneTwo", "simple_one_two"),
("myURL", "my_url"),
("singleCharacterAtEndX", "single_character_at_end_x"),
("thisIsAnXMLProperty", "this_is_an_xml_property"),
("single", "single"), // no underscore
("", ""), // don't die on empty string
("a", "a"), // single character
("aA", "a_a"), // two characters
("version4Thing", "version4_thing"), // numerics
("partCAPS", "part_caps"), // only insert underscore before first all caps
("partCAPSLowerAGAIN", "part_caps_lower_again"), // switch back and forth caps.
("manyWordsInThisThing", "many_words_in_this_thing"), // simple lowercase + underscore + more
("asdfĆqer", "asdf_ćqer"),
("already_snake_case", "already_snake_case"),
("dataPoint22", "data_point22"),
("dataPoint22Word", "data_point22_word"),
("_oneTwoThree", "_one_two_three"),
("oneTwoThree_", "one_two_three_"),
("__oneTwoThree", "__one_two_three"),
("oneTwoThree__", "one_two_three__"),
("_oneTwoThree_", "_one_two_three_"),
("__oneTwoThree", "__one_two_three"),
("__oneTwoThree__", "__one_two_three__"),
("_test", "_test"),
("_test_", "_test_"),
("__test", "__test"),
("test__", "test__"),
("m͉̟̹y̦̳G͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖U͇̝̠R͙̻̥͓̣L̥̖͎͓̪̫ͅR̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ", "m͉̟̹y̦̳_g͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖_u͇̝̠r͙̻̥͓̣l̥̖͎͓̪̫ͅ_r̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ"), // because Itai wanted to test this
("🐧🐟", "🐧🐟") // fishy emoji example?
]
for test in toSnakeCaseTests {
let expected = "{\"\(test.1)\":\"test\"}"
let encoded = EncodeMe(keyName: test.0)
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let resultData = try! encoder.encode(encoded)
let resultString = String(bytes: resultData, encoding: String._Encoding.utf8)
XCTAssertEqual(expected, resultString)
}
}
func test_twoByteUTF16Inputs() {
let json = "7"
let decoder = JSONDecoder()
XCTAssertEqual(7, try decoder.decode(Int.self, from: json.data(using: .utf16BigEndian)!))
XCTAssertEqual(7, try decoder.decode(Int.self, from: json.data(using: .utf16LittleEndian)!))
}
private func _run_passTest<T:Codable & Equatable>(name: String, json5: Bool = false, type: T.Type) {
let jsonData = testData(forResource: name, withExtension: json5 ? "json5" : "json" , subdirectory: json5 ? "JSON5/pass" : "JSON/pass")!
let plistData = testData(forResource: name, withExtension: "plist", subdirectory: "JSON/pass")
let decoder = json5Decoder
let decoded: T
do {
decoded = try decoder.decode(T.self, from: jsonData)
} catch {
XCTFail("Pass test \"\(name)\" failed with error: \(error)")
return
}
let prettyPrintEncoder = JSONEncoder()
prettyPrintEncoder.outputFormatting = .prettyPrinted
for encoder in [JSONEncoder(), prettyPrintEncoder] {
let reencodedData = try! encoder.encode(decoded)
let redecodedObjects = try! decoder.decode(T.self, from: reencodedData)
XCTAssertEqual(decoded, redecodedObjects)
if let plistData {
let decodedPlistObjects = try! PropertyListDecoder().decode(T.self, from: plistData)
XCTAssertEqual(decoded, decodedPlistObjects)
}
}
}
func test_JSONPassTests() {
_run_passTest(name: "pass1-utf8", type: JSONPass.Test1.self)
_run_passTest(name: "pass1-utf16be", type: JSONPass.Test1.self)
_run_passTest(name: "pass1-utf16le", type: JSONPass.Test1.self)
_run_passTest(name: "pass1-utf32be", type: JSONPass.Test1.self)
_run_passTest(name: "pass1-utf32le", type: JSONPass.Test1.self)
_run_passTest(name: "pass2", type: JSONPass.Test2.self)
_run_passTest(name: "pass3", type: JSONPass.Test3.self)
_run_passTest(name: "pass4", type: JSONPass.Test4.self)
_run_passTest(name: "pass5", type: JSONPass.Test5.self)
_run_passTest(name: "pass6", type: JSONPass.Test6.self)
_run_passTest(name: "pass7", type: JSONPass.Test7.self)
_run_passTest(name: "pass8", type: JSONPass.Test8.self)
_run_passTest(name: "pass9", type: JSONPass.Test9.self)
_run_passTest(name: "pass10", type: JSONPass.Test10.self)
_run_passTest(name: "pass11", type: JSONPass.Test11.self)
_run_passTest(name: "pass12", type: JSONPass.Test12.self)
_run_passTest(name: "pass13", type: JSONPass.Test13.self)
_run_passTest(name: "pass14", type: JSONPass.Test14.self)
_run_passTest(name: "pass15", type: JSONPass.Test15.self)
}
func test_json5PassJSONFiles() {
_run_passTest(name: "example", json5: true, type: JSON5Pass.Example.self)
_run_passTest(name: "hex", json5: true, type: JSON5Pass.Hex.self)
_run_passTest(name: "numbers", json5: true, type: JSON5Pass.Numbers.self)
_run_passTest(name: "strings", json5: true, type: JSON5Pass.Strings.self)
_run_passTest(name: "whitespace", json5: true, type: JSON5Pass.Whitespace.self)
}
private func _run_failTest<T:Decodable>(name: String, type: T.Type) {
let jsonData = testData(forResource: name, withExtension: "json", subdirectory: "JSON/fail")!
let decoder = JSONDecoder()
decoder.assumesTopLevelDictionary = true
do {
let _ = try decoder.decode(T.self, from: jsonData)
XCTFail("Decoding should have failed for invalid JSON data (test name: \(name))")
} catch {
print(error as NSError)
}
}
func test_JSONFailTests() {
_run_failTest(name: "fail1", type: JSONFail.Test1.self)
_run_failTest(name: "fail2", type: JSONFail.Test2.self)
_run_failTest(name: "fail3", type: JSONFail.Test3.self)
_run_failTest(name: "fail4", type: JSONFail.Test4.self)
_run_failTest(name: "fail5", type: JSONFail.Test5.self)
_run_failTest(name: "fail6", type: JSONFail.Test6.self)
_run_failTest(name: "fail7", type: JSONFail.Test7.self)
_run_failTest(name: "fail8", type: JSONFail.Test8.self)
_run_failTest(name: "fail9", type: JSONFail.Test9.self)
_run_failTest(name: "fail10", type: JSONFail.Test10.self)
_run_failTest(name: "fail11", type: JSONFail.Test11.self)
_run_failTest(name: "fail12", type: JSONFail.Test12.self)
_run_failTest(name: "fail13", type: JSONFail.Test13.self)
_run_failTest(name: "fail14", type: JSONFail.Test14.self)
_run_failTest(name: "fail15", type: JSONFail.Test15.self)
_run_failTest(name: "fail16", type: JSONFail.Test16.self)
_run_failTest(name: "fail17", type: JSONFail.Test17.self)
_run_failTest(name: "fail18", type: JSONFail.Test18.self)
_run_failTest(name: "fail19", type: JSONFail.Test19.self)
_run_failTest(name: "fail21", type: JSONFail.Test21.self)
_run_failTest(name: "fail22", type: JSONFail.Test22.self)
_run_failTest(name: "fail23", type: JSONFail.Test23.self)
_run_failTest(name: "fail24", type: JSONFail.Test24.self)
_run_failTest(name: "fail25", type: JSONFail.Test25.self)
_run_failTest(name: "fail26", type: JSONFail.Test26.self)
_run_failTest(name: "fail27", type: JSONFail.Test27.self)
_run_failTest(name: "fail28", type: JSONFail.Test28.self)
_run_failTest(name: "fail29", type: JSONFail.Test29.self)
_run_failTest(name: "fail30", type: JSONFail.Test30.self)
_run_failTest(name: "fail31", type: JSONFail.Test31.self)
_run_failTest(name: "fail32", type: JSONFail.Test32.self)
_run_failTest(name: "fail33", type: JSONFail.Test33.self)
_run_failTest(name: "fail34", type: JSONFail.Test34.self)
_run_failTest(name: "fail35", type: JSONFail.Test35.self)
_run_failTest(name: "fail36", type: JSONFail.Test36.self)
_run_failTest(name: "fail37", type: JSONFail.Test37.self)
_run_failTest(name: "fail38", type: JSONFail.Test38.self)
_run_failTest(name: "fail39", type: JSONFail.Test39.self)
_run_failTest(name: "fail40", type: JSONFail.Test40.self)
_run_failTest(name: "fail41", type: JSONFail.Test41.self)
}
func _run_json5SpecTest<T:Decodable>(_ category: String, _ name: String, testType: JSON5SpecTestType, type: T.Type) {
let subdirectory = "/JSON5/spec/\(category)"
let ext = testType.fileExtension
let jsonData = testData(forResource: name, withExtension: ext, subdirectory: subdirectory)!
let json5 = json5Decoder
let json = JSONDecoder()
switch testType {
case .json, .json5_foundationPermissiveJSON:
// Valid JSON should remain valid JSON5
XCTAssertNoThrow(try json5.decode(type, from: jsonData))
// Repeat with non-JSON5-compliant decoder.
XCTAssertNoThrow(try json.decode(type, from: jsonData))
case .json5:
XCTAssertNoThrow(try json5.decode(type, from: jsonData))
// Regular JSON decoder should throw.
do {
let val = try json.decode(type, from: jsonData)
XCTFail("Expected decode failure (original JSON)for test \(name).\(ext), but got: \(val)")
} catch { }
case .js:
// Valid ES5 that's explicitly disallowed by JSON5 is also invalid JSON.
do {
let val = try json5.decode(type, from: jsonData)
XCTFail("Expected decode failure (JSON5) for test \(name).\(ext), but got: \(val)")
} catch { }
// Regular JSON decoder should also throw.
do {
let val = try json.decode(type, from: jsonData)
XCTFail("Expected decode failure (original JSON) for test \(name).\(ext), but got: \(val)")
} catch { }
case .malformed:
// Invalid ES5 should remain invalid JSON5
do {
let val = try json5.decode(type, from: jsonData)
XCTFail("Expected decode failure (JSON5) for test \(name).\(ext), but got: \(val)")
} catch { }
// Regular JSON decoder should also throw.
do {
let val = try json.decode(type, from: jsonData)
XCTFail("Expected decode failure (original JSON) for test \(name).\(ext), but got: \(val)")
} catch { }
}
}
// Also tests non-JSON5 decoder against the non-JSON5 tests in this test suite.
func test_json5Spec() {
// Expected successes:
_run_json5SpecTest("arrays", "empty-array", testType: .json, type: [Bool].self)
_run_json5SpecTest("arrays", "regular-array", testType: .json, type: [Bool?].self)
_run_json5SpecTest("arrays", "trailing-comma-array", testType: .json5_foundationPermissiveJSON, type: [NullReader].self)
_run_json5SpecTest("comments", "block-comment-following-array-element", testType: .json5, type: [Bool].self)
_run_json5SpecTest("comments", "block-comment-following-top-level-value", testType: .json5, type: NullReader.self)
_run_json5SpecTest("comments", "block-comment-in-string", testType: .json, type: String.self)
_run_json5SpecTest("comments", "block-comment-preceding-top-level-value", testType: .json5, type: NullReader.self)
_run_json5SpecTest("comments", "block-comment-with-asterisks", testType: .json5, type: Bool.self)
_run_json5SpecTest("comments", "inline-comment-following-array-element", testType: .json5, type: [Bool].self)
_run_json5SpecTest("comments", "inline-comment-following-top-level-value", testType: .json5, type: NullReader.self)
_run_json5SpecTest("comments", "inline-comment-in-string", testType: .json, type: String.self)
_run_json5SpecTest("comments", "inline-comment-preceding-top-level-value", testType: .json5, type: NullReader.self)
_run_json5SpecTest("misc", "npm-package", testType: .json, type: JSON5Spec.NPMPackage.self)
_run_json5SpecTest("misc", "npm-package", testType: .json5, type: JSON5Spec.NPMPackage.self)
_run_json5SpecTest("misc", "readme-example", testType: .json5, type: JSON5Spec.ReadmeExample.self)
_run_json5SpecTest("misc", "valid-whitespace", testType: .json5, type: [String:Bool].self)
_run_json5SpecTest("new-lines", "comment-cr", testType: .json5, type: [String:String].self)
_run_json5SpecTest("new-lines", "comment-crlf", testType: .json5, type: [String:String].self)
_run_json5SpecTest("new-lines", "comment-lf", testType: .json5, type: [String:String].self)
_run_json5SpecTest("new-lines", "escaped-cr", testType: .json5, type: [String:String].self)
_run_json5SpecTest("new-lines", "escaped-crlf", testType: .json5, type: [String:String].self)
_run_json5SpecTest("new-lines", "escaped-lf", testType: .json5, type: [String:String].self)
_run_json5SpecTest("numbers", "float-leading-decimal-point", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "float-leading-zero", testType: .json, type: Double.self)
_run_json5SpecTest("numbers", "float-trailing-decimal-point-with-integer-exponent", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "float-trailing-decimal-point", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "float-with-integer-exponent", testType: .json, type: Double.self)
_run_json5SpecTest("numbers", "float", testType: .json, type: Double.self)
_run_json5SpecTest("numbers", "hexadecimal-lowercase-letter", testType: .json5, type: UInt.self)
_run_json5SpecTest("numbers", "hexadecimal-uppercase-x", testType: .json5, type: UInt.self)
_run_json5SpecTest("numbers", "hexadecimal-with-integer-exponent", testType: .json5, type: UInt.self)
_run_json5SpecTest("numbers", "hexadecimal", testType: .json5, type: UInt.self)
_run_json5SpecTest("numbers", "infinity", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "integer-with-integer-exponent", testType: .json, type: Double.self)
_run_json5SpecTest("numbers", "integer-with-negative-integer-exponent", testType: .json, type: Double.self)
_run_json5SpecTest("numbers", "integer-with-negative-zero-integer-exponent", testType: .json, type: Int.self)
_run_json5SpecTest("numbers", "integer-with-positive-integer-exponent", testType: .json, type: Int.self)
_run_json5SpecTest("numbers", "integer-with-positive-zero-integer-exponent", testType: .json, type: Int.self)
_run_json5SpecTest("numbers", "integer-with-zero-integer-exponent", testType: .json, type: Int.self)
_run_json5SpecTest("numbers", "integer", testType: .json, type: Int.self)
_run_json5SpecTest("numbers", "nan", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "negative-float-leading-decimal-point", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "negative-float-leading-zero", testType: .json, type: Double.self)
_run_json5SpecTest("numbers", "negative-float-trailing-decimal-point", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "negative-float", testType: .json, type: Double.self)
_run_json5SpecTest("numbers", "negative-hexadecimal", testType: .json5, type: Int.self)
_run_json5SpecTest("numbers", "negative-infinity", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "negative-integer", testType: .json, type: Int.self)
_run_json5SpecTest("numbers", "negative-zero-float-leading-decimal-point", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "negative-zero-float-trailing-decimal-point", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "negative-zero-hexadecimal", testType: .json5, type: Int.self)
_run_json5SpecTest("numbers", "negative-zero-integer", testType: .json, type: Int.self)
_run_json5SpecTest("numbers", "positive-integer", testType: .json5, type: Int.self)
_run_json5SpecTest("numbers", "positive-zero-float-leading-decimal-point", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "positive-zero-float-trailing-decimal-point", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "positive-zero-float", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "positive-zero-hexadecimal", testType: .json5, type: Int.self)
_run_json5SpecTest("numbers", "positive-zero-integer", testType: .json5, type: Int.self)
_run_json5SpecTest("numbers", "zero-float-leading-decimal-point", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "zero-float-trailing-decimal-point", testType: .json5, type: Double.self)
_run_json5SpecTest("numbers", "zero-float", testType: .json, type: Double.self)
_run_json5SpecTest("numbers", "zero-hexadecimal", testType: .json5, type: Int.self)
_run_json5SpecTest("numbers", "zero-integer-with-integer-exponent", testType: .json, type: Int.self)
_run_json5SpecTest("numbers", "zero-integer", testType: .json, type: Int.self)
_run_json5SpecTest("objects", "duplicate-keys", testType: .json, type: [String:Bool].self)
_run_json5SpecTest("objects", "empty-object", testType: .json, type: [String:Bool].self)
_run_json5SpecTest("objects", "reserved-unquoted-key", testType: .json5, type: [String:Bool].self)
_run_json5SpecTest("objects", "single-quoted-key", testType: .json5, type: [String:String].self)
_run_json5SpecTest("objects", "trailing-comma-object", testType: .json5_foundationPermissiveJSON, type: [String:String].self)
_run_json5SpecTest("objects", "unquoted-keys", testType: .json5, type: [String:String].self)
_run_json5SpecTest("strings", "escaped-single-quoted-string", testType: .json5, type: String.self)
_run_json5SpecTest("strings", "multi-line-string", testType: .json5, type: String.self)
_run_json5SpecTest("strings", "single-quoted-string", testType: .json5, type: String.self)
_run_json5SpecTest("todo", "unicode-escaped-unquoted-key", testType: .json5, type: [String:String].self)
_run_json5SpecTest("todo", "unicode-unquoted-key", testType: .json5, type: [String:String].self)
// Expected failures:
_run_json5SpecTest("arrays", "leading-comma-array", testType: .js, type: [Bool].self)
_run_json5SpecTest("arrays", "lone-trailing-comma-array", testType: .js, type: [Bool].self)
_run_json5SpecTest("arrays", "no-comma-array", testType: .malformed, type: [Bool].self)
_run_json5SpecTest("comments", "top-level-block-comment", testType: .malformed, type: Bool.self)
_run_json5SpecTest("comments", "top-level-inline-comment", testType: .malformed, type: Bool.self)
_run_json5SpecTest("comments", "unterminated-block-comment", testType: .malformed, type: Bool.self)
_run_json5SpecTest("misc", "empty", testType: .malformed, type: Bool.self)
_run_json5SpecTest("numbers", "hexadecimal-empty", testType: .malformed, type: UInt.self)
_run_json5SpecTest("numbers", "integer-with-float-exponent", testType: .malformed, type: Double.self)
_run_json5SpecTest("numbers", "integer-with-hexadecimal-exponent", testType: .malformed, type: Double.self)
_run_json5SpecTest("numbers", "integer-with-negative-float-exponent", testType: .malformed, type: Double.self)
_run_json5SpecTest("numbers", "integer-with-negative-hexadecimal-exponent", testType: .malformed, type: Double.self)
_run_json5SpecTest("numbers", "integer-with-positive-float-exponent", testType: .malformed, type: Double.self)
_run_json5SpecTest("numbers", "integer-with-positive-hexadecimal-exponent", testType: .malformed, type: Double.self)
_run_json5SpecTest("numbers", "lone-decimal-point", testType: .malformed, type: Double.self)
_run_json5SpecTest("numbers", "negative-noctal", testType: .js, type: Int.self)
_run_json5SpecTest("numbers", "negative-octal", testType: .malformed, type: Int.self)
_run_json5SpecTest("numbers", "noctal-with-leading-octal-digit", testType: .js, type: Int.self)
_run_json5SpecTest("numbers", "noctal", testType: .js, type: Int.self)
_run_json5SpecTest("numbers", "octal", testType: .malformed, type: Int.self)
_run_json5SpecTest("numbers", "positive-noctal", testType: .js, type: Int.self)
_run_json5SpecTest("numbers", "positive-octal", testType: .malformed, type: Int.self)
_run_json5SpecTest("numbers", "positive-zero-octal", testType: .malformed, type: Int.self)
_run_json5SpecTest("numbers", "zero-octal", testType: .malformed, type: Int.self)
_run_json5SpecTest("objects", "illegal-unquoted-key-number", testType: .malformed, type: [String:String].self)
// The spec test disallows this case, but historically NSJSONSerialization has allowed it. Our new implementation is more up-to-spec.
_run_json5SpecTest("objects", "illegal-unquoted-key-symbol", testType: .malformed, type: [String:String].self)
_run_json5SpecTest("objects", "leading-comma-object", testType: .malformed, type: [String:String].self)
_run_json5SpecTest("objects", "lone-trailing-comma-object", testType: .malformed, type: [String:String].self)
_run_json5SpecTest("objects", "no-comma-object", testType: .malformed, type: [String:String].self)
_run_json5SpecTest("strings", "unescaped-multi-line-string", testType: .malformed, type: String.self)
}
func testEncodingDateISO8601() {
let timestamp = Date(timeIntervalSince1970: 1000)
let expectedJSON = "\"\(timestamp.formatted(.iso8601))\"".data(using: String._Encoding.utf8)!
_testRoundTrip(of: timestamp,
expectedJSON: expectedJSON,
dateEncodingStrategy: .iso8601,
dateDecodingStrategy: .iso8601)
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .iso8601,
dateDecodingStrategy: .iso8601)
}
func testEncodingDataBase64() {
let data = Data([0xDE, 0xAD, 0xBE, 0xEF])
let expectedJSON = "\"3q2+7w==\"".data(using: String._Encoding.utf8)!
_testRoundTrip(of: data, expectedJSON: expectedJSON)
// Optional data should encode the same way.
_testRoundTrip(of: Optional(data), expectedJSON: expectedJSON)
}
}
// MARK: - Decimal Tests
extension JSONEncoderTests {
func testInterceptDecimal() {
let expectedJSON = "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".data(using: String._Encoding.utf8)!
// Want to make sure we write out a JSON number, not the keyed encoding here.
// 1e127 is too big to fit natively in a Double, too, so want to make sure it's encoded as a Decimal.
let decimal = Decimal(sign: .plus, exponent: 127, significand: Decimal(1))
_testRoundTrip(of: decimal, expectedJSON: expectedJSON)
// Optional Decimals should encode the same way.
_testRoundTrip(of: Optional(decimal), expectedJSON: expectedJSON)
}
func test_hugeNumbers() {
let json = "23456789012000000000000000000000000000000000000000000000000000000000000000000 "
let data = json.data(using: String._Encoding.utf8)!
let decimal = try! JSONDecoder().decode(Decimal.self, from: data)
let expected = Decimal(string: json)
XCTAssertEqual(decimal, expected)
}
func testInterceptLargeDecimal() {
struct TestBigDecimal: Codable, Equatable {
var uint64Max: Decimal = Decimal(UInt64.max)
var unit64MaxPlus1: Decimal = Decimal(
_exponent: 0,
_length: 5,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0, 0, 0, 0, 1, 0, 0, 0)
)
var int64Min: Decimal = Decimal(Int64.min)
var int64MinMinus1: Decimal = Decimal(
_exponent: 0,
_length: 4,
_isNegative: 1,
_isCompact: 1,
_reserved: 0,
_mantissa: (1, 0, 0, 32768, 0, 0, 0, 0)
)
}
let testBigDecimal = TestBigDecimal()
_testRoundTrip(of: testBigDecimal)
}
func testOverlargeDecimal() {
// Check value too large fails to decode.
XCTAssertThrowsError(try JSONDecoder().decode(Decimal.self, from: "100e200".data(using: .utf8)!))
}
}
// MARK: - Framework-only tests
#if FOUNDATION_FRAMEWORK
extension JSONEncoderTests {
// This will remain a framework-only test due to dependence on `DateFormatter`.
func testEncodingDateFormatted() {
let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.timeStyle = .full
let timestamp = Date(timeIntervalSince1970: 1000)
let expectedJSON = "\"\(formatter.string(from: timestamp))\"".data(using: String._Encoding.utf8)!
_testRoundTrip(of: timestamp,
expectedJSON: expectedJSON,
dateEncodingStrategy: .formatted(formatter),
dateDecodingStrategy: .formatted(formatter))
// Optional dates should encode the same way.
_testRoundTrip(of: Optional(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .formatted(formatter),
dateDecodingStrategy: .formatted(formatter))
}
}
#endif
// MARK: - .sortedKeys Tests
extension JSONEncoderTests {
func testEncodingTopLevelStructuredClass() {
// Person is a class with multiple fields.
let expectedJSON = "{\"email\":\"appleseed@apple.com\",\"name\":\"Johnny Appleseed\"}".data(using: String._Encoding.utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys])
}
func testEncodingOutputFormattingSortedKeys() {
let expectedJSON = "{\"email\":\"appleseed@apple.com\",\"name\":\"Johnny Appleseed\"}".data(using: String._Encoding.utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys])
}
func testEncodingOutputFormattingPrettyPrintedSortedKeys() {
let expectedJSON = "{\n \"email\" : \"appleseed@apple.com\",\n \"name\" : \"Johnny Appleseed\"\n}".data(using: String._Encoding.utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted, .sortedKeys])
}
func testEncodingSortedKeys() {
// When requesting sorted keys, dictionary keys are sorted prior to being written out.
// This sort should be stable, numeric, and follow human-readable sorting rules as defined by the system locale.
let dict = [
// These three keys should appear in a stable, deterministic ordering relative to one another, regardless of their order in the dictionary.
// For example, if the sort were naively case-insensitive, these three would be `NSOrderedSame`, and would not swap with one another in the sort, maintaining their relative ordering based on their position in the dictionary. The inclusion of other keys in the dictionary can alter their relative ordering (because of hashing), producing non-stable output.
"Foo" : 1,
"FOO" : 2,
"foo" : 3,
// These keys should output in numeric order (1, 2, 3, 11, 12) rather than literal string order (1, 11, 12, 2, 3).
"foo1" : 4,
"Foo2" : 5,
"foo3" : 6,
"foo12" : 7,
"Foo11" : 8,
// This key should be sorted in a human-readable way (e.g. among the other "foo" keys, not after them just because the binary value of 'ø' > 'o').
"føo" : 9,
"bar" : 10
]
_testRoundTrip(of: dict, expectedJSON: #"{"FOO":2,"Foo":1,"Foo11":8,"Foo2":5,"bar":10,"foo":3,"foo1":4,"foo12":7,"foo3":6,"føo":9}"#.data(using: String._Encoding.utf8)!, outputFormatting: [.sortedKeys])
}
func testEncodingSortedKeysStableOrdering() {
// We want to make sure that keys of different length (but with identical prefixes) always sort in a stable way, regardless of their hash ordering.
var dict = ["AAA" : 1, "AAAAAAB" : 2]
var expectedJSONString = "{\"AAA\":1,\"AAAAAAB\":2}"
_testRoundTrip(of: dict, expectedJSON: expectedJSONString.data(using: String._Encoding.utf8)!, outputFormatting: [.sortedKeys])
// We don't want this test to rely on the hashing of Strings or how Dictionary uses that hash.
// We'll insert a large number of keys into this dictionary and guarantee that the ordering of the above keys has indeed not changed.
// To ensure that we don't accidentally test the same (passing) case every time these keys will be shuffled.
let testSize = 256
var Ns = Array(0 ..< testSize)
// Simple Fisher-Yates shuffle.
for i in Ns.indices.reversed() {
let index = Int(Double.random(in: 0.0 ..< Double(i+1)))
let N = Ns[i]
Ns[i] = Ns[index]
// Normally we'd set Ns[index] = N, but since all we need this value for is for inserting into the dictionary later, we can do it right here and not even write back to the source array.
// No need to do an O(n) loop over Ns again.
dict["key\(N)"] = N
}
let numberKeys = (0 ..< testSize).map { "\($0)" }.sorted()
for key in numberKeys {
let insertedKeyJSON = ",\"key\(key)\":\(key)"
expectedJSONString.insert(contentsOf: insertedKeyJSON, at: expectedJSONString.index(before: expectedJSONString.endIndex))
}
_testRoundTrip(of: dict, expectedJSON: expectedJSONString.data(using: String._Encoding.utf8)!, outputFormatting: [.sortedKeys])
}
func testEncodingMultipleNestedContainersWithTheSameTopLevelKey() {
struct Model : Codable, Equatable {
let first: String
let second: String
init(from coder: Decoder) throws {
let container = try coder.container(keyedBy: TopLevelCodingKeys.self)
let firstNestedContainer = try container.nestedContainer(keyedBy: FirstNestedCodingKeys.self, forKey: .top)
self.first = try firstNestedContainer.decode(String.self, forKey: .first)
let secondNestedContainer = try container.nestedContainer(keyedBy: SecondNestedCodingKeys.self, forKey: .top)
self.second = try secondNestedContainer.decode(String.self, forKey: .second)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: TopLevelCodingKeys.self)
var firstNestedContainer = container.nestedContainer(keyedBy: FirstNestedCodingKeys.self, forKey: .top)
try firstNestedContainer.encode(self.first, forKey: .first)
var secondNestedContainer = container.nestedContainer(keyedBy: SecondNestedCodingKeys.self, forKey: .top)
try secondNestedContainer.encode(self.second, forKey: .second)
}
init(first: String, second: String) {
self.first = first
self.second = second
}
static var testValue: Model {
return Model(first: "Johnny Appleseed",
second: "appleseed@apple.com")
}
enum TopLevelCodingKeys : String, CodingKey {
case top
}
enum FirstNestedCodingKeys : String, CodingKey {
case first
}
enum SecondNestedCodingKeys : String, CodingKey {
case second
}
}
let model = Model.testValue
let expectedJSON = "{\"top\":{\"first\":\"Johnny Appleseed\",\"second\":\"appleseed@apple.com\"}}".data(using: String._Encoding.utf8)!
_testRoundTrip(of: model, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys])
}
func test_redundantKeyedContainer() {
struct EncodesTwice: Encodable {
enum CodingKeys: String, CodingKey {
case container
case somethingElse
}
struct Nested: Encodable {
let foo = "Test"
}
func encode(to encoder: Encoder) throws {
var topLevel = encoder.container(keyedBy: CodingKeys.self)
try topLevel.encode("Foo", forKey: .somethingElse)
// Encode an object-like JSON value for the key "container"
try topLevel.encode(Nested(), forKey: .container)
// A nested container for the same "container" key should reuse the previous container, appending to it, instead of asserting. 106648746.
var secondAgain = topLevel.nestedContainer(keyedBy: CodingKeys.self, forKey: .container)
try secondAgain.encode("SecondAgain", forKey: .somethingElse)
}
}
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let data = try! encoder.encode(EncodesTwice())
let string = String(data: data, encoding: .utf8)!
XCTAssertEqual(string, "{\"container\":{\"foo\":\"Test\",\"somethingElse\":\"SecondAgain\"},\"somethingElse\":\"Foo\"}")
}
func test_singleValueDictionaryAmendedByContainer() {
struct Test: Encodable {
enum CodingKeys: String, CodingKey {
case a
}
func encode(to encoder: Encoder) throws {
var svc = encoder.singleValueContainer()
try svc.encode(["a" : "b", "other" : "foo"])
var keyed = encoder.container(keyedBy: CodingKeys.self)
try keyed.encode("c", forKey: .a)
}
}
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let data = try! encoder.encode(Test())
let string = String(data: data, encoding: .utf8)!
XCTAssertEqual(string, "{\"a\":\"c\",\"other\":\"foo\"}")
}
}
// MARK: - URL Tests
extension JSONEncoderTests {
func testInterceptURL() {
// Want to make sure JSONEncoder writes out single-value URLs, not the keyed encoding.
let expectedJSON = "\"http:\\/\\/swift.org\"".data(using: String._Encoding.utf8)!
let url = URL(string: "http://swift.org")!
_testRoundTrip(of: url, expectedJSON: expectedJSON)
// Optional URLs should encode the same way.
_testRoundTrip(of: Optional(url), expectedJSON: expectedJSON)
}
func testInterceptURLWithoutEscapingOption() {
// Want to make sure JSONEncoder writes out single-value URLs, not the keyed encoding.
let expectedJSON = "\"http://swift.org\"".data(using: String._Encoding.utf8)!
let url = URL(string: "http://swift.org")!
_testRoundTrip(of: url, expectedJSON: expectedJSON, outputFormatting: [.withoutEscapingSlashes])
// Optional URLs should encode the same way.
_testRoundTrip(of: Optional(url), expectedJSON: expectedJSON, outputFormatting: [.withoutEscapingSlashes])
}
}
// MARK: - Helper Global Functions
func expectEqualPaths(_ lhs: [CodingKey], _ rhs: [CodingKey], _ prefix: String) {
if lhs.count != rhs.count {
XCTFail("\(prefix) [CodingKey].count mismatch: \(lhs.count) != \(rhs.count)")
return
}
for (key1, key2) in zip(lhs, rhs) {
switch (key1.intValue, key2.intValue) {
case (.none, .none): break
case (.some(let i1), .none):
XCTFail("\(prefix) CodingKey.intValue mismatch: \(type(of: key1))(\(i1)) != nil")
return
case (.none, .some(let i2)):
XCTFail("\(prefix) CodingKey.intValue mismatch: nil != \(type(of: key2))(\(i2))")
return
case (.some(let i1), .some(let i2)):
guard i1 == i2 else {
XCTFail("\(prefix) CodingKey.intValue mismatch: \(type(of: key1))(\(i1)) != \(type(of: key2))(\(i2))")
return
}
}
XCTAssertEqual(key1.stringValue, key2.stringValue, "\(prefix) CodingKey.stringValue mismatch: \(type(of: key1))('\(key1.stringValue)') != \(type(of: key2))('\(key2.stringValue)')")
}
}
// MARK: - Test Types
/* FIXME: Import from %S/Inputs/Coding/SharedTypes.swift somehow. */
// MARK: - Empty Types
fileprivate struct EmptyStruct : Codable, Equatable {
static func ==(_ lhs: EmptyStruct, _ rhs: EmptyStruct) -> Bool {
return true
}
}
fileprivate class EmptyClass : Codable, Equatable {
static func ==(_ lhs: EmptyClass, _ rhs: EmptyClass) -> Bool {
return true
}
}
// MARK: - Single-Value Types
/// A simple on-off switch type that encodes as a single Bool value.
fileprivate enum Switch : Codable {
case off
case on
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
switch try container.decode(Bool.self) {
case false: self = .off
case true: self = .on
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .off: try container.encode(false)
case .on: try container.encode(true)
}
}
}
/// A simple timestamp type that encodes as a single Double value.
fileprivate struct Timestamp : Codable, Equatable {
let value: Double
init(_ value: Double) {
self.value = value
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
value = try container.decode(Double.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.value)
}
static func ==(_ lhs: Timestamp, _ rhs: Timestamp) -> Bool {
return lhs.value == rhs.value
}
}
/// A simple referential counter type that encodes as a single Int value.
fileprivate final class Counter : Codable, Equatable {
var count: Int = 0
init() {}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
count = try container.decode(Int.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.count)
}
static func ==(_ lhs: Counter, _ rhs: Counter) -> Bool {
return lhs === rhs || lhs.count == rhs.count
}
}
// MARK: - Structured Types
/// A simple address type that encodes as a dictionary of values.
fileprivate struct Address : Codable, Equatable {
let street: String
let city: String
let state: String
let zipCode: Int
let country: String
init(street: String, city: String, state: String, zipCode: Int, country: String) {
self.street = street
self.city = city
self.state = state
self.zipCode = zipCode
self.country = country
}
static func ==(_ lhs: Address, _ rhs: Address) -> Bool {
return lhs.street == rhs.street &&
lhs.city == rhs.city &&
lhs.state == rhs.state &&
lhs.zipCode == rhs.zipCode &&
lhs.country == rhs.country
}
static var testValue: Address {
return Address(street: "1 Infinite Loop",
city: "Cupertino",
state: "CA",
zipCode: 95014,
country: "United States")
}
}
/// A simple person class that encodes as a dictionary of values.
fileprivate class Person : Codable, Equatable {
let name: String
let email: String
let website: URL?
init(name: String, email: String, website: URL? = nil) {
self.name = name
self.email = email
self.website = website
}
func isEqual(_ other: Person) -> Bool {
return self.name == other.name &&
self.email == other.email &&
self.website == other.website
}
static func ==(_ lhs: Person, _ rhs: Person) -> Bool {
return lhs.isEqual(rhs)
}
class var testValue: Person {
return Person(name: "Johnny Appleseed", email: "appleseed@apple.com")
}
}
/// A class which shares its encoder and decoder with its superclass.
fileprivate class Employee : Person {
let id: Int
init(name: String, email: String, website: URL? = nil, id: Int) {
self.id = id
super.init(name: name, email: email, website: website)
}
enum CodingKeys : String, CodingKey {
case id
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
try super.init(from: decoder)
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try super.encode(to: encoder)
}
override func isEqual(_ other: Person) -> Bool {
if let employee = other as? Employee {
guard self.id == employee.id else { return false }
}
return super.isEqual(other)
}
override class var testValue: Employee {
return Employee(name: "Johnny Appleseed", email: "appleseed@apple.com", id: 42)
}
}
/// A simple company struct which encodes as a dictionary of nested values.
fileprivate struct Company : Codable, Equatable {
let address: Address
var employees: [Employee]
init(address: Address, employees: [Employee]) {
self.address = address
self.employees = employees
}
static func ==(_ lhs: Company, _ rhs: Company) -> Bool {
return lhs.address == rhs.address && lhs.employees == rhs.employees
}
static var testValue: Company {
return Company(address: Address.testValue, employees: [Employee.testValue])
}
}
/// An enum type which decodes from Bool?.
fileprivate enum EnhancedBool : Codable {
case `true`
case `false`
case fileNotFound
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self = .fileNotFound
} else {
let value = try container.decode(Bool.self)
self = value ? .true : .false
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .true: try container.encode(true)
case .false: try container.encode(false)
case .fileNotFound: try container.encodeNil()
}
}
}
/// A type which encodes as an array directly through a single value container.
private struct Numbers : Codable, Equatable {
let values = [4, 8, 15, 16, 23, 42]
init() {}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let decodedValues = try container.decode([Int].self)
guard decodedValues == values else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "The Numbers are wrong!"))
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(values)
}
static func ==(_ lhs: Numbers, _ rhs: Numbers) -> Bool {
return lhs.values == rhs.values
}
static var testValue: Numbers {
return Numbers()
}
}
/// A type which encodes as a dictionary directly through a single value container.
fileprivate final class Mapping : Codable, Equatable {
let values: [String : Int]
init(values: [String : Int]) {
self.values = values
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
values = try container.decode([String : Int].self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(values)
}
static func ==(_ lhs: Mapping, _ rhs: Mapping) -> Bool {
return lhs === rhs || lhs.values == rhs.values
}
static var testValue: Mapping {
return Mapping(values: ["Apple": 42,
"localhost": 127])
}
}
private struct NestedContainersTestType : Encodable {
let testSuperEncoder: Bool
init(testSuperEncoder: Bool = false) {
self.testSuperEncoder = testSuperEncoder
}
enum TopLevelCodingKeys : Int, CodingKey {
case a
case b
case c
}
enum IntermediateCodingKeys : Int, CodingKey {
case one
case two
}
func encode(to encoder: Encoder) throws {
if self.testSuperEncoder {
var topLevelContainer = encoder.container(keyedBy: TopLevelCodingKeys.self)
expectEqualPaths(encoder.codingPath, [], "Top-level Encoder's codingPath changed.")
expectEqualPaths(topLevelContainer.codingPath, [], "New first-level keyed container has non-empty codingPath.")
let superEncoder = topLevelContainer.superEncoder(forKey: .a)
expectEqualPaths(encoder.codingPath, [], "Top-level Encoder's codingPath changed.")
expectEqualPaths(topLevelContainer.codingPath, [], "First-level keyed container's codingPath changed.")
expectEqualPaths(superEncoder.codingPath, [TopLevelCodingKeys.a], "New superEncoder had unexpected codingPath.")
_testNestedContainers(in: superEncoder, baseCodingPath: [TopLevelCodingKeys.a])
} else {
_testNestedContainers(in: encoder, baseCodingPath: [])
}
}
func _testNestedContainers(in encoder: Encoder, baseCodingPath: [CodingKey]) {
expectEqualPaths(encoder.codingPath, baseCodingPath, "New encoder has non-empty codingPath.")
// codingPath should not change upon fetching a non-nested container.
var firstLevelContainer = encoder.container(keyedBy: TopLevelCodingKeys.self)
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "New first-level keyed container has non-empty codingPath.")
// Nested Keyed Container
do {
// Nested container for key should have a new key pushed on.
var secondLevelContainer = firstLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self, forKey: .a)
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "New second-level keyed container had unexpected codingPath.")
// Inserting a keyed container should not change existing coding paths.
let thirdLevelContainerKeyed = secondLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self, forKey: .one)
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "Second-level keyed container's codingPath changed.")
expectEqualPaths(thirdLevelContainerKeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.a, IntermediateCodingKeys.one], "New third-level keyed container had unexpected codingPath.")
// Inserting an unkeyed container should not change existing coding paths.
let thirdLevelContainerUnkeyed = secondLevelContainer.nestedUnkeyedContainer(forKey: .two)
expectEqualPaths(encoder.codingPath, baseCodingPath + [], "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath + [], "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "Second-level keyed container's codingPath changed.")
expectEqualPaths(thirdLevelContainerUnkeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.a, IntermediateCodingKeys.two], "New third-level unkeyed container had unexpected codingPath.")
}
// Nested Unkeyed Container
do {
// Nested container for key should have a new key pushed on.
var secondLevelContainer = firstLevelContainer.nestedUnkeyedContainer(forKey: .b)
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.b], "New second-level keyed container had unexpected codingPath.")
// Appending a keyed container should not change existing coding paths.
let thirdLevelContainerKeyed = secondLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self)
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.b], "Second-level unkeyed container's codingPath changed.")
expectEqualPaths(thirdLevelContainerKeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.b, _TestKey(index: 0)], "New third-level keyed container had unexpected codingPath.")
// Appending an unkeyed container should not change existing coding paths.
let thirdLevelContainerUnkeyed = secondLevelContainer.nestedUnkeyedContainer()
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.b], "Second-level unkeyed container's codingPath changed.")
expectEqualPaths(thirdLevelContainerUnkeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.b, _TestKey(index: 1)], "New third-level unkeyed container had unexpected codingPath.")
}
}
}
private struct CodableTypeWithConfiguration : CodableWithConfiguration, Equatable {
struct Config {
let num: Int
init(_ num: Int) {
self.num = num
}
}
struct ConfigProviding : EncodingConfigurationProviding, DecodingConfigurationProviding {
static var encodingConfiguration: Config { Config(2) }
static var decodingConfiguration: Config { Config(2) }
}
typealias EncodingConfiguration = Config
typealias DecodingConfiguration = Config
static let testValue = Self(3)
let num: Int
init(_ num: Int) {
self.num = num
}
func encode(to encoder: Encoder, configuration: Config) throws {
var container = encoder.singleValueContainer()
try container.encode(num + configuration.num)
}
init(from decoder: Decoder, configuration: Config) throws {
let container = try decoder.singleValueContainer()
num = try container.decode(Int.self) - configuration.num
}
}
// MARK: - Helper Types
/// A key type which can take on any string or integer value.
/// This needs to mirror _CodingKey.
fileprivate struct _TestKey : CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
init(index: Int) {
self.stringValue = "Index \(index)"
self.intValue = index
}
}
fileprivate struct FloatNaNPlaceholder : Codable, Equatable {
init() {}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(Float.nan)
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let float = try container.decode(Float.self)
if !float.isNaN {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Couldn't decode NaN."))
}
}
static func ==(_ lhs: FloatNaNPlaceholder, _ rhs: FloatNaNPlaceholder) -> Bool {
return true
}
}
fileprivate struct DoubleNaNPlaceholder : Codable, Equatable {
init() {}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(Double.nan)
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let double = try container.decode(Double.self)
if !double.isNaN {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Couldn't decode NaN."))
}
}
static func ==(_ lhs: DoubleNaNPlaceholder, _ rhs: DoubleNaNPlaceholder) -> Bool {
return true
}
}
fileprivate enum EitherDecodable<T : Decodable, U : Decodable> : Decodable {
case t(T)
case u(U)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = .t(try container.decode(T.self))
} catch {
self = .u(try container.decode(U.self))
}
}
}
struct NullReader : Decodable, Equatable {
enum NullError : String, Error {
case expectedNull = "Expected a null value"
}
init(from decoder: Decoder) throws {
let c = try decoder.singleValueContainer()
guard c.decodeNil() else {
throw NullError.expectedNull
}
}
}
enum JSONPass { }
extension JSONPass {
struct Test1: Codable, Equatable {
let glossary: Glossary
struct Glossary: Codable, Equatable {
let title: String
let glossDiv: GlossDiv
enum CodingKeys: String, CodingKey {
case title
case glossDiv = "GlossDiv"
}
}
struct GlossDiv: Codable, Equatable {
let title: String
let glossList: GlossList
enum CodingKeys: String, CodingKey {
case title
case glossList = "GlossList"
}
}
struct GlossList: Codable, Equatable {
let glossEntry: GlossEntry
enum CodingKeys: String, CodingKey {
case glossEntry = "GlossEntry"
}
}
struct GlossEntry: Codable, Equatable {
let id, sortAs, glossTerm, acronym: String
let abbrev: String
let glossDef: GlossDef
let glossSee: String
enum CodingKeys: String, CodingKey {
case id = "ID"
case sortAs = "SortAs"
case glossTerm = "GlossTerm"
case acronym = "Acronym"
case abbrev = "Abbrev"
case glossDef = "GlossDef"
case glossSee = "GlossSee"
}
}
struct GlossDef: Codable, Equatable {
let para: String
let glossSeeAlso: [String]
enum CodingKeys: String, CodingKey {
case para
case glossSeeAlso = "GlossSeeAlso"
}
}
}
}
extension JSONPass {
struct Test2: Codable, Equatable {
let menu: Menu
struct Menu: Codable, Equatable {
let id, value: String
let popup: Popup
}
struct Popup: Codable, Equatable {
let menuitem: [Menuitem]
}
struct Menuitem: Codable, Equatable {
let value, onclick: String
}
}
}
extension JSONPass {
struct Test3: Codable, Equatable {
let widget: Widget
struct Widget: Codable, Equatable {
let debug: String
let window: Window
let image: Image
let text: Text
}
struct Image: Codable, Equatable {
let src, name: String
let hOffset, vOffset: Int
let alignment: String
}
struct Text: Codable, Equatable {
let data: String
let size: Int
let style, name: String
let hOffset, vOffset: Int
let alignment, onMouseUp: String
}
struct Window: Codable, Equatable {
let title, name: String
let width, height: Int
}
}
}
extension JSONPass {
struct Test4: Codable, Equatable {
let webApp: WebApp
enum CodingKeys: String, CodingKey {
case webApp = "web-app"
}
struct WebApp: Codable, Equatable {
let servlet: [Servlet]
let servletMapping: ServletMapping
let taglib: Taglib
enum CodingKeys: String, CodingKey {
case servlet
case servletMapping = "servlet-mapping"
case taglib
}
}
struct Servlet: Codable, Equatable {
let servletName, servletClass: String
let initParam: InitParam?
enum CodingKeys: String, CodingKey {
case servletName = "servlet-name"
case servletClass = "servlet-class"
case initParam = "init-param"
}
}
struct InitParam: Codable, Equatable {
let configGlossaryInstallationAt, configGlossaryAdminEmail, configGlossaryPoweredBy, configGlossaryPoweredByIcon: String?
let configGlossaryStaticPath, templateProcessorClass, templateLoaderClass, templatePath: String?
let templateOverridePath, defaultListTemplate, defaultFileTemplate: String?
let useJSP: Bool?
let jspListTemplate, jspFileTemplate: String?
let cachePackageTagsTrack, cachePackageTagsStore, cachePackageTagsRefresh, cacheTemplatesTrack: Int?
let cacheTemplatesStore, cacheTemplatesRefresh, cachePagesTrack, cachePagesStore: Int?
let cachePagesRefresh, cachePagesDirtyRead: Int?
let searchEngineListTemplate, searchEngineFileTemplate, searchEngineRobotsDB: String?
let useDataStore: Bool?
let dataStoreClass, redirectionClass, dataStoreName, dataStoreDriver: String?
let dataStoreURL, dataStoreUser, dataStorePassword, dataStoreTestQuery: String?
let dataStoreLogFile: String?
let dataStoreInitConns, dataStoreMaxConns, dataStoreConnUsageLimit: Int?
let dataStoreLogLevel: String?
let maxURLLength: Int?
let mailHost, mailHostOverride: String?
let log: Int?
let logLocation, logMaxSize: String?
let dataLog: Int?
let dataLogLocation, dataLogMaxSize, removePageCache, removeTemplateCache: String?
let fileTransferFolder: String?
let lookInContext, adminGroupID: Int?
let betaServer: Bool?
enum CodingKeys: String, CodingKey {
case configGlossaryInstallationAt
case configGlossaryAdminEmail
case configGlossaryPoweredBy
case configGlossaryPoweredByIcon
case configGlossaryStaticPath
case templateProcessorClass, templateLoaderClass, templatePath, templateOverridePath, defaultListTemplate, defaultFileTemplate, useJSP, jspListTemplate, jspFileTemplate, cachePackageTagsTrack, cachePackageTagsStore, cachePackageTagsRefresh, cacheTemplatesTrack, cacheTemplatesStore, cacheTemplatesRefresh, cachePagesTrack, cachePagesStore, cachePagesRefresh, cachePagesDirtyRead, searchEngineListTemplate, searchEngineFileTemplate
case searchEngineRobotsDB
case useDataStore, dataStoreClass, redirectionClass, dataStoreName, dataStoreDriver
case dataStoreURL
case dataStoreUser, dataStorePassword, dataStoreTestQuery, dataStoreLogFile, dataStoreInitConns, dataStoreMaxConns, dataStoreConnUsageLimit, dataStoreLogLevel
case maxURLLength
case mailHost, mailHostOverride, log, logLocation, logMaxSize, dataLog, dataLogLocation, dataLogMaxSize, removePageCache, removeTemplateCache, fileTransferFolder, lookInContext, adminGroupID, betaServer
}
}
struct ServletMapping: Codable, Equatable {
let cofaxCDS, cofaxEmail, cofaxAdmin, fileServlet: String
let cofaxTools: String
}
struct Taglib: Codable, Equatable {
let taglibURI, taglibLocation: String
enum CodingKeys: String, CodingKey {
case taglibURI = "taglib-uri"
case taglibLocation = "taglib-location"
}
}
}
}
extension JSONPass {
struct Test5: Codable, Equatable {
let image: Image
enum CodingKeys: String, CodingKey {
case image = "Image"
}
struct Image: Codable, Equatable {
let width, height: Int
let title: String
let thumbnail: Thumbnail
let ids: [Int]
enum CodingKeys: String, CodingKey {
case width = "Width"
case height = "Height"
case title = "Title"
case thumbnail = "Thumbnail"
case ids = "IDs"
}
}
struct Thumbnail: Codable, Equatable {
let url: String
let height: Int
let width: String
enum CodingKeys: String, CodingKey {
case url = "Url"
case height = "Height"
case width = "Width"
}
}
}
}
extension JSONPass {
typealias Test6 = [Test6Element]
struct Test6Element: Codable, Equatable {
let precision: String
let latitude, longitude: Double
let address, city, state, zip: String
let country: String
enum CodingKeys: String, CodingKey {
case precision
case latitude = "Latitude"
case longitude = "Longitude"
case address = "Address"
case city = "City"
case state = "State"
case zip = "Zip"
case country = "Country"
}
static func == (lhs: Self, rhs: Self) -> Bool {
guard lhs.precision == rhs.precision, lhs.address == rhs.address, lhs.city == rhs.city, lhs.zip == rhs.zip, lhs.country == rhs.country else {
return false
}
guard fabs(lhs.longitude - rhs.longitude) <= 1e-10 else {
return false
}
guard fabs(lhs.latitude - rhs.latitude) <= 1e-10 else {
return false
}
return true
}
}
}
extension JSONPass {
struct Test7: Codable, Equatable {
let menu: Menu
struct Menu: Codable, Equatable {
let header: String
let items: [Item]
}
struct Item: Codable, Equatable {
let id: String
let label: String?
}
}
}
extension JSONPass {
typealias Test8 = [[[[[[[[[[[[[[[[[[[String]]]]]]]]]]]]]]]]]]]
}
extension JSONPass {
struct Test9: Codable, Equatable {
let objects : [AnyHashable]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var decodedObjects = [AnyHashable]()
decodedObjects.append(try container.decode(String.self))
decodedObjects.append(try container.decode([String:[String]].self))
decodedObjects.append(try container.decode([String:String].self))
decodedObjects.append(try container.decode([String].self))
decodedObjects.append(try container.decode(Int.self))
decodedObjects.append(try container.decode(Bool.self))
decodedObjects.append(try container.decode(Bool.self))
if try container.decodeNil() {
decodedObjects.append("<null>")
}
decodedObjects.append(try container.decode(SpecialCases.self))
decodedObjects.append(try container.decode(Float.self))
decodedObjects.append(try container.decode(Float.self))
decodedObjects.append(try container.decode(Float.self))
decodedObjects.append(try container.decode(Int.self))
decodedObjects.append(try container.decode(Double.self))
decodedObjects.append(try container.decode(Double.self))
decodedObjects.append(try container.decode(Double.self))
decodedObjects.append(try container.decode(Double.self))
decodedObjects.append(try container.decode(Double.self))
decodedObjects.append(try container.decode(Double.self))
decodedObjects.append(try container.decode(String.self))
self.objects = decodedObjects
}
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(objects[ 0] as! String)
try container.encode(objects[ 1] as! [String:[String]])
try container.encode(objects[ 2] as! [String:String])
try container.encode(objects[ 3] as! [String])
try container.encode(objects[ 4] as! Int)
try container.encode(objects[ 5] as! Bool)
try container.encode(objects[ 6] as! Bool)
try container.encodeNil()
try container.encode(objects[ 8] as! SpecialCases)
try container.encode(objects[ 9] as! Float)
try container.encode(objects[10] as! Float)
try container.encode(objects[11] as! Float)
try container.encode(objects[12] as! Int)
try container.encode(objects[13] as! Double)
try container.encode(objects[14] as! Double)
try container.encode(objects[15] as! Double)
try container.encode(objects[16] as! Double)
try container.encode(objects[17] as! Double)
try container.encode(objects[18] as! Double)
try container.encode(objects[19] as! String)
}
struct SpecialCases : Codable, Hashable {
let integer : UInt64
let real : Double
let e : Double
let E : Double
let empty_key : Double
let zero : UInt8
let one : UInt8
let space : String
let quote : String
let backslash : String
let controls : String
let slash : String
let alpha : String
let ALPHA : String
let digit : String
let _0123456789 : String
let special : String
let hex: String
let `true` : Bool
let `false` : Bool
let null : Bool?
let array : [String]
let object : [String:String]
let address : String
let url : URL
let comment : String
let special_sequences_key : String
let spaced : [Int]
let compact : [Int]
let jsontext : String
let quotes : String
let escapedKey : String
enum CodingKeys: String, CodingKey {
case integer
case real
case e
case E
case empty_key = ""
case zero
case one
case space
case quote
case backslash
case controls
case slash
case alpha
case ALPHA
case digit
case _0123456789 = "0123456789"
case special
case hex
case `true`
case `false`
case null
case array
case object
case address
case url
case comment
case special_sequences_key = "# -- --> */"
case spaced = " s p a c e d "
case compact
case jsontext
case quotes
case escapedKey = "/\\\"\u{CAFE}\u{BABE}\u{AB98}\u{FCDE}\u{bcda}\u{ef4A}\u{08}\u{0C}\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"
}
}
}
}
extension JSONPass {
typealias Test10 = [String:[String:String]]
typealias Test11 = [String:String]
}
extension JSONPass {
struct Test12: Codable, Equatable {
let query: Query
struct Query: Codable, Equatable {
let pages: Pages
}
struct Pages: Codable, Equatable {
let the80348: The80348
enum CodingKeys: String, CodingKey {
case the80348 = "80348"
}
}
struct The80348: Codable, Equatable {
let pageid, ns: Int
let title: String
let langlinks: [Langlink]
}
struct Langlink: Codable, Equatable {
let lang, asterisk: String
enum CodingKeys: String, CodingKey {
case lang
case asterisk = "*"
}
}
}
}
extension JSONPass {
typealias Test13 = [String:Int]
typealias Test14 = [String:[String:[String:String]]]
}
extension JSONPass {
struct Test15: Codable, Equatable {
let attached: Bool
let klass: String
let errors: [String:[String]]
let gid: Int
let id: ID
let mpid, name: String
let properties: Properties
let state: State
let type: String
let version: Int
enum CodingKeys: String, CodingKey {
case attached
case klass = "class"
case errors, gid, id, mpid, name, properties, state, type, version
}
struct ID: Codable, Equatable {
let klass: String
let inc: Int
let machine: Int
let new: Bool
let time: UInt64
let timeSecond: UInt64
enum CodingKeys: String, CodingKey {
case klass = "class"
case inc, machine, new, time, timeSecond
}
}
class Properties: Codable, Equatable {
let mpid, type: String
let dbo: DBO?
let gid: Int
let name: String?
let state: State?
let apiTimestamp: String?
let gatewayTimestamp: String?
let eventData: [String:Float]?
static func == (lhs: Properties, rhs: Properties) -> Bool {
return lhs.mpid == rhs.mpid && lhs.type == rhs.type && lhs.dbo == rhs.dbo && lhs.gid == rhs.gid && lhs.name == rhs.name && lhs.state == rhs.state && lhs.apiTimestamp == rhs.apiTimestamp && lhs.gatewayTimestamp == rhs.gatewayTimestamp && lhs.eventData == rhs.eventData
}
}
struct DBO: Codable, Equatable {
let id: ID
let gid: Int
let mpid: String
let name: String
let type: String
let version: Int
enum CodingKeys: String, CodingKey {
case id = "_id"
case gid, mpid, name, type, version
}
}
struct State: Codable, Equatable {
let apiTimestamp: String
let attached: Bool
let klass : String
let errors: [String:[String]]
let eventData: [String:Float]
let gatewayTimestamp: String
let gid: Int
let id: ID
let mpid: String
let properties: Properties
let type: String
let version: Int?
enum CodingKeys: String, CodingKey {
case apiTimestamp, attached
case klass = "class"
case errors, eventData, gatewayTimestamp, gid, id, mpid, properties, type, version
}
}
}
}
enum JSONFail {
typealias Test1 = String
typealias Test2 = [String]
typealias Test3 = [String:String]
typealias Test4 = [String]
typealias Test5 = [String]
typealias Test6 = [String]
typealias Test7 = [String]
typealias Test8 = [String]
typealias Test9 = [String]
typealias Test10 = [String:Bool]
typealias Test11 = [String:Int]
typealias Test12 = [String:String]
typealias Test13 = [String:Int]
typealias Test14 = [String:Int]
typealias Test15 = [String]
typealias Test16 = [String]
typealias Test17 = [String]
typealias Test18 = [String]
typealias Test19 = [String:String?]
typealias Test21 = [String:String?]
typealias Test22 = [String]
typealias Test23 = [String]
typealias Test24 = [String]
typealias Test25 = [String]
typealias Test26 = [String]
typealias Test27 = [String]
typealias Test28 = [String]
typealias Test29 = [Float]
typealias Test30 = [Float]
typealias Test31 = [Float]
typealias Test32 = [String:Bool]
typealias Test33 = [String]
typealias Test34 = [String]
typealias Test35 = [String:String]
typealias Test36 = [String:Int]
typealias Test37 = [String:Int]
typealias Test38 = [String:Float]
typealias Test39 = [String:String]
typealias Test40 = [String:String]
typealias Test41 = [String:String]
}
enum JSON5Pass { }
extension JSON5Pass {
struct Example : Codable, Equatable {
let unquoted: String
let singleQuotes: String
let lineBreaks: String
let hexadecimal: UInt
let leadingDecimalPoint: Double
let andTrailing: Double
let positiveSign: Int
let trailingComma: String
let andIn: [String]
let backwardsCompatible: String
}
}
extension JSON5Pass {
struct Hex : Codable, Equatable {
let `in`: [Int]
let out: [Int]
}
}
extension JSON5Pass {
struct Numbers : Codable, Equatable {
let a: Double
let b: Double
let c: Double
let d: Int
}
}
extension JSON5Pass {
struct Strings : Codable, Equatable {
let Hello: String
let Hello2: String
let Hello3: String
let hex1: String
let hex2: String
}
}
extension JSON5Pass {
struct Whitespace : Codable, Equatable {
let Hello: String
}
}
enum JSON5Spec { }
extension JSON5Spec {
struct NPMPackage: Codable {
let name: String
let publishConfig: PublishConfig
let `description`: String
let keywords: [String]
let version: String
let preferGlobal: Bool
let config: Config
let homepage: String
let author: String
let repository: Repository
let bugs: Bugs
let directories: [String:String]
let main, bin: String
let dependencies: [String:String]
let bundleDependencies: [String]
let devDependencies: [String:String]
let engines: [String:String]
let scripts: [String:String]
let licenses: [License]
struct PublishConfig: Codable {
let proprietaryAttribs: Bool
enum CodingKeys: String, CodingKey {
case proprietaryAttribs = "proprietary-attribs"
}
}
struct Config: Codable {
let publishtest: Bool
}
struct Repository: Codable {
let type: String
let url: String
}
struct Bugs: Codable {
let email: String
let url: String
}
struct License: Codable {
let type: String
let url: String
}
}
}
extension JSON5Spec {
struct ReadmeExample: Codable {
let foo: String
let `while`: Bool
let this: String
let here: String
let hex: UInt
let half: Double
let delta: Int
let to: Double
let finally: String
let oh: [String]
}
}
|