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 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320 18321 18322 18323 18324 18325 18326 18327 18328 18329 18330 18331 18332 18333 18334 18335 18336 18337 18338 18339 18340 18341 18342 18343 18344 18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362 18363 18364 18365 18366 18367 18368 18369 18370 18371 18372 18373 18374 18375 18376 18377 18378 18379 18380 18381 18382 18383 18384 18385 18386 18387 18388 18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400 18401 18402 18403 18404 18405 18406 18407 18408 18409 18410 18411 18412 18413 18414 18415 18416 18417 18418 18419 18420 18421 18422 18423 18424 18425 18426 18427 18428 18429 18430 18431 18432 18433 18434 18435 18436 18437 18438 18439 18440 18441 18442 18443 18444 18445 18446 18447 18448 18449 18450 18451 18452 18453 18454 18455 18456 18457 18458 18459 18460 18461 18462 18463 18464 18465 18466 18467 18468 18469 18470 18471 18472 18473 18474 18475 18476 18477 18478 18479 18480 18481 18482 18483 18484 18485 18486 18487 18488 18489 18490 18491 18492 18493 18494 18495 18496 18497 18498 18499 18500 18501 18502 18503 18504 18505 18506 18507 18508 18509 18510 18511 18512 18513 18514 18515 18516 18517 18518 18519 18520 18521 18522 18523 18524 18525 18526 18527 18528 18529 18530 18531 18532 18533 18534 18535 18536 18537 18538 18539 18540 18541 18542 18543 18544 18545 18546 18547 18548 18549 18550 18551 18552 18553 18554 18555 18556 18557 18558 18559 18560 18561 18562 18563 18564 18565 18566 18567 18568 18569 18570 18571 18572 18573 18574 18575 18576 18577 18578 18579 18580 18581 18582 18583 18584 18585 18586 18587 18588 18589 18590 18591 18592 18593 18594 18595 18596 18597 18598 18599 18600 18601 18602 18603 18604 18605 18606 18607 18608 18609 18610 18611 18612 18613 18614 18615 18616 18617 18618 18619 18620 18621 18622 18623 18624 18625 18626 18627 18628 18629 18630 18631 18632 18633 18634 18635 18636 18637 18638 18639 18640 18641 18642 18643 18644 18645 18646 18647 18648 18649 18650 18651 18652 18653 18654 18655 18656 18657 18658 18659 18660 18661 18662 18663 18664 18665 18666 18667 18668 18669 18670 18671 18672 18673 18674 18675 18676 18677 18678 18679 18680 18681 18682 18683 18684 18685 18686 18687 18688 18689 18690 18691 18692 18693 18694 18695 18696 18697 18698 18699 18700 18701 18702 18703 18704 18705 18706 18707 18708 18709 18710 18711 18712 18713 18714 18715 18716 18717 18718 18719 18720 18721 18722 18723 18724 18725 18726 18727 18728 18729 18730 18731 18732 18733 18734 18735 18736 18737 18738 18739 18740 18741 18742 18743 18744 18745 18746 18747 18748 18749 18750 18751 18752 18753 18754 18755 18756 18757 18758 18759 18760 18761 18762 18763 18764 18765 18766 18767 18768 18769 18770 18771 18772 18773 18774 18775 18776 18777 18778 18779 18780 18781 18782 18783 18784 18785 18786 18787 18788 18789 18790 18791 18792 18793 18794 18795 18796 18797 18798 18799 18800 18801 18802 18803 18804 18805 18806 18807 18808 18809 18810 18811 18812 18813 18814 18815 18816 18817 18818 18819 18820 18821 18822 18823 18824 18825 18826 18827 18828 18829 18830 18831 18832 18833 18834 18835 18836 18837 18838 18839 18840 18841 18842 18843 18844 18845 18846 18847 18848 18849 18850 18851 18852 18853 18854 18855 18856 18857 18858 18859 18860 18861 18862 18863 18864 18865 18866 18867 18868 18869 18870 18871 18872 18873 18874 18875 18876 18877 18878 18879 18880 18881 18882 18883 18884 18885 18886 18887 18888 18889 18890 18891 18892 18893 18894 18895 18896 18897 18898 18899 18900 18901 18902 18903 18904 18905 18906 18907 18908 18909 18910 18911 18912 18913 18914 18915 18916 18917 18918 18919 18920 18921 18922 18923 18924 18925 18926 18927 18928 18929 18930 18931 18932 18933 18934 18935 18936 18937 18938 18939 18940 18941 18942 18943 18944 18945 18946 18947 18948 18949 18950 18951 18952 18953 18954 18955 18956 18957 18958 18959 18960 18961 18962 18963 18964 18965 18966 18967 18968 18969 18970 18971 18972 18973 18974 18975 18976 18977 18978 18979 18980 18981 18982 18983 18984 18985 18986 18987 18988 18989 18990 18991 18992 18993 18994 18995 18996 18997 18998 18999 19000 19001 19002 19003 19004 19005 19006 19007 19008 19009 19010 19011 19012 19013 19014 19015 19016 19017 19018 19019 19020 19021 19022 19023 19024 19025 19026 19027 19028 19029 19030 19031 19032 19033 19034 19035 19036 19037 19038 19039 19040 19041 19042 19043 19044 19045 19046 19047 19048 19049 19050 19051 19052 19053 19054 19055 19056 19057 19058 19059 19060 19061 19062 19063 19064 19065 19066 19067 19068 19069 19070 19071 19072 19073 19074 19075 19076 19077 19078 19079 19080 19081 19082 19083 19084 19085 19086 19087 19088 19089 19090 19091 19092 19093 19094 19095 19096 19097 19098 19099 19100 19101 19102 19103 19104 19105 19106 19107 19108 19109 19110 19111 19112 19113 19114 19115 19116 19117 19118 19119 19120 19121 19122 19123 19124 19125 19126 19127 19128 19129 19130 19131 19132 19133 19134 19135 19136 19137 19138 19139 19140 19141 19142 19143 19144 19145 19146 19147 19148 19149 19150 19151 19152 19153 19154 19155 19156 19157 19158 19159 19160 19161 19162 19163 19164 19165 19166 19167 19168 19169 19170 19171 19172 19173 19174 19175 19176 19177 19178 19179 19180 19181 19182 19183 19184 19185 19186 19187 19188 19189 19190 19191 19192 19193 19194 19195 19196 19197 19198 19199 19200 19201 19202 19203 19204 19205 19206 19207 19208 19209 19210 19211 19212 19213 19214 19215 19216 19217 19218 19219 19220 19221 19222 19223 19224 19225 19226 19227 19228 19229 19230 19231 19232 19233 19234 19235 19236 19237 19238 19239 19240 19241 19242 19243 19244 19245 19246 19247 19248 19249 19250 19251 19252 19253 19254 19255 19256 19257 19258 19259 19260 19261 19262 19263 19264 19265 19266 19267 19268 19269 19270 19271 19272 19273 19274 19275 19276 19277 19278 19279 19280 19281 19282 19283 19284 19285 19286 19287 19288 19289 19290 19291 19292 19293 19294 19295 19296 19297 19298 19299 19300 19301 19302 19303 19304 19305 19306 19307 19308 19309 19310 19311 19312 19313 19314 19315 19316 19317 19318 19319 19320 19321 19322 19323 19324 19325 19326 19327 19328 19329 19330 19331 19332 19333 19334 19335 19336 19337 19338 19339 19340 19341 19342 19343 19344 19345 19346 19347 19348 19349 19350 19351 19352 19353 19354 19355 19356 19357 19358 19359 19360 19361 19362 19363 19364 19365 19366 19367 19368 19369 19370 19371 19372 19373 19374 19375 19376 19377 19378 19379 19380 19381 19382 19383 19384 19385 19386 19387 19388 19389 19390 19391 19392 19393 19394 19395 19396 19397 19398 19399 19400 19401 19402 19403 19404 19405 19406 19407 19408 19409 19410 19411 19412 19413 19414 19415 19416 19417 19418 19419 19420 19421 19422 19423 19424 19425 19426 19427 19428 19429 19430 19431 19432 19433 19434 19435 19436 19437 19438 19439 19440 19441 19442 19443 19444 19445 19446 19447 19448 19449 19450 19451 19452 19453 19454 19455 19456 19457 19458 19459 19460 19461 19462 19463 19464 19465 19466 19467 19468 19469 19470 19471 19472 19473 19474 19475 19476 19477 19478 19479 19480 19481 19482 19483 19484 19485 19486 19487 19488 19489 19490 19491 19492 19493 19494 19495 19496 19497 19498 19499 19500 19501 19502 19503 19504 19505 19506 19507 19508 19509 19510 19511 19512 19513 19514 19515 19516 19517 19518 19519 19520 19521 19522 19523 19524 19525 19526 19527 19528 19529 19530 19531 19532 19533 19534 19535 19536 19537 19538 19539 19540 19541 19542 19543 19544 19545 19546 19547 19548 19549 19550 19551 19552 19553 19554 19555 19556 19557 19558 19559 19560 19561 19562 19563 19564 19565 19566 19567 19568 19569 19570 19571 19572 19573 19574 19575 19576 19577 19578 19579 19580 19581 19582 19583 19584 19585 19586 19587 19588 19589 19590 19591 19592 19593 19594 19595 19596 19597 19598 19599 19600 19601 19602 19603 19604 19605 19606 19607 19608 19609 19610 19611 19612 19613 19614 19615 19616 19617 19618 19619 19620 19621 19622 19623 19624 19625 19626 19627 19628 19629 19630 19631 19632 19633 19634 19635 19636 19637 19638 19639 19640 19641 19642 19643 19644 19645 19646 19647 19648 19649 19650 19651 19652 19653 19654 19655 19656 19657 19658 19659 19660 19661 19662 19663 19664 19665 19666 19667 19668 19669 19670 19671 19672 19673 19674 19675 19676 19677 19678 19679 19680 19681 19682 19683 19684 19685 19686 19687 19688 19689 19690 19691 19692 19693 19694 19695 19696 19697 19698 19699 19700 19701 19702 19703 19704 19705 19706 19707 19708 19709 19710 19711 19712 19713 19714 19715 19716 19717 19718 19719 19720 19721 19722 19723 19724 19725 19726 19727 19728 19729 19730 19731 19732 19733 19734 19735 19736 19737 19738 19739 19740 19741 19742 19743 19744 19745 19746 19747 19748 19749 19750 19751 19752 19753 19754 19755 19756 19757 19758 19759 19760 19761 19762 19763 19764 19765 19766 19767 19768 19769 19770 19771 19772 19773 19774 19775 19776 19777 19778 19779 19780 19781 19782 19783 19784 19785 19786 19787 19788 19789 19790 19791 19792 19793 19794 19795 19796 19797 19798 19799 19800 19801 19802 19803 19804 19805 19806 19807 19808 19809 19810 19811 19812 19813 19814 19815 19816 19817 19818 19819 19820 19821 19822 19823 19824 19825 19826 19827 19828 19829 19830 19831 19832 19833 19834 19835 19836 19837 19838 19839 19840 19841 19842 19843 19844 19845 19846 19847 19848 19849 19850 19851 19852 19853 19854 19855 19856 19857 19858 19859 19860 19861 19862 19863 19864 19865 19866 19867 19868 19869 19870 19871 19872 19873 19874 19875 19876 19877 19878 19879 19880 19881 19882 19883 19884 19885 19886 19887 19888 19889 19890 19891 19892 19893 19894 19895 19896 19897 19898 19899 19900 19901 19902 19903 19904 19905 19906 19907 19908 19909 19910 19911 19912 19913 19914 19915 19916 19917 19918 19919 19920 19921 19922 19923 19924 19925 19926 19927 19928 19929 19930 19931 19932 19933 19934 19935 19936 19937 19938 19939 19940 19941 19942 19943 19944 19945 19946 19947 19948 19949 19950 19951 19952 19953 19954 19955 19956 19957 19958 19959 19960 19961 19962 19963 19964 19965 19966 19967 19968 19969 19970 19971 19972 19973 19974 19975 19976 19977 19978 19979 19980 19981 19982 19983 19984 19985 19986 19987 19988 19989 19990 19991 19992 19993 19994 19995 19996 19997 19998 19999 20000 20001 20002 20003 20004 20005 20006 20007 20008 20009 20010 20011 20012 20013 20014 20015 20016 20017 20018 20019 20020 20021 20022 20023 20024 20025 20026 20027 20028 20029 20030 20031 20032 20033 20034 20035 20036 20037 20038 20039 20040 20041 20042 20043 20044 20045 20046 20047 20048 20049 20050 20051 20052 20053 20054 20055 20056 20057 20058 20059 20060 20061 20062 20063 20064 20065 20066 20067 20068 20069 20070 20071 20072 20073 20074 20075 20076 20077 20078 20079 20080 20081 20082 20083 20084 20085 20086 20087 20088 20089 20090 20091 20092 20093 20094 20095 20096 20097 20098 20099 20100 20101 20102 20103 20104 20105 20106 20107 20108 20109 20110 20111 20112 20113 20114 20115 20116 20117 20118 20119 20120 20121 20122 20123 20124 20125 20126 20127 20128 20129 20130 20131 20132 20133 20134 20135 20136 20137 20138 20139 20140 20141 20142 20143 20144 20145 20146 20147 20148 20149 20150 20151 20152 20153 20154 20155 20156 20157 20158 20159 20160 20161 20162 20163 20164 20165 20166 20167 20168 20169 20170 20171 20172 20173 20174 20175 20176 20177 20178 20179 20180 20181 20182 20183 20184 20185 20186 20187 20188 20189 20190 20191 20192 20193 20194 20195 20196 20197 20198 20199 20200 20201 20202 20203 20204 20205 20206 20207 20208 20209 20210 20211 20212 20213 20214 20215 20216 20217 20218 20219 20220 20221 20222 20223 20224 20225 20226 20227 20228 20229 20230 20231 20232 20233 20234 20235 20236 20237 20238 20239 20240 20241 20242 20243 20244 20245 20246 20247 20248 20249 20250 20251 20252 20253 20254 20255 20256 20257 20258 20259 20260 20261 20262 20263 20264 20265 20266 20267 20268 20269 20270 20271 20272 20273 20274 20275 20276 20277 20278 20279 20280 20281 20282 20283 20284 20285 20286 20287 20288 20289 20290 20291 20292 20293 20294 20295 20296 20297 20298 20299 20300 20301 20302 20303 20304 20305 20306 20307 20308 20309 20310 20311 20312 20313 20314 20315 20316 20317 20318 20319 20320 20321 20322 20323 20324 20325 20326 20327 20328 20329 20330 20331 20332 20333 20334 20335 20336 20337 20338 20339 20340 20341 20342 20343 20344 20345 20346 20347 20348 20349 20350 20351 20352 20353 20354 20355 20356 20357 20358 20359 20360 20361 20362 20363 20364 20365 20366 20367 20368 20369 20370 20371 20372 20373 20374 20375 20376 20377 20378 20379 20380 20381 20382 20383 20384 20385 20386 20387 20388 20389 20390 20391 20392 20393 20394 20395 20396 20397 20398 20399 20400 20401 20402 20403 20404 20405 20406 20407 20408 20409 20410 20411 20412 20413 20414 20415 20416 20417 20418 20419 20420 20421 20422 20423 20424 20425 20426 20427 20428 20429 20430 20431 20432 20433 20434 20435 20436 20437 20438 20439 20440 20441 20442 20443 20444 20445 20446 20447 20448 20449 20450 20451 20452 20453 20454 20455 20456 20457 20458 20459 20460 20461 20462 20463 20464 20465 20466 20467 20468 20469 20470 20471 20472 20473 20474 20475 20476 20477 20478 20479 20480 20481 20482 20483 20484 20485 20486 20487 20488 20489 20490 20491 20492 20493 20494 20495 20496 20497 20498 20499 20500 20501 20502 20503 20504 20505 20506 20507 20508 20509 20510 20511 20512 20513 20514 20515 20516 20517 20518 20519 20520 20521 20522 20523 20524 20525 20526 20527 20528 20529 20530 20531 20532 20533 20534 20535 20536 20537 20538 20539 20540 20541 20542 20543 20544 20545 20546 20547 20548 20549 20550 20551 20552 20553 20554 20555 20556 20557 20558 20559 20560 20561 20562 20563 20564 20565 20566 20567 20568 20569 20570 20571 20572 20573 20574 20575 20576 20577 20578 20579 20580 20581 20582 20583 20584 20585 20586 20587 20588 20589 20590 20591 20592 20593 20594 20595 20596 20597 20598 20599 20600 20601 20602 20603 20604 20605 20606 20607 20608 20609 20610 20611 20612 20613 20614 20615 20616 20617 20618 20619 20620 20621 20622 20623 20624 20625 20626 20627 20628 20629 20630 20631 20632 20633 20634 20635 20636 20637 20638 20639 20640 20641 20642 20643 20644 20645 20646 20647 20648 20649 20650 20651 20652 20653 20654 20655 20656 20657 20658 20659 20660 20661 20662 20663 20664 20665 20666 20667 20668 20669 20670 20671 20672 20673 20674 20675 20676 20677 20678 20679 20680 20681 20682 20683 20684 20685 20686 20687 20688 20689 20690 20691 20692 20693 20694 20695 20696 20697 20698 20699 20700 20701 20702 20703 20704 20705 20706 20707 20708 20709 20710 20711 20712 20713 20714 20715 20716 20717 20718 20719 20720 20721 20722 20723 20724 20725 20726 20727 20728 20729 20730 20731 20732 20733 20734 20735 20736 20737 20738 20739 20740 20741 20742 20743 20744 20745 20746 20747 20748 20749 20750 20751 20752 20753 20754 20755 20756 20757 20758 20759 20760 20761 20762 20763 20764 20765 20766 20767 20768 20769 20770 20771 20772 20773 20774 20775 20776 20777 20778 20779 20780 20781 20782 20783 20784 20785 20786 20787 20788 20789 20790 20791 20792 20793 20794 20795 20796 20797 20798 20799 20800 20801 20802 20803 20804 20805 20806 20807 20808 20809 20810 20811 20812 20813 20814 20815 20816 20817 20818 20819 20820 20821 20822 20823 20824 20825 20826 20827 20828 20829 20830 20831 20832 20833 20834 20835 20836 20837 20838 20839 20840 20841 20842 20843 20844 20845 20846 20847 20848 20849 20850 20851 20852 20853 20854 20855 20856 20857 20858 20859 20860 20861 20862 20863 20864 20865 20866 20867 20868 20869 20870 20871 20872 20873 20874 20875 20876 20877 20878 20879 20880 20881 20882 20883 20884 20885 20886 20887 20888 20889 20890 20891 20892 20893 20894 20895 20896 20897 20898 20899 20900 20901 20902 20903 20904 20905 20906 20907 20908 20909 20910 20911 20912 20913 20914 20915 20916 20917 20918 20919 20920 20921 20922 20923 20924 20925 20926 20927 20928 20929 20930 20931 20932 20933 20934 20935 20936 20937 20938 20939 20940 20941 20942 20943 20944 20945 20946 20947 20948 20949 20950 20951 20952 20953 20954 20955 20956 20957 20958 20959 20960 20961 20962 20963 20964 20965 20966 20967 20968 20969 20970 20971 20972 20973 20974 20975 20976 20977 20978 20979 20980 20981 20982 20983 20984 20985 20986 20987 20988 20989 20990 20991 20992 20993 20994 20995 20996 20997 20998 20999 21000 21001 21002 21003 21004 21005 21006 21007 21008 21009 21010 21011 21012 21013 21014 21015 21016 21017 21018 21019 21020 21021 21022 21023 21024 21025 21026 21027 21028 21029 21030 21031 21032 21033 21034 21035 21036 21037 21038 21039 21040 21041 21042 21043 21044 21045 21046 21047 21048 21049 21050 21051 21052 21053 21054 21055 21056 21057 21058 21059 21060 21061 21062 21063 21064 21065 21066 21067 21068 21069 21070 21071 21072 21073 21074 21075 21076 21077 21078 21079 21080 21081 21082 21083 21084 21085 21086 21087 21088 21089 21090 21091 21092 21093 21094 21095 21096 21097 21098 21099 21100 21101 21102 21103 21104 21105 21106 21107 21108 21109 21110 21111 21112 21113 21114 21115 21116 21117 21118 21119 21120 21121 21122 21123 21124 21125 21126 21127 21128 21129 21130 21131 21132 21133 21134 21135 21136 21137 21138 21139 21140 21141 21142 21143 21144 21145 21146 21147 21148 21149 21150 21151 21152 21153 21154 21155 21156 21157 21158 21159 21160 21161 21162 21163 21164 21165 21166 21167 21168 21169 21170 21171 21172 21173 21174 21175 21176 21177 21178 21179 21180 21181 21182 21183 21184 21185 21186 21187 21188 21189 21190 21191 21192 21193 21194 21195 21196 21197 21198 21199 21200 21201 21202 21203 21204 21205 21206 21207 21208 21209 21210 21211 21212 21213 21214 21215 21216 21217 21218 21219 21220 21221 21222 21223 21224 21225 21226 21227 21228 21229 21230 21231 21232 21233 21234 21235 21236 21237 21238 21239 21240 21241 21242 21243 21244 21245 21246 21247 21248 21249 21250 21251 21252 21253 21254 21255 21256 21257 21258 21259 21260 21261 21262 21263 21264 21265 21266 21267 21268 21269 21270 21271 21272 21273 21274 21275 21276 21277 21278 21279 21280 21281 21282 21283 21284 21285 21286 21287 21288 21289 21290 21291 21292 21293 21294 21295 21296 21297 21298 21299 21300 21301 21302 21303 21304 21305 21306 21307 21308 21309 21310 21311 21312 21313 21314 21315 21316 21317 21318 21319 21320 21321 21322 21323 21324 21325 21326 21327 21328 21329 21330 21331 21332 21333 21334 21335 21336 21337 21338 21339 21340 21341 21342 21343 21344 21345 21346 21347 21348 21349 21350 21351 21352 21353 21354 21355 21356 21357 21358 21359 21360 21361 21362 21363 21364 21365 21366 21367 21368 21369 21370 21371 21372 21373 21374 21375 21376 21377 21378 21379 21380 21381 21382 21383 21384 21385 21386 21387 21388 21389 21390 21391 21392 21393 21394 21395 21396 21397 21398 21399 21400 21401 21402 21403 21404 21405 21406 21407 21408 21409 21410 21411 21412 21413 21414 21415 21416 21417 21418 21419 21420 21421 21422 21423 21424 21425 21426 21427 21428 21429 21430 21431 21432 21433 21434 21435 21436 21437 21438 21439 21440 21441 21442 21443 21444 21445 21446 21447 21448 21449 21450 21451 21452 21453 21454 21455 21456 21457 21458 21459 21460 21461 21462 21463 21464 21465 21466 21467 21468 21469 21470 21471 21472 21473 21474 21475 21476 21477 21478 21479 21480 21481 21482 21483 21484 21485 21486 21487 21488 21489 21490 21491 21492 21493 21494 21495 21496 21497 21498 21499 21500 21501 21502 21503 21504 21505 21506 21507 21508 21509 21510 21511 21512 21513 21514 21515 21516 21517 21518 21519 21520 21521 21522 21523 21524 21525 21526 21527 21528 21529 21530 21531 21532 21533 21534 21535 21536 21537 21538 21539 21540 21541 21542 21543 21544 21545 21546 21547 21548 21549 21550 21551 21552 21553 21554 21555 21556 21557 21558 21559 21560 21561 21562 21563 21564 21565 21566 21567 21568 21569 21570 21571 21572 21573 21574 21575 21576 21577 21578 21579 21580 21581 21582 21583 21584 21585 21586 21587 21588 21589 21590 21591 21592 21593 21594 21595 21596 21597 21598 21599 21600 21601 21602 21603 21604 21605 21606 21607 21608 21609 21610 21611 21612 21613 21614 21615 21616 21617 21618 21619 21620 21621 21622 21623 21624 21625 21626 21627 21628 21629 21630 21631 21632 21633 21634 21635 21636 21637 21638 21639 21640 21641 21642 21643 21644 21645 21646 21647 21648 21649 21650 21651 21652 21653 21654 21655 21656 21657 21658 21659 21660 21661 21662 21663 21664 21665 21666 21667 21668 21669 21670 21671 21672 21673 21674 21675 21676 21677 21678 21679 21680 21681 21682 21683 21684 21685 21686 21687 21688 21689 21690 21691 21692 21693 21694 21695 21696 21697 21698 21699 21700 21701 21702 21703 21704 21705 21706 21707 21708 21709 21710 21711 21712 21713 21714 21715 21716 21717 21718 21719 21720 21721 21722 21723 21724 21725 21726 21727 21728 21729 21730 21731 21732 21733 21734 21735 21736 21737 21738 21739 21740 21741 21742 21743 21744 21745 21746 21747 21748 21749 21750 21751 21752 21753 21754 21755 21756 21757 21758 21759 21760 21761 21762 21763 21764 21765 21766 21767 21768 21769 21770 21771 21772 21773 21774 21775 21776 21777 21778 21779 21780 21781 21782 21783 21784 21785 21786 21787 21788 21789 21790 21791 21792 21793 21794 21795 21796 21797 21798 21799 21800 21801 21802 21803 21804 21805 21806 21807 21808 21809 21810 21811 21812 21813 21814 21815 21816 21817 21818 21819 21820 21821 21822 21823 21824 21825 21826 21827 21828 21829 21830 21831 21832 21833 21834 21835 21836 21837 21838 21839 21840 21841 21842 21843 21844 21845 21846 21847 21848 21849 21850 21851 21852 21853 21854 21855 21856 21857 21858 21859 21860 21861 21862 21863 21864 21865 21866 21867 21868 21869 21870 21871 21872 21873 21874 21875 21876 21877 21878 21879 21880 21881 21882 21883 21884 21885 21886 21887 21888 21889 21890 21891 21892 21893 21894 21895 21896 21897 21898 21899 21900 21901 21902 21903 21904 21905 21906 21907 21908 21909 21910 21911 21912 21913 21914 21915 21916 21917 21918 21919 21920 21921 21922 21923 21924 21925 21926 21927 21928 21929 21930 21931 21932 21933 21934 21935 21936 21937 21938 21939 21940 21941 21942 21943 21944 21945 21946 21947 21948 21949 21950 21951 21952 21953 21954 21955 21956 21957 21958 21959 21960 21961 21962 21963 21964 21965 21966 21967 21968 21969 21970 21971 21972 21973 21974 21975 21976 21977 21978 21979 21980 21981 21982 21983 21984 21985 21986 21987 21988 21989 21990 21991 21992 21993 21994 21995 21996 21997 21998 21999 22000 22001 22002 22003 22004 22005 22006 22007 22008 22009 22010 22011 22012 22013 22014 22015 22016 22017 22018 22019 22020 22021 22022 22023 22024 22025 22026 22027 22028 22029 22030 22031 22032 22033 22034 22035 22036 22037 22038 22039 22040 22041 22042 22043 22044 22045 22046 22047 22048 22049 22050 22051 22052 22053 22054 22055 22056 22057 22058 22059 22060 22061 22062 22063 22064 22065 22066 22067 22068 22069 22070 22071 22072 22073 22074 22075 22076 22077 22078 22079 22080 22081 22082 22083 22084 22085 22086 22087 22088 22089 22090 22091 22092 22093 22094 22095 22096 22097 22098 22099 22100 22101 22102 22103 22104 22105 22106 22107 22108 22109 22110 22111 22112 22113 22114 22115 22116 22117 22118 22119 22120 22121 22122 22123 22124 22125 22126 22127 22128 22129 22130 22131 22132 22133 22134 22135 22136 22137 22138 22139 22140 22141 22142 22143 22144 22145 22146 22147 22148 22149 22150 22151 22152 22153 22154 22155 22156 22157 22158 22159 22160 22161 22162 22163 22164 22165 22166 22167 22168 22169 22170 22171 22172 22173 22174 22175 22176 22177 22178 22179 22180 22181 22182 22183 22184 22185 22186 22187 22188 22189 22190 22191 22192 22193 22194 22195 22196 22197 22198 22199 22200 22201 22202 22203 22204 22205 22206 22207 22208 22209 22210 22211 22212 22213 22214 22215 22216 22217 22218 22219 22220 22221 22222 22223 22224 22225 22226 22227 22228 22229 22230 22231 22232 22233 22234 22235 22236 22237 22238 22239 22240 22241 22242 22243 22244 22245 22246 22247 22248 22249 22250 22251 22252 22253 22254 22255 22256 22257 22258 22259 22260 22261 22262 22263 22264 22265 22266 22267 22268 22269 22270 22271 22272 22273
|
#include <math.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdbool.h>
#include <limits.h>
#include <float.h>
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "datetime.h"
#include "structmember.h"
#include "common.h"
#include "itoa.h"
#include "ryu.h"
#include "atof.h"
/* Python version checks */
#define PY310_PLUS (PY_VERSION_HEX >= 0x030a0000)
#define PY311_PLUS (PY_VERSION_HEX >= 0x030b0000)
#define PY312_PLUS (PY_VERSION_HEX >= 0x030c0000)
#define PY313_PLUS (PY_VERSION_HEX >= 0x030d0000)
#define PY314_PLUS (PY_VERSION_HEX >= 0x030e0000)
/* Hint to the compiler not to store `x` in a register since it is likely to
* change. Results in much higher performance on GCC, with smaller benefits on
* clang */
#if defined(__GNUC__)
#define OPT_FORCE_RELOAD(x) __asm volatile("":"=m"(x)::);
#else
#define OPT_FORCE_RELOAD(x)
#endif
#ifdef __GNUC__
#define ms_popcount(i) __builtin_popcountll(i)
#else
static int
ms_popcount(uint64_t i) { \
i = i - ((i >> 1) & 0x5555555555555555); // pairs
i = (i & 0x3333333333333333) + ((i >> 2) & 0x3333333333333333); // quads
i = (i + (i >> 4)) & 0x0F0F0F0F0F0F0F0F; // groups of 8
return (uint64_t)(i * 0x0101010101010101) >> 56; // sum bytes
}
#endif
/* In Python 3.12+, tp_dict is NULL for some core types, PyType_GetDict returns
* a borrowed reference to the interpreter or cls mapping */
#if PY312_PLUS
#define MS_GET_TYPE_DICT(a) PyType_GetDict(a)
#else
#define MS_GET_TYPE_DICT(a) ((a)->tp_dict)
#endif
#if PY313_PLUS
#define MS_UNICODE_EQ(a, b) (PyUnicode_Compare(a, b) == 0)
#else
#define MS_UNICODE_EQ(a, b) _PyUnicode_EQ(a, b)
#endif
#if PY314_PLUS
#define MS_IMMORTAL_INITIAL_REFCNT _Py_IMMORTAL_INITIAL_REFCNT
#else
#define MS_IMMORTAL_INITIAL_REFCNT _Py_IMMORTAL_REFCNT
#endif
#define DIV_ROUND_CLOSEST(n, d) ((((n) < 0) == ((d) < 0)) ? (((n) + (d)/2)/(d)) : (((n) - (d)/2)/(d)))
/* These macros are used to manually unroll some loops */
#define repeat8(x) { x(0) x(1) x(2) x(3) x(4) x(5) x(6) x(7) }
#define is_digit(c) (c >= '0' && c <= '9')
/* Easy access to NoneType object */
#define NONE_TYPE ((PyObject *)(Py_TYPE(Py_None)))
/* Capacity of a list */
#define LIST_CAPACITY(x) (((PyListObject *)x)->allocated)
/* Get the raw items pointer for a list and tuple */
#define LIST_ITEMS(x) (((PyListObject *)(x))->ob_item)
#define TUPLE_ITEMS(x) (((PyTupleObject *)(x))->ob_item)
/* Fast shrink of bytes & bytearray objects. This doesn't do any memory
* allocations, it just shrinks the size of the view presented to Python. Since
* outputs of `encode` should be short lived (immediately written to a
* socket/file then dropped), this shouldn't result in increased application
* memory usage. */
# define FAST_BYTES_SHRINK(obj, size) \
do { \
Py_SET_SIZE(obj, size); \
PyBytes_AS_STRING(obj)[size] = '\0'; \
} while (0);
# define FAST_BYTEARRAY_SHRINK(obj, size) \
do { \
Py_SET_SIZE(obj, size); \
PyByteArray_AS_STRING(obj)[size] = '\0'; \
} while (0);
/* XXX: Optimized `PyUnicode_AsUTF8AndSize` for strs that we know have
* a cached unicode representation. */
static inline const char *
unicode_str_and_size_nocheck(PyObject *str, Py_ssize_t *size) {
if (MS_LIKELY(PyUnicode_IS_COMPACT_ASCII(str))) {
*size = ((PyASCIIObject *)str)->length;
return (char *)(((PyASCIIObject *)str) + 1);
}
*size = ((PyCompactUnicodeObject *)str)->utf8_length;
return ((PyCompactUnicodeObject *)str)->utf8;
}
/* XXX: Optimized `PyUnicode_AsUTF8AndSize` */
static inline const char *
unicode_str_and_size(PyObject *str, Py_ssize_t *size) {
const char *out = unicode_str_and_size_nocheck(str, size);
if (MS_LIKELY(out != NULL)) return out;
return PyUnicode_AsUTF8AndSize(str, size);
}
static MS_INLINE char *
ascii_get_buffer(PyObject *str) {
return (char *)(((PyASCIIObject *)str) + 1);
}
/* Fill in view.buf & view.len from either a Unicode or buffer-compatible
* object. */
static int
ms_get_buffer(PyObject *obj, Py_buffer *view) {
if (MS_UNLIKELY(PyUnicode_CheckExact(obj))) {
view->buf = (void *)unicode_str_and_size(obj, &(view->len));
if (view->buf == NULL) return -1;
Py_INCREF(obj);
view->obj = obj;
return 0;
}
return PyObject_GetBuffer(obj, view, PyBUF_CONTIG_RO);
}
static void
ms_release_buffer(Py_buffer *view) {
if (MS_LIKELY(!PyUnicode_CheckExact(view->obj))) {
PyBuffer_Release(view);
}
else {
Py_CLEAR(view->obj);
}
}
/* Hash algorithm borrowed from cpython 3.10's hashing algorithm for tuples.
* See https://github.com/python/cpython/blob/4bcef2bb48b3fd82011a89c1c716421b789f1442/Objects/tupleobject.c#L386-L424
*/
#if SIZEOF_PY_UHASH_T > 4
#define MS_HASH_XXPRIME_1 ((Py_uhash_t)11400714785074694791ULL)
#define MS_HASH_XXPRIME_2 ((Py_uhash_t)14029467366897019727ULL)
#define MS_HASH_XXPRIME_5 ((Py_uhash_t)2870177450012600261ULL)
#define MS_HASH_XXROTATE(x) ((x << 31) | (x >> 33)) /* Rotate left 31 bits */
#else
#define MS_HASH_XXPRIME_1 ((Py_uhash_t)2654435761UL)
#define MS_HASH_XXPRIME_2 ((Py_uhash_t)2246822519UL)
#define MS_HASH_XXPRIME_5 ((Py_uhash_t)374761393UL)
#define MS_HASH_XXROTATE(x) ((x << 13) | (x >> 19)) /* Rotate left 13 bits */
#endif
/* Optimized version of PyLong_AsLongLongAndOverflow/PyLong_AsUnsignedLongLong.
*
* Returns True if sign * scale won't fit in an `int64` or a `uint64`.
*/
static inline bool
fast_long_extract_parts(PyObject *vv, bool *neg, uint64_t *scale) {
PyLongObject *v = (PyLongObject *)vv;
uint64_t prev, x = 0;
bool negative;
#if PY312_PLUS
/* CPython 3.12 changed int internal representation */
int sign = 1 - (v->long_value.lv_tag & _PyLong_SIGN_MASK);
negative = sign == -1;
if (_PyLong_IsCompact(v)) {
x = v->long_value.ob_digit[0];
}
else {
Py_ssize_t i = v->long_value.lv_tag >> _PyLong_NON_SIZE_BITS;
while (--i >= 0) {
prev = x;
x = (x << PyLong_SHIFT) + v->long_value.ob_digit[i];
if ((x >> PyLong_SHIFT) != prev) {
return true;
}
}
if (negative && x > (1ull << 63)) {
return true;
}
}
#else
Py_ssize_t i = Py_SIZE(v);
negative = false;
if (MS_LIKELY(i == 1)) {
x = v->ob_digit[0];
}
else if (i != 0) {
negative = i < 0;
if (MS_UNLIKELY(negative)) { i = -i; }
while (--i >= 0) {
prev = x;
x = (x << PyLong_SHIFT) + v->ob_digit[i];
if ((x >> PyLong_SHIFT) != prev) {
return true;
}
}
if (negative && x > (1ull << 63)) {
return true;
}
}
#endif
*neg = negative;
*scale = x;
return false;
}
/* Access macro to the members which are floating "behind" the object */
#define MS_PyHeapType_GET_MEMBERS(etype) \
((PyMemberDef *)(((char *)(etype)) + Py_TYPE(etype)->tp_basicsize))
#define MS_GET_FIRST_SLOT(obj) \
*((PyObject **)((char *)(obj) + sizeof(PyObject))) \
#define MS_SET_FIRST_SLOT(obj, val) \
MS_GET_FIRST_SLOT(obj) = (val)
/*************************************************************************
* Lookup Tables *
*************************************************************************/
static const char hex_encode_table[] = "0123456789abcdef";
static const char base64_encode_table[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/*************************************************************************
* GC Utilities *
*************************************************************************/
/* Mirrored from pycore_gc.h in cpython */
typedef struct {
uintptr_t _gc_next;
uintptr_t _gc_prev;
} MS_PyGC_Head;
#define MS_AS_GC(o) ((MS_PyGC_Head *)(o)-1)
#define MS_TYPE_IS_GC(t) (((PyTypeObject *)(t))->tp_flags & Py_TPFLAGS_HAVE_GC)
#define MS_OBJECT_IS_GC(obj) MS_TYPE_IS_GC(Py_TYPE(obj))
#define MS_IS_TRACKED(o) (MS_AS_GC(o)->_gc_next != 0)
/* Is this object something that is/could be GC tracked? True if
* - the value supports GC
* - the value isn't a tuple or the object is tracked (skip tracked checks for non-tuples)
*/
#define MS_MAYBE_TRACKED(x) \
(MS_TYPE_IS_GC(Py_TYPE(x)) && \
(!PyTuple_CheckExact(x) || MS_IS_TRACKED(x)))
/*************************************************************************
* Murmurhash2 *
*************************************************************************/
static inline uint32_t
unaligned_load(const unsigned char *p) {
uint32_t out;
memcpy(&out, p, sizeof(out));
return out;
}
static inline uint32_t
murmur2(const char *p, Py_ssize_t len) {
const unsigned char *buf = (unsigned char *)p;
const size_t m = 0x5bd1e995;
uint32_t hash = (uint32_t)len;
while(len >= 4) {
uint32_t k = unaligned_load(buf);
k *= m;
k ^= k >> 24;
k *= m;
hash *= m;
hash ^= k;
buf += 4;
len -= 4;
}
switch(len) {
case 3:
hash ^= buf[2] << 16;
case 2:
hash ^= buf[1] << 8;
case 1:
hash ^= buf[0];
hash *= m;
};
hash ^= hash >> 13;
hash *= m;
hash ^= hash >> 15;
return hash;
}
/*************************************************************************
* String Cache *
*************************************************************************/
#ifndef STRING_CACHE_SIZE
#define STRING_CACHE_SIZE 512
#endif
#ifndef STRING_CACHE_MAX_STRING_LENGTH
#define STRING_CACHE_MAX_STRING_LENGTH 32
#endif
static PyObject *string_cache[STRING_CACHE_SIZE];
static void
string_cache_clear(void) {
/* Traverse the string cache, deleting any string with a reference count of
* only 1 */
for (Py_ssize_t i = 0; i < STRING_CACHE_SIZE; i++) {
PyObject *obj = string_cache[i];
if (obj != NULL) {
if (Py_REFCNT(obj) == 1) {
Py_DECREF(obj);
string_cache[i] = NULL;
}
}
}
}
/*************************************************************************
* Endian handling macros *
*************************************************************************/
#define _msgspec_store16(to, x) do { \
((uint8_t*)to)[0] = (uint8_t)((x >> 8) & 0xff); \
((uint8_t*)to)[1] = (uint8_t)(x & 0xff); \
} while (0);
#define _msgspec_store32(to, x) do { \
((uint8_t*)to)[0] = (uint8_t)((x >> 24) & 0xff); \
((uint8_t*)to)[1] = (uint8_t)((x >> 16) & 0xff); \
((uint8_t*)to)[2] = (uint8_t)((x >> 8) & 0xff); \
((uint8_t*)to)[3] = (uint8_t)(x & 0xff); \
} while (0);
#define _msgspec_store64(to, x) do { \
((uint8_t*)to)[0] = (uint8_t)((x >> 56) & 0xff); \
((uint8_t*)to)[1] = (uint8_t)((x >> 48) & 0xff); \
((uint8_t*)to)[2] = (uint8_t)((x >> 40) & 0xff); \
((uint8_t*)to)[3] = (uint8_t)((x >> 32) & 0xff); \
((uint8_t*)to)[4] = (uint8_t)((x >> 24) & 0xff); \
((uint8_t*)to)[5] = (uint8_t)((x >> 16) & 0xff); \
((uint8_t*)to)[6] = (uint8_t)((x >> 8) & 0xff); \
((uint8_t*)to)[7] = (uint8_t)(x & 0xff); \
} while (0);
#define _msgspec_load16(cast, from) ((cast)( \
(((uint16_t)((uint8_t*)from)[0]) << 8) | \
(((uint16_t)((uint8_t*)from)[1]) ) ))
#define _msgspec_load32(cast, from) ((cast)( \
(((uint32_t)((uint8_t*)from)[0]) << 24) | \
(((uint32_t)((uint8_t*)from)[1]) << 16) | \
(((uint32_t)((uint8_t*)from)[2]) << 8) | \
(((uint32_t)((uint8_t*)from)[3]) ) ))
#define _msgspec_load64(cast, from) ((cast)( \
(((uint64_t)((uint8_t*)from)[0]) << 56) | \
(((uint64_t)((uint8_t*)from)[1]) << 48) | \
(((uint64_t)((uint8_t*)from)[2]) << 40) | \
(((uint64_t)((uint8_t*)from)[3]) << 32) | \
(((uint64_t)((uint8_t*)from)[4]) << 24) | \
(((uint64_t)((uint8_t*)from)[5]) << 16) | \
(((uint64_t)((uint8_t*)from)[6]) << 8) | \
(((uint64_t)((uint8_t*)from)[7]) ) ))
/*************************************************************************
* Module level state *
*************************************************************************/
/* State of the msgspec module */
typedef struct {
PyObject *MsgspecError;
PyObject *EncodeError;
PyObject *DecodeError;
PyObject *ValidationError;
PyObject *StructType;
PyTypeObject *EnumMetaType;
PyObject *struct_lookup_cache;
PyObject *str___weakref__;
PyObject *str___dict__;
PyObject *str___msgspec_cached_hash__;
PyObject *str__value2member_map_;
PyObject *str___msgspec_cache__;
PyObject *str__value_;
PyObject *str__missing_;
PyObject *str_type;
PyObject *str_enc_hook;
PyObject *str_dec_hook;
PyObject *str_ext_hook;
PyObject *str_strict;
PyObject *str_order;
PyObject *str_utcoffset;
PyObject *str___origin__;
PyObject *str___args__;
PyObject *str___metadata__;
PyObject *str___total__;
PyObject *str___required_keys__;
PyObject *str__fields;
PyObject *str__field_defaults;
PyObject *str___post_init__;
PyObject *str___dataclass_fields__;
PyObject *str___attrs_attrs__;
PyObject *str___supertype__;
#if PY312_PLUS
PyObject *str___value__;
#endif
PyObject *str___bound__;
PyObject *str___constraints__;
PyObject *str_int;
PyObject *str_is_safe;
PyObject *UUIDType;
PyObject *uuid_safeuuid_unknown;
PyObject *DecimalType;
PyObject *typing_union;
PyObject *typing_any;
PyObject *typing_literal;
PyObject *typing_classvar;
PyObject *typing_typevar;
PyObject *typing_final;
PyObject *typing_generic;
PyObject *typing_generic_alias;
PyObject *typing_annotated_alias;
PyObject *concrete_types;
PyObject *get_type_hints;
PyObject *get_class_annotations;
PyObject *get_typeddict_info;
PyObject *get_dataclass_info;
PyObject *rebuild;
#if PY310_PLUS
PyObject *types_uniontype;
#endif
#if PY312_PLUS
PyObject *typing_typealiastype;
#endif
PyObject *astimezone;
PyObject *re_compile;
uint8_t gc_cycle;
} MsgspecState;
/* Forward declaration of the msgspec module definition. */
static struct PyModuleDef msgspecmodule;
/* Given a module object, get its per-module state. */
static MsgspecState *
msgspec_get_state(PyObject *module)
{
return (MsgspecState *)PyModule_GetState(module);
}
/* Find the module instance imported in the currently running sub-interpreter
and get its state. */
static MsgspecState *
msgspec_get_global_state(void)
{
PyObject *module = PyState_FindModule(&msgspecmodule);
return module == NULL ? NULL : msgspec_get_state(module);
}
static int
ms_err_truncated(void)
{
PyErr_SetString(msgspec_get_global_state()->DecodeError, "Input data was truncated");
return -1;
}
/*************************************************************************
* Utilities *
*************************************************************************/
static PyObject*
find_keyword(PyObject *kwnames, PyObject *const *kwstack, PyObject *key)
{
Py_ssize_t i, nkwargs;
nkwargs = PyTuple_GET_SIZE(kwnames);
for (i = 0; i < nkwargs; i++) {
PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
/* kwname == key will normally find a match in since keyword keys
should be interned strings; if not retry below in a new loop. */
if (kwname == key) {
return kwstack[i];
}
}
for (i = 0; i < nkwargs; i++) {
PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
assert(PyUnicode_Check(kwname));
if (MS_UNICODE_EQ(kwname, key)) {
return kwstack[i];
}
}
return NULL;
}
static int
check_positional_nargs(Py_ssize_t nargs, Py_ssize_t min, Py_ssize_t max) {
if (nargs > max) {
PyErr_SetString(
PyExc_TypeError,
"Extra positional arguments provided"
);
return 0;
}
else if (nargs < min) {
PyErr_Format(
PyExc_TypeError,
"Missing %zd required arguments",
min - nargs
);
return 0;
}
return 1;
}
/* A utility incrementally building strings */
typedef struct strbuilder {
char *sep;
Py_ssize_t sep_size;
char *buffer;
Py_ssize_t size; /* How many bytes have been written */
Py_ssize_t capacity; /* How many bytes can be written */
} strbuilder;
#define strbuilder_extend_literal(self, str) strbuilder_extend(self, str, sizeof(str) - 1)
static bool strbuilder_extend(strbuilder *self, const char *buf, Py_ssize_t nbytes) {
bool is_first_write = self->size == 0;
Py_ssize_t required = self->size + nbytes + self->sep_size;
if (required > self->capacity) {
self->capacity = required * 1.5;
char *new_buf = PyMem_Realloc(self->buffer, self->capacity);
if (new_buf == NULL) {
PyMem_Free(self->buffer);
self->buffer = NULL;
return false;
}
self->buffer = new_buf;
}
if (self->sep_size && !is_first_write) {
memcpy(self->buffer + self->size, self->sep, self->sep_size);
self->size += self->sep_size;
}
memcpy(self->buffer + self->size, buf, nbytes);
self->size += nbytes;
return true;
}
static bool
strbuilder_extend_unicode(strbuilder *self, PyObject *obj) {
Py_ssize_t size;
const char* buf = unicode_str_and_size(obj, &size);
if (buf == NULL) return false;
return strbuilder_extend(self, buf, size);
}
static void
strbuilder_reset(strbuilder *self) {
if (self->capacity != 0 && self->buffer != NULL) {
PyMem_Free(self->buffer);
}
self->buffer = NULL;
self->size = 0;
self->capacity = 0;
}
static PyObject *
strbuilder_build(strbuilder *self) {
PyObject *out = PyUnicode_FromStringAndSize(self->buffer, self->size);
strbuilder_reset(self);
return out;
}
/*************************************************************************
* PathNode *
*************************************************************************/
#define PATH_ELLIPSIS -1
#define PATH_STR -2
#define PATH_KEY -3
typedef struct PathNode {
struct PathNode *parent;
Py_ssize_t index;
PyObject *object;
} PathNode;
/* reverse the parent pointers in the path linked list */
static PathNode *
pathnode_reverse(PathNode *path) {
PathNode *current = path, *prev = NULL, *next = NULL;
while (current != NULL) {
next = current->parent;
current->parent = prev;
prev = current;
current = next;
}
return prev;
}
static PyObject* StructMeta_get_field_name(PyObject*, Py_ssize_t);
static PyObject *
PathNode_ErrSuffix(PathNode *path) {
strbuilder parts = {0};
PathNode *path_orig;
PyObject *out = NULL, *path_repr = NULL, *groups = NULL, *group = NULL;
if (path == NULL) {
return PyUnicode_FromString("");
}
/* Reverse the parent pointers for easier printing */
path = pathnode_reverse(path);
/* Cache the original path to reset the parent pointers later */
path_orig = path;
/* Start with the root element */
if (!strbuilder_extend_literal(&parts, "`$")) goto cleanup;
while (path != NULL) {
if (path->object != NULL) {
PyObject *name;
if (path->index == PATH_STR) {
name = path->object;
}
else {
name = StructMeta_get_field_name(path->object, path->index);
}
if (!strbuilder_extend_literal(&parts, ".")) goto cleanup;
if (!strbuilder_extend_unicode(&parts, name)) goto cleanup;
}
else if (path->index == PATH_ELLIPSIS) {
if (!strbuilder_extend_literal(&parts, "[...]")) goto cleanup;
}
else if (path->index == PATH_KEY) {
if (groups == NULL) {
groups = PyList_New(0);
if (groups == NULL) goto cleanup;
}
if (!strbuilder_extend_literal(&parts, "`")) goto cleanup;
group = strbuilder_build(&parts);
if (group == NULL) goto cleanup;
if (PyList_Append(groups, group) < 0) goto cleanup;
Py_CLEAR(group);
strbuilder_extend_literal(&parts, "`key");
}
else {
char buf[20];
char *p = &buf[20];
Py_ssize_t x = path->index;
if (!strbuilder_extend_literal(&parts, "[")) goto cleanup;
while (x >= 100) {
const int64_t old = x;
p -= 2;
x /= 100;
memcpy(p, DIGIT_TABLE + ((old - (x * 100)) << 1), 2);
}
if (x >= 10) {
p -= 2;
memcpy(p, DIGIT_TABLE + (x << 1), 2);
}
else {
*--p = x + '0';
}
if (!strbuilder_extend(&parts, p, &buf[20] - p)) goto cleanup;
if (!strbuilder_extend_literal(&parts, "]")) goto cleanup;
}
path = path->parent;
}
if (!strbuilder_extend_literal(&parts, "`")) goto cleanup;
if (groups == NULL) {
path_repr = strbuilder_build(&parts);
}
else {
group = strbuilder_build(&parts);
if (group == NULL) goto cleanup;
if (PyList_Append(groups, group) < 0) goto cleanup;
PyObject *sep = PyUnicode_FromString(" in ");
if (sep == NULL) goto cleanup;
if (PyList_Reverse(groups) < 0) goto cleanup;
path_repr = PyUnicode_Join(sep, groups);
Py_DECREF(sep);
}
out = PyUnicode_FromFormat(" - at %U", path_repr);
cleanup:
Py_XDECREF(path_repr);
Py_XDECREF(group);
Py_XDECREF(groups);
pathnode_reverse(path_orig);
strbuilder_reset(&parts);
return out;
}
/*************************************************************************
* Lookup Tables for ints & strings *
*************************************************************************/
typedef struct Lookup {
PyObject_VAR_HEAD
PyObject *tag_field; /* used for struct lookup table only */
PyObject *cls; /* Used for enum lookup table only */
bool array_like;
} Lookup;
static PyTypeObject IntLookup_Type;
static PyTypeObject StrLookup_Type;
typedef struct IntLookup {
Lookup common;
bool compact;
} IntLookup;
typedef struct IntLookupEntry {
int64_t key;
PyObject *value;
} IntLookupEntry;
typedef struct IntLookupHashmap {
IntLookup base;
IntLookupEntry table[];
} IntLookupHashmap;
typedef struct IntLookupCompact {
IntLookup base;
int64_t offset;
PyObject* table[];
} IntLookupCompact;
typedef struct StrLookupEntry {
PyObject *key;
PyObject *value;
} StrLookupEntry;
typedef struct StrLookup {
Lookup common;
StrLookupEntry table[];
} StrLookup;
#define Lookup_array_like(obj) ((Lookup *)(obj))->array_like
#define Lookup_tag_field(obj) ((Lookup *)(obj))->tag_field
#define Lookup_IsStrLookup(obj) (Py_TYPE(obj) == &StrLookup_Type)
#define Lookup_IsIntLookup(obj) (Py_TYPE(obj) == &IntLookup_Type)
/* Handles Enum._missing_ calls. Returns a new reference, or NULL on error.
* Will decref val if non-null. */
static PyObject *
_Lookup_OnMissing(Lookup *lookup, PyObject *val, PathNode *path) {
if (val == NULL) return NULL;
MsgspecState *mod = msgspec_get_global_state();
if (lookup->cls != NULL) {
PyObject *out = PyObject_CallMethodOneArg(lookup->cls, mod->str__missing_, val);
if (out == NULL) {
PyErr_Clear();
}
else if (out == Py_None) {
Py_DECREF(out);
}
else {
Py_DECREF(val);
return out;
}
}
PyObject *suffix = PathNode_ErrSuffix(path);
if (suffix != NULL) {
PyErr_Format(mod->ValidationError, "Invalid enum value %R%U", val, suffix);
Py_DECREF(suffix);
}
Py_DECREF(val);
return NULL;
}
static IntLookupEntry *
_IntLookupHashmap_lookup(IntLookupHashmap *self, int64_t key) {
IntLookupEntry *table = self->table;
size_t mask = Py_SIZE(self) - 1;
size_t i = key & mask;
while (true) {
IntLookupEntry *entry = &table[i];
if (MS_LIKELY(entry->key == key)) return entry;
if (entry->value == NULL) return entry;
i = (i + 1) & mask;
}
/* Unreachable */
return NULL;
}
static void
_IntLookupHashmap_Set(IntLookupHashmap *self, int64_t key, PyObject *value) {
IntLookupEntry *entry = _IntLookupHashmap_lookup(self, key);
Py_XDECREF(entry->value);
Py_INCREF(value);
entry->key = key;
entry->value = value;
}
static PyObject *
IntLookup_New(PyObject *arg, PyObject *tag_field, PyObject *cls, bool array_like) {
Py_ssize_t nitems;
PyObject *item, *items = NULL;
IntLookup *self = NULL;
int64_t imin = LLONG_MAX, imax = LLONG_MIN;
if (PyDict_CheckExact(arg)) {
nitems = PyDict_GET_SIZE(arg);
}
else {
items = PySequence_Tuple(arg);
if (items == NULL) return NULL;
nitems = PyTuple_GET_SIZE(items);
}
/* Must have at least one item */
if (nitems == 0) {
PyErr_Format(
PyExc_TypeError,
"Enum types must have at least one item, %R is invalid",
arg
);
goto cleanup;
}
/* Find the min/max of items, and error if any item isn't an integer or is
* out of range */
#define handle(key) \
do { \
int overflow = 0; \
int64_t ival = PyLong_AsLongLongAndOverflow(key, &overflow); \
if (overflow) { \
PyErr_SetString( \
PyExc_NotImplementedError, \
"Integer values > (2**63 - 1) are not currently supported for " \
"Enum/Literal/integer tags. If you need this feature, please " \
"open an issue on GitHub." \
); \
goto cleanup; \
} \
if (ival == -1 && PyErr_Occurred()) goto cleanup; \
if (ival < imin) { \
imin = ival; \
} \
if (ival > imax) { \
imax = ival; \
} \
} while (false)
if (PyDict_CheckExact(arg)) {
PyObject *key, *val;
Py_ssize_t pos = 0;
while (PyDict_Next(arg, &pos, &key, &val)) {
handle(key);
}
}
else {
for (Py_ssize_t i = 0; i < nitems; i++) {
handle(PyTuple_GET_ITEM(items, i));
}
}
#undef handle
/* Calculate range without overflow */
uint64_t range;
if (imax > 0) {
range = imax;
range -= imin;
}
else {
range = imax - imin;
}
if (range < 1.4 * nitems) {
/* Use compact representation */
size_t size = range + 1;
/* XXX: In Python 3.11+ there's not an easy way to allocate an untyped
* block of memory that is also tracked by the GC. To hack around this
* we set `tp_itemsize = 1` for `IntLookup_Type`, and manually calculate
* the size of trailing parts. It's gross, but it works. */
size_t nextra = (
sizeof(IntLookupCompact)
+ (size * sizeof(PyObject *))
- sizeof(IntLookup)
);
IntLookupCompact *out = PyObject_GC_NewVar(
IntLookupCompact, &IntLookup_Type, nextra
);
if (out == NULL) goto cleanup;
/* XXX: overwrite `ob_size`, since we lied above */
Py_SET_SIZE(out, size);
out->offset = imin;
for (size_t i = 0; i < size; i++) {
out->table[i] = NULL;
}
#define setitem(key, val) \
do { \
int64_t ikey = PyLong_AsLongLong(key); \
out->table[ikey - imin] = val; \
Py_INCREF(val); \
} while (false)
if (PyDict_CheckExact(arg)) {
PyObject *key, *val;
Py_ssize_t pos = 0;
while (PyDict_Next(arg, &pos, &key, &val)) {
setitem(key, val);
}
}
else {
for (Py_ssize_t i = 0; i < nitems; i++) {
item = PyTuple_GET_ITEM(items, i);
setitem(item, item);
}
}
#undef setitem
self = (IntLookup *)out;
self->compact = true;
}
else {
/* Use hashtable */
size_t needed = nitems * 4 / 3;
size_t size = 4;
while (size < (size_t)needed) { size <<= 1; }
/* XXX: This is hacky, see comment above allocating IntLookupCompact */
size_t nextra = (
sizeof(IntLookupHashmap)
+ (size * sizeof(IntLookupEntry))
- sizeof(IntLookup)
);
IntLookupHashmap *out = PyObject_GC_NewVar(
IntLookupHashmap, &IntLookup_Type, nextra
);
if (out == NULL) goto cleanup;
/* XXX: overwrite `ob_size`, since we lied above */
Py_SET_SIZE(out, size);
for (size_t i = 0; i < size; i++) {
out->table[i].key = 0;
out->table[i].value = NULL;
}
if (PyDict_CheckExact(arg)) {
PyObject *key, *val;
Py_ssize_t pos = 0;
while (PyDict_Next(arg, &pos, &key, &val)) {
int64_t ival = PyLong_AsLongLong(key);
_IntLookupHashmap_Set(out, ival, val);
}
}
else {
for (Py_ssize_t i = 0; i < nitems; i++) {
PyObject *val = PyTuple_GET_ITEM(items, i);
int64_t ival = PyLong_AsLongLong(val);
_IntLookupHashmap_Set(out, ival, val);
}
}
self = (IntLookup *)out;
self->compact = false;
}
/* Store extra metadata (struct lookup only) */
Py_XINCREF(tag_field);
self->common.tag_field = tag_field;
Py_XINCREF(cls);
self->common.cls = cls;
self->common.array_like = array_like;
cleanup:
Py_XDECREF(items);
if (self != NULL) {
PyObject_GC_Track(self);
}
return (PyObject *)self;
}
static int
IntLookup_traverse(IntLookup *self, visitproc visit, void *arg)
{
Py_VISIT(self->common.cls);
if (self->compact) {
IntLookupCompact *lk = (IntLookupCompact *)self;
for (Py_ssize_t i = 0; i < Py_SIZE(lk); i++) {
Py_VISIT(lk->table[i]);
}
}
else {
IntLookupHashmap *lk = (IntLookupHashmap *)self;
for (Py_ssize_t i = 0; i < Py_SIZE(lk); i++) {
Py_VISIT(lk->table[i].value);
}
}
return 0;
}
static int
IntLookup_clear(IntLookup *self)
{
if (self->compact) {
IntLookupCompact *lk = (IntLookupCompact *)self;
for (Py_ssize_t i = 0; i < Py_SIZE(lk); i++) {
Py_CLEAR(lk->table[i]);
}
}
else {
IntLookupHashmap *lk = (IntLookupHashmap *)self;
for (Py_ssize_t i = 0; i < Py_SIZE(lk); i++) {
Py_CLEAR(lk->table[i].value);
}
}
Py_CLEAR(self->common.cls);
Py_CLEAR(self->common.tag_field);
return 0;
}
static void
IntLookup_dealloc(IntLookup *self)
{
PyObject_GC_UnTrack(self);
IntLookup_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
IntLookup_GetInt64(IntLookup *self, int64_t key) {
if (MS_LIKELY(self->compact)) {
IntLookupCompact *lk = (IntLookupCompact *)self;
Py_ssize_t index = key - lk->offset;
if (index >= 0 && index < Py_SIZE(lk)) {
return lk->table[index];
}
return NULL;
}
return _IntLookupHashmap_lookup((IntLookupHashmap *)self, key)->value;
}
static PyObject *
IntLookup_GetInt64OrError(IntLookup *self, int64_t key, PathNode *path) {
PyObject *out = IntLookup_GetInt64(self, key);
if (out != NULL) {
Py_INCREF(out);
return out;
}
return _Lookup_OnMissing((Lookup *)self, PyLong_FromLongLong(key), path);
}
static PyObject *
IntLookup_GetUInt64(IntLookup *self, uint64_t key) {
if (key > LLONG_MAX) return NULL;
return IntLookup_GetInt64(self, key);
}
static PyObject *
IntLookup_GetUInt64OrError(IntLookup *self, uint64_t key, PathNode *path) {
PyObject *out = IntLookup_GetUInt64(self, key);
if (out != NULL) {
Py_INCREF(out);
return out;
}
return _Lookup_OnMissing(
(Lookup *)self, PyLong_FromUnsignedLongLong(key), path
);
}
static PyObject *
IntLookup_GetPyIntOrError(IntLookup *self, PyObject *key, PathNode *path) {
uint64_t x;
bool neg, overflow;
PyObject *out = NULL;
overflow = fast_long_extract_parts(key, &neg, &x);
if (!overflow) {
if (neg) {
out = IntLookup_GetInt64(self, -(int64_t)x);
}
else {
out = IntLookup_GetUInt64(self, x);
}
}
if (out != NULL) {
Py_INCREF(out);
return out;
}
/* PyNumber_Long call ensures input is actual int */
return _Lookup_OnMissing((Lookup *)self, PyNumber_Long(key), path);
}
static PyTypeObject IntLookup_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.IntLookup",
.tp_basicsize = sizeof(IntLookup),
.tp_itemsize = 1,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_dealloc = (destructor)IntLookup_dealloc,
.tp_clear = (inquiry)IntLookup_clear,
.tp_traverse = (traverseproc)IntLookup_traverse,
};
static StrLookupEntry *
_StrLookup_lookup(StrLookup *self, const char *key, Py_ssize_t size)
{
StrLookupEntry *table = self->table;
size_t hash = murmur2(key, size);
size_t perturb = hash;
size_t mask = Py_SIZE(self) - 1;
size_t i = hash & mask;
while (true) {
StrLookupEntry *entry = &table[i];
if (entry->value == NULL) return entry;
Py_ssize_t entry_size;
const char *entry_key = unicode_str_and_size_nocheck(entry->key, &entry_size);
if (entry_size == size && memcmp(entry_key, key, size) == 0) return entry;
/* Collision, perturb and try again */
perturb >>= 5;
i = mask & (i*5 + perturb + 1);
}
/* Unreachable */
return NULL;
}
static int
StrLookup_Set(StrLookup *self, PyObject *key, PyObject *value) {
Py_ssize_t key_size;
const char *key_str = unicode_str_and_size(key, &key_size);
if (key_str == NULL) return -1;
StrLookupEntry *entry = _StrLookup_lookup(self, key_str, key_size);
entry->key = key;
Py_INCREF(key);
entry->value = value;
Py_INCREF(value);
return 0;
}
static PyObject *
StrLookup_New(PyObject *arg, PyObject *tag_field, PyObject *cls, bool array_like) {
Py_ssize_t nitems;
PyObject *item, *items = NULL;
StrLookup *self = NULL;
if (PyDict_CheckExact(arg)) {
nitems = PyDict_GET_SIZE(arg);
}
else {
items = PySequence_Tuple(arg);
if (items == NULL) return NULL;
nitems = PyTuple_GET_SIZE(items);
}
/* Must have at least one item */
if (nitems == 0) {
PyErr_Format(
PyExc_TypeError,
"Enum types must have at least one item, %R is invalid",
arg
);
goto cleanup;
}
size_t needed = nitems * 4 / 3;
size_t size = 4;
while (size < (size_t)needed) {
size <<= 1;
}
self = PyObject_GC_NewVar(StrLookup, &StrLookup_Type, size);
if (self == NULL) goto cleanup;
/* Zero out memory */
self->common.cls = NULL;
self->common.tag_field = NULL;
for (size_t i = 0; i < size; i++) {
self->table[i].key = NULL;
self->table[i].value = NULL;
}
if (PyDict_CheckExact(arg)) {
PyObject *key, *val;
Py_ssize_t pos = 0;
while (PyDict_Next(arg, &pos, &key, &val)) {
if (!PyUnicode_CheckExact(key)) {
PyErr_SetString(PyExc_RuntimeError, "Enum values must be strings");
Py_CLEAR(self);
goto cleanup;
}
if (StrLookup_Set(self, key, val) < 0) {
Py_CLEAR(self);
goto cleanup;
}
}
}
else {
for (Py_ssize_t i = 0; i < nitems; i++) {
item = PyTuple_GET_ITEM(items, i);
if (!PyUnicode_CheckExact(item)) {
PyErr_SetString(PyExc_RuntimeError, "Enum values must be strings");
Py_CLEAR(self);
goto cleanup;
}
if (StrLookup_Set(self, item, item) < 0) {
Py_CLEAR(self);
goto cleanup;
}
}
}
Py_XINCREF(cls);
self->common.cls = cls;
Py_XINCREF(tag_field);
self->common.tag_field = tag_field;
self->common.array_like = array_like;
cleanup:
Py_XDECREF(items);
if (self != NULL) {
PyObject_GC_Track(self);
}
return (PyObject *)self;
}
static int
StrLookup_traverse(StrLookup *self, visitproc visit, void *arg)
{
Py_VISIT(self->common.cls);
for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
Py_VISIT(self->table[i].key);
Py_VISIT(self->table[i].value);
}
return 0;
}
static int
StrLookup_clear(StrLookup *self)
{
for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
Py_CLEAR(self->table[i].key);
Py_CLEAR(self->table[i].value);
}
Py_CLEAR(self->common.cls);
Py_CLEAR(self->common.tag_field);
return 0;
}
static void
StrLookup_dealloc(StrLookup *self)
{
PyObject_GC_UnTrack(self);
StrLookup_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
StrLookup_Get(StrLookup *self, const char *key, Py_ssize_t size) {
StrLookupEntry *entry = _StrLookup_lookup(self, key, size);
return entry->value;
}
static PyObject *
StrLookup_GetOrError(
StrLookup *self, const char *key, Py_ssize_t size, PathNode *path
) {
PyObject *out = StrLookup_Get(self, key, size);
if (out != NULL) {
Py_INCREF(out);
return out;
}
return _Lookup_OnMissing(
(Lookup *)self, PyUnicode_FromStringAndSize(key, size), path
);
}
static PyTypeObject StrLookup_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.StrLookup",
.tp_basicsize = sizeof(StrLookup),
.tp_itemsize = sizeof(StrLookupEntry),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_dealloc = (destructor) StrLookup_dealloc,
.tp_clear = (inquiry)StrLookup_clear,
.tp_traverse = (traverseproc) StrLookup_traverse,
};
/*************************************************************************
* Raw *
*************************************************************************/
static PyTypeObject Raw_Type;
typedef struct Raw {
PyObject_HEAD
PyObject *base;
char *buf;
Py_ssize_t len;
bool is_view;
} Raw;
static PyObject *
Raw_New(PyObject *msg) {
Raw *out = (Raw *)Raw_Type.tp_alloc(&Raw_Type, 0);
if (out == NULL) return NULL;
if (PyBytes_CheckExact(msg)) {
Py_INCREF(msg);
out->base = msg;
out->buf = PyBytes_AS_STRING(msg);
out->len = PyBytes_GET_SIZE(msg);
out->is_view = false;
}
else if (PyUnicode_CheckExact(msg)) {
out->base = msg;
out->buf = (char *)unicode_str_and_size(msg, &out->len);
if (out->buf == NULL) return NULL;
Py_INCREF(msg);
out->is_view = false;
}
else {
Py_buffer buffer;
if (PyObject_GetBuffer(msg, &buffer, PyBUF_CONTIG_RO) < 0) {
Py_DECREF(out);
return NULL;
}
out->base = buffer.obj;
out->buf = buffer.buf;
out->len = buffer.len;
out->is_view = true;
}
return (PyObject *)out;
}
PyDoc_STRVAR(Raw__doc__,
"Raw(msg="", /)\n"
"--\n"
"\n"
"A buffer containing an encoded message.\n"
"\n"
"Raw objects have two common uses:\n"
"\n"
"- During decoding. Fields annotated with the ``Raw`` type won't be decoded\n"
" immediately, but will instead return a ``Raw`` object with a view into the\n"
" original message where that field is encoded. This is useful for decoding\n"
" fields whose type may only be inferred after decoding other fields.\n"
"- During encoding. Raw objects wrap pre-encoded messages. These can be added\n"
" as components of larger messages without having to pay the cost of decoding\n"
" and re-encoding them.\n"
"\n"
"Parameters\n"
"----------\n"
"msg: bytes, bytearray, memoryview, or str, optional\n"
" A buffer containing an encoded message. One of bytes, bytearray, memoryview,\n"
" str, or any object that implements the buffer protocol. If not present,\n"
" defaults to an empty buffer."
);
static PyObject *
Raw_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
PyObject *msg;
Py_ssize_t nargs, nkwargs;
nargs = PyTuple_GET_SIZE(args);
nkwargs = (kwargs == NULL) ? 0 : PyDict_GET_SIZE(kwargs);
if (nkwargs != 0) {
PyErr_SetString(
PyExc_TypeError,
"Raw takes no keyword arguments"
);
return NULL;
}
else if (nargs == 0) {
msg = PyBytes_FromStringAndSize(NULL, 0);
if (msg == NULL) return NULL;
/* This looks weird, but is safe since the empty bytes object is an
* immortal singleton */
Py_DECREF(msg);
}
else if (nargs == 1) {
msg = PyTuple_GET_ITEM(args, 0);
}
else {
PyErr_Format(
PyExc_TypeError,
"Raw expected at most 1 arguments, got %zd",
nargs
);
return NULL;
}
return Raw_New(msg);
}
static void
Raw_dealloc(Raw *self)
{
if (self->base != NULL) {
if (!self->is_view) {
Py_DECREF(self->base);
}
else {
Py_buffer buffer;
buffer.obj = self->base;
buffer.len = self->len;
buffer.buf = self->buf;
ms_release_buffer(&buffer);
}
}
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
Raw_FromView(PyObject *buffer_obj, char *data, Py_ssize_t len) {
Raw *out = (Raw *)Raw_Type.tp_alloc(&Raw_Type, 0);
if (out == NULL) return NULL;
Py_buffer buffer;
if (ms_get_buffer(buffer_obj, &buffer) < 0) {
Py_DECREF(out);
return NULL;
}
out->base = buffer.obj;
out->buf = data;
out->len = len;
out->is_view = true;
return (PyObject *)out;
}
static PyObject *
Raw_richcompare(Raw *self, PyObject *other, int op) {
if (Py_TYPE(other) != &Raw_Type) {
Py_RETURN_NOTIMPLEMENTED;
}
if (op != Py_EQ && op != Py_NE) {
Py_RETURN_NOTIMPLEMENTED;
}
Raw *raw_other = (Raw *)other;
bool equal = (
self == raw_other || (
(self->len == raw_other->len) &&
(memcmp(self->buf, raw_other->buf, self->len) == 0)
)
);
bool result = (op == Py_EQ) ? equal : !equal;
if (result) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static int
Raw_buffer_getbuffer(Raw *self, Py_buffer *view, int flags)
{
return PyBuffer_FillInfo(view, (PyObject *)self, self->buf, self->len, 1, flags);
}
static PyBufferProcs Raw_as_buffer = {
.bf_getbuffer = (getbufferproc)Raw_buffer_getbuffer
};
static Py_ssize_t
Raw_length(Raw *self) {
return self->len;
}
static PySequenceMethods Raw_as_sequence = {
.sq_length = (lenfunc)Raw_length
};
static PyObject *
Raw_reduce(Raw *self, PyObject *unused)
{
if (!self->is_view) {
return Py_BuildValue("O(O)", &Raw_Type, self->base);
}
return Py_BuildValue("O(y#)", &Raw_Type, self->buf, self->len);
}
PyDoc_STRVAR(Raw_copy__doc__,
"copy(self)\n"
"--\n"
"\n"
"Copy a Raw object.\n"
"\n"
"If the raw message is backed by a memoryview into a larger buffer (as happens\n"
"during decoding), the message is copied and the reference to the larger buffer\n"
"released. This may be useful to reduce memory usage if a Raw object created\n"
"during decoding will be kept in memory for a while rather than immediately\n"
"decoded and dropped."
);
static PyObject *
Raw_copy(Raw *self, PyObject *unused)
{
if (!self->is_view) {
Py_INCREF(self);
return (PyObject *)self;
}
PyObject *buf = PyBytes_FromStringAndSize(self->buf, self->len);
if (buf == NULL) return NULL;
PyObject *out = Raw_New(buf);
Py_DECREF(buf);
return out;
}
static PyMethodDef Raw_methods[] = {
{"__reduce__", (PyCFunction)Raw_reduce, METH_NOARGS},
{"copy", (PyCFunction)Raw_copy, METH_NOARGS, Raw_copy__doc__},
{NULL, NULL},
};
static PyTypeObject Raw_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec.Raw",
.tp_doc = Raw__doc__,
.tp_basicsize = sizeof(Raw),
.tp_itemsize = sizeof(char),
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_new = Raw_new,
.tp_dealloc = (destructor) Raw_dealloc,
.tp_as_buffer = &Raw_as_buffer,
.tp_as_sequence = &Raw_as_sequence,
.tp_methods = Raw_methods,
.tp_richcompare = (richcmpfunc) Raw_richcompare,
};
/*************************************************************************
* Meta *
*************************************************************************/
static PyTypeObject Meta_Type;
typedef struct Meta {
PyObject_HEAD
PyObject *gt;
PyObject *ge;
PyObject *lt;
PyObject *le;
PyObject *multiple_of;
PyObject *pattern;
PyObject *regex;
PyObject *min_length;
PyObject *max_length;
PyObject *tz;
PyObject *title;
PyObject *description;
PyObject *examples;
PyObject *extra_json_schema;
PyObject *extra;
} Meta;
static bool
ensure_is_string(PyObject *val, const char *param) {
if (PyUnicode_CheckExact(val)) return true;
PyErr_Format(
PyExc_TypeError,
"`%s` must be a str, got %.200s",
param, Py_TYPE(val)->tp_name
);
return false;
}
static bool
ensure_is_bool(PyObject *val, const char *param) {
if (val == Py_True || val == Py_False) return true;
PyErr_Format(
PyExc_TypeError,
"`%s` must be a bool, got %.200s",
param, Py_TYPE(val)->tp_name
);
return false;
}
static bool
ensure_is_nonnegative_integer(PyObject *val, const char *param) {
if (!PyLong_CheckExact(val)) {
PyErr_Format(
PyExc_TypeError,
"`%s` must be an int, got %.200s",
param, Py_TYPE(val)->tp_name
);
return false;
}
Py_ssize_t x = PyLong_AsSsize_t(val);
if (x >= 0) return true;
PyErr_Format(PyExc_ValueError, "`%s` must be >= 0, got %R", param, val);
return false;
}
static bool
ensure_is_finite_numeric(PyObject *val, const char *param, bool positive) {
double x;
if (PyLong_CheckExact(val)) {
x = PyLong_AsDouble(val);
}
else if (PyFloat_CheckExact(val)) {
x = PyFloat_AS_DOUBLE(val);
if (!isfinite(x)) {
PyErr_Format(
PyExc_ValueError,
"`%s` must be finite, %R is not supported",
param, val
);
return false;
}
}
else {
PyErr_Format(
PyExc_TypeError,
"`%s` must be an int or float, got %.200s",
param, Py_TYPE(val)->tp_name
);
return false;
}
if (positive && x <= 0) {
PyErr_Format(PyExc_ValueError, "`%s` must be > 0", param);
return false;
}
return true;
}
PyDoc_STRVAR(Meta__doc__,
"Meta(*, gt=None, ge=None, lt=None, le=None, multiple_of=None, pattern=None, "
"min_length=None, max_length=None, tz=None, title=None, description=None, "
"examples=None, extra_json_schema=None, extra=None)\n"
"--\n"
"\n"
"Extra metadata and constraints for a type or field.\n"
"\n"
"Parameters\n"
"----------\n"
"gt : int or float, optional\n"
" The annotated value must be greater than ``gt``.\n"
"ge : int or float, optional\n"
" The annotated value must be greater than or equal to ``ge``.\n"
"lt : int or float, optional\n"
" The annotated value must be less than ``lt``.\n"
"le : int or float, optional\n"
" The annotated value must be less than or equal to ``le``.\n"
"multiple_of : int or float, optional\n"
" The annotated value must be a multiple of ``multiple_of``.\n"
"pattern : str, optional\n"
" A regex pattern that the annotated value must match against. Note that\n"
" the pattern is treated as **unanchored**, meaning the ``re.search``\n"
" method is used when matching.\n"
"min_length: int, optional\n"
" The annotated value must have a length greater than or equal to\n"
" ``min_length``.\n"
"max_length: int, optional\n"
" The annotated value must have a length less than or equal to\n"
" ``max_length``.\n"
"tz: bool, optional\n"
" Configures the timezone-requirements for annotated ``datetime``/``time``\n"
" types. Set to ``True`` to require timezone-aware values, or ``False`` to\n"
" require timezone-naive values. The default is ``None``, which accepts\n"
" either timezone-aware or timezone-naive values.\n"
"title: str, optional\n"
" The title to use for the annotated value when generating a json-schema.\n"
"description: str, optional\n"
" The description to use for the annotated value when generating a\n"
" json-schema.\n"
"examples: list, optional\n"
" A list of examples to use for the annotated value when generating a\n"
" json-schema.\n"
"extra_json_schema: dict, optional\n"
" A dict of extra fields to set for the annotated value when generating\n"
" a json-schema. This dict is recursively merged with the generated schema,\n"
" with ``extra_json_schema`` overriding any conflicting autogenerated fields.\n"
"extra: dict, optional\n"
" Any additional user-defined metadata.\n"
"\n"
"Examples\n"
"--------\n"
"Here we use ``Meta`` to add constraints on two different types. The first\n"
"defines a new type alias ``NonNegativeInt``, which is an integer that must be\n"
"``>= 0``. This type alias can be reused in multiple locations. The second uses\n"
"``Meta`` inline in a struct definition to restrict the ``name`` string field\n"
"to a maximum length of 32 characters.\n"
"\n"
">>> import msgspec\n"
">>> from typing import Annotated\n"
">>> from msgspec import Struct, Meta\n"
">>> NonNegativeInt = Annotated[int, Meta(ge=0)]\n"
">>> class User(Struct):\n"
"... name: Annotated[str, Meta(max_length=32)]\n"
"... age: NonNegativeInt\n"
"...\n"
">>> msgspec.json.decode(b'{\"name\": \"alice\", \"age\": 25}', type=User)\n"
"User(name='alice', age=25)\n"
);
static PyObject *
Meta_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
char *kwlist[] = {
"gt", "ge", "lt", "le", "multiple_of",
"pattern", "min_length", "max_length", "tz",
"title", "description", "examples", "extra_json_schema",
"extra", NULL
};
PyObject *gt = NULL, *ge = NULL, *lt = NULL, *le = NULL, *multiple_of = NULL;
PyObject *pattern = NULL, *min_length = NULL, *max_length = NULL, *tz = NULL;
PyObject *title = NULL, *description = NULL, *examples = NULL;
PyObject *extra_json_schema = NULL, *extra = NULL;
PyObject *regex = NULL;
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "|$OOOOOOOOOOOOOO:Meta.__new__", kwlist,
>, &ge, <, &le, &multiple_of,
&pattern, &min_length, &max_length, &tz,
&title, &description, &examples, &extra_json_schema,
&extra
)
)
return NULL;
#define NONE_TO_NULL(x) do { if (x == Py_None) {x = NULL;} } while(0)
NONE_TO_NULL(gt);
NONE_TO_NULL(ge);
NONE_TO_NULL(lt);
NONE_TO_NULL(le);
NONE_TO_NULL(multiple_of);
NONE_TO_NULL(pattern);
NONE_TO_NULL(min_length);
NONE_TO_NULL(max_length);
NONE_TO_NULL(tz);
NONE_TO_NULL(title);
NONE_TO_NULL(description);
NONE_TO_NULL(examples);
NONE_TO_NULL(extra_json_schema);
NONE_TO_NULL(extra);
#undef NONE_TO_NULL
/* Check parameter types/values */
if (gt != NULL && !ensure_is_finite_numeric(gt, "gt", false)) return NULL;
if (ge != NULL && !ensure_is_finite_numeric(ge, "ge", false)) return NULL;
if (lt != NULL && !ensure_is_finite_numeric(lt, "lt", false)) return NULL;
if (le != NULL && !ensure_is_finite_numeric(le, "le", false)) return NULL;
if (multiple_of != NULL && !ensure_is_finite_numeric(multiple_of, "multiple_of", true)) return NULL;
if (pattern != NULL && !ensure_is_string(pattern, "pattern")) return NULL;
if (min_length != NULL && !ensure_is_nonnegative_integer(min_length, "min_length")) return NULL;
if (max_length != NULL && !ensure_is_nonnegative_integer(max_length, "max_length")) return NULL;
if (tz != NULL && !ensure_is_bool(tz, "tz")) return NULL;
/* Check multiple constraint restrictions */
if (gt != NULL && ge != NULL) {
PyErr_SetString(PyExc_ValueError, "Cannot specify both `gt` and `ge`");
return NULL;
}
if (lt != NULL && le != NULL) {
PyErr_SetString(PyExc_ValueError, "Cannot specify both `lt` and `le`");
return NULL;
}
bool numeric = (gt != NULL || ge != NULL || lt != NULL || le != NULL || multiple_of != NULL);
bool other = (pattern != NULL || min_length != NULL || max_length != NULL || tz != NULL);
if (numeric && other) {
PyErr_SetString(
PyExc_ValueError,
"Cannot mix numeric constraints (gt, lt, ...) with non-numeric "
"constraints (pattern, min_length, max_length, tz)"
);
return NULL;
}
/* Check types/values of extra metadata */
if (title != NULL && !ensure_is_string(title, "title")) return NULL;
if (description != NULL && !ensure_is_string(description, "description")) return NULL;
if (examples != NULL && !PyList_CheckExact(examples)) {
PyErr_Format(
PyExc_TypeError,
"`examples` must be a list, got %.200s",
Py_TYPE(examples)->tp_name
);
return NULL;
}
if (extra_json_schema != NULL && !PyDict_CheckExact(extra_json_schema)) {
PyErr_Format(
PyExc_TypeError,
"`extra_json_schema` must be a dict, got %.200s",
Py_TYPE(extra_json_schema)->tp_name
);
return NULL;
}
if (extra != NULL && !PyDict_CheckExact(extra)) {
PyErr_Format(
PyExc_TypeError,
"`extra` must be a dict, got %.200s",
Py_TYPE(extra)->tp_name
);
return NULL;
}
/* regex compile pattern if provided */
if (pattern != NULL) {
MsgspecState *mod = msgspec_get_global_state();
regex = PyObject_CallOneArg(mod->re_compile, pattern);
if (regex == NULL) return NULL;
}
Meta *out = (Meta *)Meta_Type.tp_alloc(&Meta_Type, 0);
if (out == NULL) return NULL;
#define SET_FIELD(x) do { Py_XINCREF(x); out->x = x; } while(0)
SET_FIELD(gt);
SET_FIELD(ge);
SET_FIELD(lt);
SET_FIELD(le);
SET_FIELD(multiple_of);
SET_FIELD(pattern);
SET_FIELD(regex);
SET_FIELD(min_length);
SET_FIELD(max_length);
SET_FIELD(tz);
SET_FIELD(title);
SET_FIELD(description);
SET_FIELD(examples);
SET_FIELD(extra_json_schema);
SET_FIELD(extra);
#undef SET_FIELD
return (PyObject *)out;
}
static int
Meta_traverse(Meta *self, visitproc visit, void *arg) {
Py_VISIT(self->regex);
Py_VISIT(self->examples);
Py_VISIT(self->extra_json_schema);
Py_VISIT(self->extra);
return 0;
}
static int
Meta_clear(Meta *self) {
Py_CLEAR(self->gt);
Py_CLEAR(self->ge);
Py_CLEAR(self->lt);
Py_CLEAR(self->le);
Py_CLEAR(self->multiple_of);
Py_CLEAR(self->pattern);
Py_CLEAR(self->regex);
Py_CLEAR(self->min_length);
Py_CLEAR(self->max_length);
Py_CLEAR(self->tz);
Py_CLEAR(self->title);
Py_CLEAR(self->description);
Py_CLEAR(self->examples);
Py_CLEAR(self->extra_json_schema);
Py_CLEAR(self->extra);
return 0;
}
static void
Meta_dealloc(Meta *self) {
PyObject_GC_UnTrack(self);
Meta_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static bool
_meta_repr_part(strbuilder *builder, const char *prefix, Py_ssize_t prefix_size, PyObject *field, bool *first) {
if (*first) {
*first = false;
}
else {
if (!strbuilder_extend_literal(builder, ", ")) return false;
}
if (!strbuilder_extend(builder, prefix, prefix_size)) return false;
PyObject *repr = PyObject_Repr(field);
if (repr == NULL) return false;
bool ok = strbuilder_extend_unicode(builder, repr);
Py_DECREF(repr);
return ok;
}
static PyObject *
Meta_repr(Meta *self) {
strbuilder builder = {0};
bool first = true;
if (!strbuilder_extend_literal(&builder, "msgspec.Meta(")) return NULL;
/* sizeof(#field) is the length of the field name + 1 (null terminator). We
* want the length of field name + 1 (for the `=`). */
#define DO_REPR(field) do { \
if (self->field != NULL) { \
if (!_meta_repr_part(&builder, #field "=", sizeof(#field), self->field, &first)) { \
goto error; \
} \
} \
} while(0)
DO_REPR(gt);
DO_REPR(ge);
DO_REPR(lt);
DO_REPR(le);
DO_REPR(multiple_of);
DO_REPR(pattern);
DO_REPR(min_length);
DO_REPR(max_length);
DO_REPR(tz);
DO_REPR(title);
DO_REPR(description);
DO_REPR(examples);
DO_REPR(extra_json_schema);
DO_REPR(extra);
#undef DO_REPR
if (!strbuilder_extend_literal(&builder, ")")) goto error;
return strbuilder_build(&builder);
error:
strbuilder_reset(&builder);
return NULL;
}
static PyObject *
Meta_rich_repr(PyObject *py_self, PyObject *args) {
Meta *self = (Meta *)py_self;
PyObject *out = PyList_New(0);
if (out == NULL) goto error;
#define DO_REPR(field) do { \
if (self->field != NULL) { \
PyObject *part = Py_BuildValue("(UO)", #field, self->field); \
if (part == NULL || (PyList_Append(out, part) < 0)) goto error;\
} } while(0)
DO_REPR(gt);
DO_REPR(ge);
DO_REPR(lt);
DO_REPR(le);
DO_REPR(multiple_of);
DO_REPR(pattern);
DO_REPR(min_length);
DO_REPR(max_length);
DO_REPR(tz);
DO_REPR(title);
DO_REPR(description);
DO_REPR(examples);
DO_REPR(extra_json_schema);
DO_REPR(extra);
#undef DO_REPR
return out;
error:
Py_XDECREF(out);
return NULL;
}
static int
_meta_richcompare_part(PyObject *left, PyObject *right) {
if ((left == NULL) != (right == NULL)) {
return 0;
}
if (left != NULL) {
return PyObject_RichCompareBool(left, right, Py_EQ);
}
else {
return 1;
}
}
static PyObject *
Meta_richcompare(Meta *self, PyObject *py_other, int op) {
int equal = 1;
PyObject *out;
if (Py_TYPE(py_other) != &Meta_Type) {
Py_RETURN_NOTIMPLEMENTED;
}
if (!(op == Py_EQ || op == Py_NE)) {
Py_RETURN_NOTIMPLEMENTED;
}
Meta *other = (Meta *)py_other;
/* Only need to loop if self is not other` */
if (MS_LIKELY(self != other)) {
#define DO_COMPARE(field) do { \
equal = _meta_richcompare_part(self->field, other->field); \
if (equal < 0) return NULL; \
if (!equal) goto done; \
} while (0)
DO_COMPARE(gt);
DO_COMPARE(ge);
DO_COMPARE(lt);
DO_COMPARE(le);
DO_COMPARE(multiple_of);
DO_COMPARE(pattern);
DO_COMPARE(min_length);
DO_COMPARE(max_length);
DO_COMPARE(tz);
DO_COMPARE(title);
DO_COMPARE(description);
DO_COMPARE(examples);
DO_COMPARE(extra_json_schema);
DO_COMPARE(extra);
}
#undef DO_COMPARE
done:
if (op == Py_EQ) {
out = equal ? Py_True : Py_False;
}
else {
out = (!equal) ? Py_True : Py_False;
}
Py_INCREF(out);
return out;
}
static Py_hash_t
Meta_hash(Meta *self) {
Py_ssize_t nfields = 0;
Py_uhash_t acc = MS_HASH_XXPRIME_5;
#define DO_HASH(field) \
if (self->field != NULL) { \
Py_uhash_t lane = PyObject_Hash(self->field); \
if (lane == (Py_uhash_t)-1) return -1; \
acc += lane * MS_HASH_XXPRIME_2; \
acc = MS_HASH_XXROTATE(acc); \
acc *= MS_HASH_XXPRIME_1; \
nfields += 1; \
}
DO_HASH(gt);
DO_HASH(ge);
DO_HASH(lt);
DO_HASH(le);
DO_HASH(multiple_of);
DO_HASH(pattern);
DO_HASH(min_length);
DO_HASH(max_length);
DO_HASH(tz);
DO_HASH(title);
DO_HASH(description);
/* Leave out examples & description, since they could be unhashable */
#undef DO_HASH
acc += nfields ^ (MS_HASH_XXPRIME_5 ^ 3527539UL);
return (acc == (Py_uhash_t)-1) ? 1546275796 : acc;
}
static PyMethodDef Meta_methods[] = {
{"__rich_repr__", Meta_rich_repr, METH_NOARGS, "rich repr"},
{NULL, NULL},
};
static PyMemberDef Meta_members[] = {
{"gt", T_OBJECT, offsetof(Meta, gt), READONLY, NULL},
{"ge", T_OBJECT, offsetof(Meta, ge), READONLY, NULL},
{"lt", T_OBJECT, offsetof(Meta, lt), READONLY, NULL},
{"le", T_OBJECT, offsetof(Meta, le), READONLY, NULL},
{"multiple_of", T_OBJECT, offsetof(Meta, multiple_of), READONLY, NULL},
{"pattern", T_OBJECT, offsetof(Meta, pattern), READONLY, NULL},
{"min_length", T_OBJECT, offsetof(Meta, min_length), READONLY, NULL},
{"max_length", T_OBJECT, offsetof(Meta, max_length), READONLY, NULL},
{"tz", T_OBJECT, offsetof(Meta, tz), READONLY, NULL},
{"title", T_OBJECT, offsetof(Meta, title), READONLY, NULL},
{"description", T_OBJECT, offsetof(Meta, description), READONLY, NULL},
{"examples", T_OBJECT, offsetof(Meta, examples), READONLY, NULL},
{"extra_json_schema", T_OBJECT, offsetof(Meta, extra_json_schema), READONLY, NULL},
{"extra", T_OBJECT, offsetof(Meta, extra), READONLY, NULL},
{NULL},
};
static PyTypeObject Meta_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec.Meta",
.tp_doc = Meta__doc__,
.tp_basicsize = sizeof(Meta),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_new = Meta_new,
.tp_traverse = (traverseproc) Meta_traverse,
.tp_clear = (inquiry) Meta_clear,
.tp_dealloc = (destructor) Meta_dealloc,
.tp_methods = Meta_methods,
.tp_members = Meta_members,
.tp_repr = (reprfunc) Meta_repr,
.tp_richcompare = (richcmpfunc) Meta_richcompare,
.tp_hash = (hashfunc) Meta_hash
};
/*************************************************************************
* NODEFAULT singleton *
*************************************************************************/
PyObject _NoDefault_Object;
#define NODEFAULT &_NoDefault_Object
PyDoc_STRVAR(nodefault__doc__,
"NoDefaultType()\n"
"--\n"
"\n"
"A singleton indicating no default value is configured."
);
static PyObject *
nodefault_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
PyErr_SetString(PyExc_TypeError, "NoDefaultType takes no arguments");
return NULL;
}
Py_INCREF(NODEFAULT);
return NODEFAULT;
}
static PyObject *
nodefault_repr(PyObject *op)
{
return PyUnicode_FromString("NODEFAULT");
}
static PyObject *
nodefault_reduce(PyObject *op, PyObject *args)
{
return PyUnicode_FromString("NODEFAULT");
}
static PyMethodDef nodefault_methods[] = {
{"__reduce__", nodefault_reduce, METH_NOARGS, NULL},
{NULL, NULL}
};
PyTypeObject NoDefault_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.NoDefaultType",
.tp_doc = nodefault__doc__,
.tp_repr = nodefault_repr,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_methods = nodefault_methods,
.tp_new = nodefault_new,
.tp_dealloc = 0,
.tp_itemsize = 0,
.tp_basicsize = 0
};
#if PY312_PLUS
PyObject _NoDefault_Object = {
_PyObject_EXTRA_INIT
{ MS_IMMORTAL_INITIAL_REFCNT },
&NoDefault_Type
};
#else
PyObject _NoDefault_Object = {1, &NoDefault_Type};
#endif
/*************************************************************************
* UNSET singleton *
*************************************************************************/
PyObject _Unset_Object;
#define UNSET &_Unset_Object
PyDoc_STRVAR(unset__doc__,
"UnsetType()\n"
"--\n"
"\n"
"A singleton indicating a field value is unset.\n"
"\n"
"This may be useful for working with message schemas where an unset field\n"
"in an object needs to be treated differently than one containing an explicit\n"
"``None`` value. In this case, you may use ``UNSET`` as the default value,\n"
"rather than ``None`` when defining object schemas. This feature is supported\n"
"for any `msgspec.Struct`, `dataclasses` or `attrs` types.\n"
"\n"
"Examples\n"
"--------\n"
">>> from msgspec import Struct, UnsetType, UNSET, json\n"
">>> class Example(Struct):\n"
"... x: int\n"
"... y: int | None | UnsetType = UNSET\n"
"\n"
"During encoding, any field containing ``UNSET`` is omitted from the message.\n"
"\n"
">>> json.encode(Example(1))\n"
"b'{\"x\":1}'\n"
">>> json.encode(Example(1, 2))\n"
"b'{\"x\":1,\"y\":2}'\n"
"\n"
"During decoding, if a field isn't explicitly set in the message, the default\n"
"value of ``UNSET`` will be set instead. This lets downstream consumers\n"
"determine whether a field was left unset, or explicitly set to ``None``\n"
"\n"
">>> json.decode(b'{\"x\": 1}', type=Example) # unset\n"
"Example(x=1, y=UNSET)\n"
">>> json.decode(b'{\"x\": 1, \"y\": null}', type=Example) # explicit null\n"
"Example(x=1, y=None)\n"
">>> json.decode(b'{\"x\": 1, \"y\": 2}', type=Example) # explicit value\n"
"Example(x=1, y=2)"
);
static PyObject *
unset_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
PyErr_SetString(PyExc_TypeError, "UnsetType takes no arguments");
return NULL;
}
Py_INCREF(UNSET);
return UNSET;
}
static PyObject *
unset_repr(PyObject *op)
{
return PyUnicode_FromString("UNSET");
}
static PyObject *
unset_reduce(PyObject *op, PyObject *args)
{
return PyUnicode_FromString("UNSET");
}
static PyMethodDef unset_methods[] = {
{"__reduce__", unset_reduce, METH_NOARGS, NULL},
{NULL, NULL}
};
static int unset_bool(PyObject *obj) {
return 0;
};
static PyNumberMethods unset_as_number = {
.nb_bool = unset_bool,
};
PyTypeObject Unset_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec.UnsetType",
.tp_doc = unset__doc__,
.tp_repr = unset_repr,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_methods = unset_methods,
.tp_as_number = &unset_as_number,
.tp_new = unset_new,
.tp_dealloc = 0,
.tp_itemsize = 0,
.tp_basicsize = 0
};
#if PY312_PLUS
PyObject _Unset_Object = {
_PyObject_EXTRA_INIT
{ MS_IMMORTAL_INITIAL_REFCNT },
&Unset_Type
};
#else
PyObject _Unset_Object = {1, &Unset_Type};
#endif
/*************************************************************************
* Factory *
*************************************************************************/
static PyTypeObject Factory_Type;
typedef struct {
PyObject_HEAD
PyObject *factory;
} Factory;
static PyObject *
Factory_New(PyObject *factory) {
if (!PyCallable_Check(factory)) {
PyErr_SetString(PyExc_TypeError, "default_factory must be callable");
return NULL;
}
Factory *out = (Factory *)Factory_Type.tp_alloc(&Factory_Type, 0);
if (out == NULL) return NULL;
Py_INCREF(factory);
out->factory = factory;
return (PyObject *)out;
}
static PyObject *
Factory_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
Py_ssize_t nkwargs = (kwargs == NULL) ? 0 : PyDict_GET_SIZE(kwargs);
Py_ssize_t nargs = PyTuple_GET_SIZE(args);
if (nkwargs != 0) {
PyErr_SetString(PyExc_TypeError, "Factory takes no keyword arguments");
return NULL;
}
else if (nargs != 1) {
PyErr_Format(
PyExc_TypeError,
"Factory expected 1 argument, got %zd",
nargs
);
return NULL;
}
else {
return Factory_New(PyTuple_GET_ITEM(args, 0));
}
}
static PyObject *
Factory_Call(PyObject *self) {
PyObject *factory = ((Factory *)(self))->factory;
/* Inline two common factory types */
if (factory == (PyObject *)(&PyList_Type)) {
return PyList_New(0);
}
else if (factory == (PyObject *)(&PyDict_Type)) {
return PyDict_New();
}
return PyObject_CallNoArgs(factory);
}
static PyObject *
Factory_repr(PyObject *op)
{
return PyUnicode_FromString("<factory>");
}
static int
Factory_traverse(Factory *self, visitproc visit, void *arg)
{
Py_VISIT(self->factory);
return 0;
}
static int
Factory_clear(Factory *self)
{
Py_CLEAR(self->factory);
return 0;
}
static void
Factory_dealloc(Factory *self)
{
PyObject_GC_UnTrack(self);
Factory_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyMemberDef Factory_members[] = {
{"factory", T_OBJECT_EX, offsetof(Factory, factory), READONLY, "The factory function"},
{NULL},
};
static PyTypeObject Factory_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.Factory",
.tp_basicsize = sizeof(Factory),
.tp_itemsize = 0,
.tp_new = Factory_new,
.tp_repr = Factory_repr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_clear = (inquiry)Factory_clear,
.tp_traverse = (traverseproc)Factory_traverse,
.tp_dealloc = (destructor) Factory_dealloc,
.tp_members = Factory_members,
};
/*************************************************************************
* Field *
*************************************************************************/
static PyTypeObject Field_Type;
typedef struct {
PyObject_HEAD
PyObject *default_value;
PyObject *default_factory;
PyObject *name;
} Field;
PyDoc_STRVAR(Field__doc__,
"Configuration for a Struct field.\n"
"\n"
"Parameters\n"
"----------\n"
"default : Any, optional\n"
" A default value to use for this field.\n"
"default_factory : callable, optional\n"
" A zero-argument function called to generate a new default value\n"
" per-instance, rather than using a constant value as in ``default``.\n"
"name : str, optional\n"
" The name to use when encoding/decoding this field. If present, this\n"
" will override any struct-level configuration using the ``rename``\n"
" option for this field."
);
static PyObject *
Field_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
char *kwlist[] = {"default", "default_factory", "name", NULL};
PyObject *default_value = NODEFAULT, *default_factory = NODEFAULT;
PyObject *name = Py_None;
if (
!PyArg_ParseTupleAndKeywords(
args, kwargs, "|$OOO", kwlist,
&default_value, &default_factory, &name
)
) {
return NULL;
}
if (default_value != NODEFAULT && default_factory != NODEFAULT) {
PyErr_SetString(
PyExc_TypeError, "Cannot set both `default` and `default_factory`"
);
return NULL;
}
if (default_factory != NODEFAULT) {
if (!PyCallable_Check(default_factory)) {
PyErr_SetString(PyExc_TypeError, "default_factory must be callable");
return NULL;
}
}
if (name == Py_None) {
name = NULL;
}
else if (!PyUnicode_CheckExact(name)) {
PyErr_SetString(PyExc_TypeError, "name must be a str or None");
return NULL;
}
Field *self = (Field *)Field_Type.tp_alloc(&Field_Type, 0);
if (self == NULL) return NULL;
Py_INCREF(default_value);
self->default_value = default_value;
Py_INCREF(default_factory);
self->default_factory = default_factory;
Py_XINCREF(name);
self->name = name;
return (PyObject *)self;
}
static int
Field_traverse(Field *self, visitproc visit, void *arg)
{
Py_VISIT(self->default_value);
Py_VISIT(self->default_factory);
Py_VISIT(self->name);
return 0;
}
static int
Field_clear(Field *self)
{
Py_CLEAR(self->default_value);
Py_CLEAR(self->default_factory);
Py_CLEAR(self->name);
return 0;
}
static void
Field_dealloc(Field *self)
{
PyObject_GC_UnTrack(self);
Field_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyMemberDef Field_members[] = {
{
"default", T_OBJECT_EX, offsetof(Field, default_value), READONLY,
"The default value, or NODEFAULT if no default"
},
{
"default_factory", T_OBJECT_EX, offsetof(Field, default_factory), READONLY,
"The default_factory, or NODEFAULT if no default"
},
{
"name", T_OBJECT, offsetof(Field, name), READONLY,
"An alternative name to use when encoding/decoding this field"
},
{NULL},
};
static PyTypeObject Field_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.Field",
.tp_doc = Field__doc__,
.tp_basicsize = sizeof(Field),
.tp_itemsize = 0,
.tp_new = Field_new,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_clear = (inquiry)Field_clear,
.tp_traverse = (traverseproc)Field_traverse,
.tp_dealloc = (destructor) Field_dealloc,
.tp_members = Field_members,
};
/*************************************************************************
* AssocList & order handling *
*************************************************************************/
enum order_mode {
ORDER_SORTED = -1,
ORDER_DEFAULT = 0,
ORDER_DETERMINISTIC = 1,
ORDER_INVALID = 2,
};
static enum order_mode
parse_order_arg(PyObject *order) {
if (order == NULL || order == Py_None) {
return ORDER_DEFAULT;
}
else if (PyUnicode_CheckExact(order)) {
if (PyUnicode_CompareWithASCIIString(order, "deterministic") == 0) {
return ORDER_DETERMINISTIC;
}
else if (PyUnicode_CompareWithASCIIString(order, "sorted") == 0) {
return ORDER_SORTED;
}
}
PyErr_Format(
PyExc_ValueError,
"`order` must be one of `{None, 'deterministic', 'sorted'}`, got %R",
order
);
return ORDER_INVALID;
}
#define ASSOCLIST_SORT_CUTOFF 16
typedef struct {
const char *key;
Py_ssize_t key_size;
PyObject *val;
} AssocItem;
typedef struct {
Py_ssize_t size;
AssocItem items[];
} AssocList;
static AssocList *
AssocList_New(Py_ssize_t capacity) {
AssocList *out = PyMem_Malloc(sizeof(AssocList) + capacity * sizeof(AssocItem));
if (out == NULL) {
PyErr_NoMemory();
return NULL;
}
out->size = 0;
return out;
}
static void
AssocList_Free(AssocList *list) {
PyMem_Free(list);
}
static void
AssocList_AppendCStr(AssocList *list, const char *key, PyObject *val) {
list->items[list->size].key = key;
list->items[list->size].key_size = strlen(key);
list->items[list->size].val = val;
list->size++;
}
static int
AssocList_Append(AssocList *list, PyObject *key, PyObject *val) {
Py_ssize_t key_size;
const char* key_buf = unicode_str_and_size(key, &key_size);
if (key_buf == NULL) return -1;
list->items[list->size].key = key_buf;
list->items[list->size].key_size = key_size;
list->items[list->size].val = val;
list->size++;
return 0;
}
static AssocList *
AssocList_FromDict(PyObject *dict) {
Py_ssize_t len = PyDict_GET_SIZE(dict);
AssocList *out = AssocList_New(len);
PyObject *key, *val;
Py_ssize_t pos = 0;
while (PyDict_Next(dict, &pos, &key, &val)) {
if (!PyUnicode_Check(key)) {
PyErr_SetString(
PyExc_TypeError,
"Only dicts with str keys are supported when `order` is not `None`"
);
goto error;
}
if (AssocList_Append(out, key, val) < 0) goto error;
}
return out;
error:
AssocList_Free(out);
return NULL;
}
static inline int
_AssocItem_lt(AssocItem *left, AssocItem *right) {
int left_shorter = left->key_size < right->key_size;
int cmp = memcmp(
left->key, right->key, (left_shorter) ? left->key_size : right->key_size
);
return (cmp < 0) || ((cmp == 0) & left_shorter);
}
static Py_ssize_t
_AssocList_sort_partition(
AssocList* list, Py_ssize_t lo, Py_ssize_t hi, AssocItem *pivot
) {
Py_ssize_t i = lo - 1;
Py_ssize_t j = hi + 1;
while (true) {
while (_AssocItem_lt(pivot, &(list->items[--j])));
while (_AssocItem_lt(&(list->items[++i]), pivot));
if (i < j) {
AssocItem tmp = list->items[i];
list->items[i] = list->items[j];
list->items[j] = tmp;
}
else {
return j;
}
}
}
static void
_AssocList_sort_inner(AssocList* list, Py_ssize_t lo, Py_ssize_t hi) {
while (lo + ASSOCLIST_SORT_CUTOFF < hi) {
AssocItem *v1 = &(list->items[lo]);
AssocItem *v2 = &(list->items[hi]);
AssocItem *v3 = &(list->items[(lo + hi)/2]);
AssocItem pivot;
if (_AssocItem_lt(v1, v2)) {
if (_AssocItem_lt(v3, v1)) {
pivot = *v1;
}
else if (_AssocItem_lt(v2, v3)) {
pivot = *v2;
}
else {
pivot = *v3;
}
}
else {
if (_AssocItem_lt(v3, v2)) {
pivot = *v2;
}
else if (_AssocItem_lt(v1, v3)) {
pivot = *v1;
}
else {
pivot = *v3;
}
}
Py_ssize_t partition = _AssocList_sort_partition(list, lo, hi, &pivot);
_AssocList_sort_inner(list, lo, partition);
lo = partition + 1;
}
}
static void
AssocList_Sort(AssocList* list) {
if (list->size > ASSOCLIST_SORT_CUTOFF) {
_AssocList_sort_inner(list, 0, list->size - 1);
}
for (Py_ssize_t i = 1; i < list->size; i++) {
AssocItem val = list->items[i];
Py_ssize_t j = i;
while (j > 0 && _AssocItem_lt(&val, &(list->items[j - 1]))) {
list->items[j] = list->items[j - 1];
--j;
}
list->items[j] = val;
}
}
/*************************************************************************
* Struct, PathNode, and TypeNode Types *
*************************************************************************/
/* Types */
#define MS_TYPE_ANY (1ull << 0)
#define MS_TYPE_NONE (1ull << 1)
#define MS_TYPE_BOOL (1ull << 2)
#define MS_TYPE_INT (1ull << 3)
#define MS_TYPE_FLOAT (1ull << 4)
#define MS_TYPE_STR (1ull << 5)
#define MS_TYPE_BYTES (1ull << 6)
#define MS_TYPE_BYTEARRAY (1ull << 7)
#define MS_TYPE_MEMORYVIEW (1ull << 8)
#define MS_TYPE_DATETIME (1ull << 9)
#define MS_TYPE_DATE (1ull << 10)
#define MS_TYPE_TIME (1ull << 11)
#define MS_TYPE_TIMEDELTA (1ull << 12)
#define MS_TYPE_UUID (1ull << 13)
#define MS_TYPE_DECIMAL (1ull << 14)
#define MS_TYPE_EXT (1ull << 15)
#define MS_TYPE_STRUCT (1ull << 16)
#define MS_TYPE_STRUCT_ARRAY (1ull << 17)
#define MS_TYPE_STRUCT_UNION (1ull << 18)
#define MS_TYPE_STRUCT_ARRAY_UNION (1ull << 19)
#define MS_TYPE_ENUM (1ull << 20)
#define MS_TYPE_INTENUM (1ull << 21)
#define MS_TYPE_CUSTOM (1ull << 22)
#define MS_TYPE_CUSTOM_GENERIC (1ull << 23)
#define MS_TYPE_DICT ((1ull << 24) | (1ull << 25))
#define MS_TYPE_LIST (1ull << 26)
#define MS_TYPE_SET (1ull << 27)
#define MS_TYPE_FROZENSET (1ull << 28)
#define MS_TYPE_VARTUPLE (1ull << 29)
#define MS_TYPE_FIXTUPLE (1ull << 30)
#define MS_TYPE_INTLITERAL (1ull << 31)
#define MS_TYPE_STRLITERAL (1ull << 32)
#define MS_TYPE_TYPEDDICT (1ull << 33)
#define MS_TYPE_DATACLASS (1ull << 34)
#define MS_TYPE_NAMEDTUPLE (1ull << 35)
/* Constraints */
#define MS_CONSTR_INT_MIN (1ull << 42)
#define MS_CONSTR_INT_MAX (1ull << 43)
#define MS_CONSTR_INT_MULTIPLE_OF (1ull << 44)
#define MS_CONSTR_FLOAT_GT (1ull << 45)
#define MS_CONSTR_FLOAT_GE (1ull << 46)
#define MS_CONSTR_FLOAT_LT (1ull << 47)
#define MS_CONSTR_FLOAT_LE (1ull << 48)
#define MS_CONSTR_FLOAT_MULTIPLE_OF (1ull << 49)
#define MS_CONSTR_STR_REGEX (1ull << 50)
#define MS_CONSTR_STR_MIN_LENGTH (1ull << 51)
#define MS_CONSTR_STR_MAX_LENGTH (1ull << 52)
#define MS_CONSTR_BYTES_MIN_LENGTH (1ull << 53)
#define MS_CONSTR_BYTES_MAX_LENGTH (1ull << 54)
#define MS_CONSTR_ARRAY_MIN_LENGTH (1ull << 55)
#define MS_CONSTR_ARRAY_MAX_LENGTH (1ull << 56)
#define MS_CONSTR_MAP_MIN_LENGTH (1ull << 57)
#define MS_CONSTR_MAP_MAX_LENGTH (1ull << 58)
#define MS_CONSTR_TZ_AWARE (1ull << 59)
#define MS_CONSTR_TZ_NAIVE (1ull << 60)
/* Extra flag bit, used by TypedDict/dataclass implementations */
#define MS_EXTRA_FLAG (1ull << 63)
/* A TypeNode encodes information about all types at the same hierarchy in the
* type tree. They can encode both single types (`int`) and unions of types
* (`int | float | list[int]`). The encoding is optimized for the common case
* of simple scalar types (or unions of these types) with no constraints -
* these values only require a single uint64_t. More complicated types require
* extra *details* (`TypeDetail` objects) stored in a variable length array.
*
* The encoding is *compressed* - only fields that are set are stored. To know
* which fields are set, a bitmask of `types` is used, masking both the types
* and constraints set on the node.
*
* The order these details are stored is consistent, allowing the offset of a
* field to be computed using an efficient bitmask and popcount.
*
* The order is documented below:
*
* O | STRUCT | STRUCT_ARRAY | STRUCT_UNION | STRUCT_ARRAY_UNION | CUSTOM |
* O | INTENUM | INTLITERAL |
* O | ENUM | STRLITERAL |
* O | TYPEDDICT | DATACLASS |
* O | NAMEDTUPLE |
* O | STR_REGEX |
* T | DICT [key, value] |
* T | LIST | SET | FROZENSET | VARTUPLE |
* I | INT_MIN |
* I | INT_MAX |
* I | INT_MULTIPLE_OF |
* F | FLOAT_GT | FLOAT_GE |
* F | FLOAT_LT | FLOAT_LE |
* F | FLOAT_MULTIPLE_OF |
* S | STR_MIN_LENGTH |
* S | STR_MAX_LENGTH |
* S | BYTES_MIN_LENGTH |
* S | BYTES_MAX_LENGTH |
* S | ARRAY_MIN_LENGTH |
* S | ARRAY_MAX_LENGTH |
* S | MAP_MIN_LENGTH |
* S | MAP_MAX_LENGTH |
* T | FIXTUPLE [size, types ...] |
* */
#define SLOT_00 ( \
MS_TYPE_STRUCT | MS_TYPE_STRUCT_ARRAY | \
MS_TYPE_STRUCT_UNION | MS_TYPE_STRUCT_ARRAY_UNION | \
MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC \
)
#define SLOT_01 (MS_TYPE_INTENUM | MS_TYPE_INTLITERAL)
#define SLOT_02 (MS_TYPE_ENUM | MS_TYPE_STRLITERAL)
#define SLOT_03 (MS_TYPE_TYPEDDICT | MS_TYPE_DATACLASS)
#define SLOT_04 MS_TYPE_NAMEDTUPLE
#define SLOT_05 MS_CONSTR_STR_REGEX
#define SLOT_06 MS_TYPE_DICT
#define SLOT_07 (MS_TYPE_LIST | MS_TYPE_VARTUPLE | MS_TYPE_SET | MS_TYPE_FROZENSET)
#define SLOT_08 MS_CONSTR_INT_MIN
#define SLOT_09 MS_CONSTR_INT_MAX
#define SLOT_10 MS_CONSTR_INT_MULTIPLE_OF
#define SLOT_11 (MS_CONSTR_FLOAT_GE | MS_CONSTR_FLOAT_GT)
#define SLOT_12 (MS_CONSTR_FLOAT_LE | MS_CONSTR_FLOAT_LT)
#define SLOT_13 MS_CONSTR_FLOAT_MULTIPLE_OF
#define SLOT_14 MS_CONSTR_STR_MIN_LENGTH
#define SLOT_15 MS_CONSTR_STR_MAX_LENGTH
#define SLOT_16 MS_CONSTR_BYTES_MIN_LENGTH
#define SLOT_17 MS_CONSTR_BYTES_MAX_LENGTH
#define SLOT_18 MS_CONSTR_ARRAY_MIN_LENGTH
#define SLOT_19 MS_CONSTR_ARRAY_MAX_LENGTH
#define SLOT_20 MS_CONSTR_MAP_MIN_LENGTH
#define SLOT_21 MS_CONSTR_MAP_MAX_LENGTH
/* Common groups */
#define MS_INT_CONSTRS (SLOT_08 | SLOT_09 | SLOT_10)
#define MS_FLOAT_CONSTRS (SLOT_11 | SLOT_12 | SLOT_13)
#define MS_STR_CONSTRS (SLOT_05 | SLOT_14 | SLOT_15)
#define MS_BYTES_CONSTRS (SLOT_16 | SLOT_17)
#define MS_ARRAY_CONSTRS (SLOT_18 | SLOT_19)
#define MS_MAP_CONSTRS (SLOT_20 | SLOT_21)
#define MS_TIME_CONSTRS (MS_CONSTR_TZ_AWARE | MS_CONSTR_TZ_NAIVE)
typedef union TypeDetail {
int64_t i64;
double f64;
Py_ssize_t py_ssize_t;
void *pointer;
} TypeDetail;
typedef struct TypeNode {
uint64_t types;
TypeDetail details[];
} TypeNode;
/* A simple extension of TypeNode to allow for static allocation */
typedef struct {
uint64_t types;
TypeDetail details[1];
} TypeNodeSimple;
typedef struct {
PyObject_HEAD
PyObject *int_lookup;
PyObject *str_lookup;
bool literal_none;
} LiteralInfo;
typedef struct {
PyObject *key;
TypeNode *type;
} TypedDictField;
typedef struct {
PyObject_VAR_HEAD
Py_ssize_t nrequired;
TypedDictField fields[];
} TypedDictInfo;
typedef struct {
PyObject *key;
TypeNode *type;
} DataclassField;
typedef struct {
PyObject_VAR_HEAD
PyObject *class;
PyObject *pre_init;
PyObject *post_init;
PyObject *defaults;
DataclassField fields[];
} DataclassInfo;
typedef struct {
PyObject_VAR_HEAD
PyObject *class;
PyObject *defaults;
TypeNode *types[];
} NamedTupleInfo;
struct StructInfo;
typedef struct {
PyHeapTypeObject base;
PyObject *struct_fields;
PyObject *struct_defaults;
Py_ssize_t *struct_offsets;
PyObject *struct_encode_fields;
struct StructInfo *struct_info;
Py_ssize_t nkwonly;
Py_ssize_t n_trailing_defaults;
PyObject *struct_tag_field; /* str or NULL */
PyObject *struct_tag_value; /* str or NULL */
PyObject *struct_tag; /* True, str, or NULL */
PyObject *match_args;
PyObject *rename;
PyObject *post_init;
Py_ssize_t hash_offset; /* 0 for no caching, otherwise offset */
int8_t frozen;
int8_t order;
int8_t eq;
int8_t repr_omit_defaults;
int8_t array_like;
int8_t gc;
int8_t omit_defaults;
int8_t forbid_unknown_fields;
} StructMetaObject;
typedef struct StructInfo {
PyObject_VAR_HEAD
StructMetaObject *class;
TypeNode *types[];
} StructInfo;
typedef struct {
PyObject_HEAD
StructMetaObject *st_type;
} StructConfig;
static PyTypeObject LiteralInfo_Type;
static PyTypeObject TypedDictInfo_Type;
static PyTypeObject DataclassInfo_Type;
static PyTypeObject NamedTupleInfo_Type;
static PyTypeObject StructInfo_Type;
static PyTypeObject StructMetaType;
static PyTypeObject Ext_Type;
static TypeNode* TypeNode_Convert(PyObject *type);
static PyObject* StructInfo_Convert(PyObject*);
static PyObject* TypedDictInfo_Convert(PyObject*);
static PyObject* DataclassInfo_Convert(PyObject*);
static PyObject* NamedTupleInfo_Convert(PyObject*);
#define StructMeta_GET_FIELDS(s) (((StructMetaObject *)(s))->struct_fields)
#define StructMeta_GET_NFIELDS(s) (PyTuple_GET_SIZE((((StructMetaObject *)(s))->struct_fields)))
#define StructMeta_GET_DEFAULTS(s) (((StructMetaObject *)(s))->struct_defaults)
#define StructMeta_GET_OFFSETS(s) (((StructMetaObject *)(s))->struct_offsets)
#define OPT_UNSET -1
#define OPT_FALSE 0
#define OPT_TRUE 1
#define STRUCT_MERGE_OPTIONS(opt1, opt2) (((opt2) != OPT_UNSET) ? (opt2) : (opt1))
static MS_INLINE StructInfo *
TypeNode_get_struct_info(TypeNode *type) {
/* Struct types are always first */
return type->details[0].pointer;
}
static MS_INLINE Lookup *
TypeNode_get_struct_union(TypeNode *type) {
/* Struct union types are always first */
return type->details[0].pointer;
}
static MS_INLINE PyObject *
TypeNode_get_custom(TypeNode *type) {
/* Custom types can't be mixed with anything */
return type->details[0].pointer;
}
static MS_INLINE IntLookup *
TypeNode_get_int_enum_or_literal(TypeNode *type) {
Py_ssize_t i = ms_popcount(type->types & SLOT_00);
return type->details[i].pointer;
}
static MS_INLINE StrLookup *
TypeNode_get_str_enum_or_literal(TypeNode *type) {
Py_ssize_t i = ms_popcount(type->types & (SLOT_00 | SLOT_01));
return type->details[i].pointer;
}
static MS_INLINE TypedDictInfo *
TypeNode_get_typeddict_info(TypeNode *type) {
Py_ssize_t i = ms_popcount(type->types & (SLOT_00 | SLOT_01 | SLOT_02));
return type->details[i].pointer;
}
static MS_INLINE DataclassInfo *
TypeNode_get_dataclass_info(TypeNode *type) {
Py_ssize_t i = ms_popcount(type->types & (SLOT_00 | SLOT_01 | SLOT_02));
return type->details[i].pointer;
}
static MS_INLINE NamedTupleInfo *
TypeNode_get_namedtuple_info(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03
)
);
return type->details[i].pointer;
}
static MS_INLINE PyObject *
TypeNode_get_constr_str_regex(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04
)
);
return type->details[i].pointer;
}
static MS_INLINE void
TypeNode_get_dict(TypeNode *type, TypeNode **key, TypeNode **val) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05
)
);
*key = type->details[i].pointer;
*val = type->details[i + 1].pointer;
}
static MS_INLINE TypeNode *
TypeNode_get_array(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06
)
);
return type->details[i].pointer;
}
static MS_INLINE int64_t
TypeNode_get_constr_int_min(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07
)
);
return type->details[i].i64;
}
static MS_INLINE int64_t
TypeNode_get_constr_int_max(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08
)
);
return type->details[i].i64;
}
static MS_INLINE int64_t
TypeNode_get_constr_int_multiple_of(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09
)
);
return type->details[i].i64;
}
static MS_INLINE double
TypeNode_get_constr_float_min(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10
)
);
return type->details[i].f64;
}
static MS_INLINE double
TypeNode_get_constr_float_max(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11
)
);
return type->details[i].f64;
}
static MS_INLINE double
TypeNode_get_constr_float_multiple_of(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11 | SLOT_12
)
);
return type->details[i].f64;
}
static MS_INLINE Py_ssize_t
TypeNode_get_constr_str_min_length(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11 | SLOT_12 | SLOT_13
)
);
return type->details[i].py_ssize_t;
}
static MS_INLINE Py_ssize_t
TypeNode_get_constr_str_max_length(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11 | SLOT_12 | SLOT_13 | SLOT_14
)
);
return type->details[i].py_ssize_t;
}
static MS_INLINE Py_ssize_t
TypeNode_get_constr_bytes_min_length(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11 | SLOT_12 | SLOT_13 | SLOT_14 | SLOT_15
)
);
return type->details[i].py_ssize_t;
}
static MS_INLINE Py_ssize_t
TypeNode_get_constr_bytes_max_length(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11 | SLOT_12 | SLOT_13 | SLOT_14 | SLOT_15 |
SLOT_16
)
);
return type->details[i].py_ssize_t;
}
static MS_INLINE Py_ssize_t
TypeNode_get_constr_array_min_length(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11 | SLOT_12 | SLOT_13 | SLOT_14 | SLOT_15 |
SLOT_16 | SLOT_17
)
);
return type->details[i].py_ssize_t;
}
static MS_INLINE Py_ssize_t
TypeNode_get_constr_array_max_length(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11 | SLOT_12 | SLOT_13 | SLOT_14 | SLOT_15 |
SLOT_16 | SLOT_17 | SLOT_18
)
);
return type->details[i].py_ssize_t;
}
static MS_INLINE Py_ssize_t
TypeNode_get_constr_map_min_length(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11 | SLOT_12 | SLOT_13 | SLOT_14 | SLOT_15 |
SLOT_16 | SLOT_17 | SLOT_18 | SLOT_19
)
);
return type->details[i].py_ssize_t;
}
static MS_INLINE Py_ssize_t
TypeNode_get_constr_map_max_length(TypeNode *type) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11 | SLOT_12 | SLOT_13 | SLOT_14 | SLOT_15 |
SLOT_16 | SLOT_17 | SLOT_18 | SLOT_19 | SLOT_20
)
);
return type->details[i].py_ssize_t;
}
static MS_INLINE void
TypeNode_get_fixtuple(TypeNode *type, Py_ssize_t *offset, Py_ssize_t *size) {
Py_ssize_t i = ms_popcount(
type->types & (
SLOT_00 | SLOT_01 | SLOT_02 | SLOT_03 | SLOT_04 | SLOT_05 | SLOT_06 | SLOT_07 |
SLOT_08 | SLOT_09 | SLOT_10 | SLOT_11 | SLOT_12 | SLOT_13 | SLOT_14 | SLOT_15 |
SLOT_16 | SLOT_17 | SLOT_18 | SLOT_19 | SLOT_20 | SLOT_21
)
);
*size = type->details[i].py_ssize_t;
*offset = i + 1;
}
static void
TypeNode_get_traverse_ranges(
TypeNode *type, Py_ssize_t *n_objects, Py_ssize_t *n_typenode,
Py_ssize_t *fixtuple_offset, Py_ssize_t *fixtuple_size
) {
Py_ssize_t n_obj = 0, n_type = 0, ft_offset = 0, ft_size = 0;
/* Custom types cannot share a union with anything except `None` */
if (type->types & (MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC)) {
n_obj = 1;
}
else if (!(type->types & MS_TYPE_ANY)) {
/* Number of pyobject details */
n_obj = ms_popcount(
type->types & (
MS_TYPE_STRUCT | MS_TYPE_STRUCT_UNION |
MS_TYPE_STRUCT_ARRAY | MS_TYPE_STRUCT_ARRAY_UNION |
MS_TYPE_INTENUM | MS_TYPE_INTLITERAL |
MS_TYPE_ENUM | MS_TYPE_STRLITERAL |
MS_TYPE_TYPEDDICT | MS_TYPE_DATACLASS |
MS_TYPE_NAMEDTUPLE
)
);
/* Number of typenode details */
n_type = ms_popcount(
type->types & (
MS_TYPE_DICT |
MS_TYPE_LIST | MS_TYPE_SET | MS_TYPE_FROZENSET | MS_TYPE_VARTUPLE
)
);
if (type->types & MS_TYPE_FIXTUPLE) {
TypeNode_get_fixtuple(type, &ft_offset, &ft_size);
}
}
*n_objects = n_obj;
*n_typenode = n_type;
*fixtuple_offset = ft_offset;
*fixtuple_size = ft_size;
}
static void
TypeNode_Free(TypeNode *self) {
if (self == NULL) return;
Py_ssize_t n_obj, n_typenode, fixtuple_offset, fixtuple_size, i;
TypeNode_get_traverse_ranges(self, &n_obj, &n_typenode, &fixtuple_offset, &fixtuple_size);
for (i = 0; i < n_obj; i++) {
PyObject *obj = (PyObject *)(self->details[i].pointer);
Py_XDECREF(obj);
}
for (i = n_obj; i < (n_obj + n_typenode); i++) {
TypeNode *node = (TypeNode *)(self->details[i].pointer);
TypeNode_Free(node);
}
for (i = 0; i < fixtuple_size; i++) {
TypeNode *node = (TypeNode *)(self->details[i + fixtuple_offset].pointer);
TypeNode_Free(node);
}
PyMem_Free(self);
}
static int
TypeNode_traverse(TypeNode *self, visitproc visit, void *arg) {
if (self == NULL) return 0;
Py_ssize_t n_obj, n_typenode, fixtuple_offset, fixtuple_size, i;
TypeNode_get_traverse_ranges(self, &n_obj, &n_typenode, &fixtuple_offset, &fixtuple_size);
for (i = 0; i < n_obj; i++) {
PyObject *obj = (PyObject *)(self->details[i].pointer);
Py_VISIT(obj);
}
for (i = n_obj; i < (n_obj + n_typenode); i++) {
int out;
TypeNode *node = (TypeNode *)(self->details[i].pointer);
if ((out = TypeNode_traverse(node, visit, arg)) != 0) return out;
}
for (i = 0; i < fixtuple_size; i++) {
int out;
TypeNode *node = (TypeNode *)(self->details[i + fixtuple_offset].pointer);
if ((out = TypeNode_traverse(node, visit, arg)) != 0) return out;
}
return 0;
}
static PyObject *
typenode_simple_repr(TypeNode *self) {
strbuilder builder = {" | ", 3};
if (self->types & (MS_TYPE_ANY | MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC) || self->types == 0) {
return PyUnicode_FromString("any");
}
if (self->types & MS_TYPE_BOOL) {
if (!strbuilder_extend_literal(&builder, "bool")) return NULL;
}
if (self->types & (MS_TYPE_INT | MS_TYPE_INTENUM | MS_TYPE_INTLITERAL)) {
if (!strbuilder_extend_literal(&builder, "int")) return NULL;
}
if (self->types & MS_TYPE_FLOAT) {
if (!strbuilder_extend_literal(&builder, "float")) return NULL;
}
if (self->types & (MS_TYPE_STR | MS_TYPE_ENUM | MS_TYPE_STRLITERAL)) {
if (!strbuilder_extend_literal(&builder, "str")) return NULL;
}
if (self->types & (MS_TYPE_BYTES | MS_TYPE_BYTEARRAY | MS_TYPE_MEMORYVIEW)) {
if (!strbuilder_extend_literal(&builder, "bytes")) return NULL;
}
if (self->types & MS_TYPE_DATETIME) {
if (!strbuilder_extend_literal(&builder, "datetime")) return NULL;
}
if (self->types & MS_TYPE_DATE) {
if (!strbuilder_extend_literal(&builder, "date")) return NULL;
}
if (self->types & MS_TYPE_TIME) {
if (!strbuilder_extend_literal(&builder, "time")) return NULL;
}
if (self->types & MS_TYPE_TIMEDELTA) {
if (!strbuilder_extend_literal(&builder, "duration")) return NULL;
}
if (self->types & MS_TYPE_UUID) {
if (!strbuilder_extend_literal(&builder, "uuid")) return NULL;
}
if (self->types & MS_TYPE_DECIMAL) {
if (!strbuilder_extend_literal(&builder, "decimal")) return NULL;
}
if (self->types & MS_TYPE_EXT) {
if (!strbuilder_extend_literal(&builder, "ext")) return NULL;
}
if (self->types & (
MS_TYPE_STRUCT | MS_TYPE_STRUCT_UNION |
MS_TYPE_TYPEDDICT | MS_TYPE_DATACLASS | MS_TYPE_DICT
)
) {
if (!strbuilder_extend_literal(&builder, "object")) return NULL;
}
if (
self->types & (
MS_TYPE_STRUCT_ARRAY | MS_TYPE_STRUCT_ARRAY_UNION |
MS_TYPE_LIST | MS_TYPE_SET | MS_TYPE_FROZENSET |
MS_TYPE_VARTUPLE | MS_TYPE_FIXTUPLE | MS_TYPE_NAMEDTUPLE
)
) {
if (!strbuilder_extend_literal(&builder, "array")) return NULL;
}
if (self->types & MS_TYPE_NONE) {
if (!strbuilder_extend_literal(&builder, "null")) return NULL;
}
return strbuilder_build(&builder);
}
typedef struct {
PyObject *gt;
PyObject *ge;
PyObject *lt;
PyObject *le;
PyObject *multiple_of;
PyObject *regex;
PyObject *min_length;
PyObject *max_length;
PyObject *tz;
} Constraints;
typedef struct {
MsgspecState *mod;
PyObject *context;
uint64_t types;
PyObject *struct_obj;
PyObject *struct_info;
PyObject *structs_set;
PyObject *structs_lookup;
PyObject *intenum_obj;
PyObject *enum_obj;
PyObject *custom_obj;
PyObject *array_el_obj;
PyObject *dict_key_obj;
PyObject *dict_val_obj;
PyObject *typeddict_obj;
PyObject *dataclass_obj;
PyObject *namedtuple_obj;
PyObject *literals;
PyObject *literal_int_values;
PyObject *literal_int_lookup;
PyObject *literal_str_values;
PyObject *literal_str_lookup;
bool literal_none;
/* Constraints */
int64_t c_int_min;
int64_t c_int_max;
int64_t c_int_multiple_of;
double c_float_min;
double c_float_max;
double c_float_multiple_of;
PyObject *c_str_regex;
Py_ssize_t c_str_min_length;
Py_ssize_t c_str_max_length;
Py_ssize_t c_bytes_min_length;
Py_ssize_t c_bytes_max_length;
Py_ssize_t c_array_min_length;
Py_ssize_t c_array_max_length;
Py_ssize_t c_map_min_length;
Py_ssize_t c_map_max_length;
} TypeNodeCollectState;
static MS_INLINE bool
constraints_is_empty(Constraints *self) {
return (
self->gt == NULL &&
self->ge == NULL &&
self->lt == NULL &&
self->le == NULL &&
self->multiple_of == NULL &&
self->regex == NULL &&
self->min_length == NULL &&
self->max_length == NULL &&
self->tz == NULL
);
}
static int
_set_constraint(PyObject *source, PyObject **target, const char *name, PyObject *type) {
if (source == NULL) return 0;
if (*target == NULL) {
*target = source;
return 0;
}
PyErr_Format(
PyExc_TypeError,
"Multiple `Meta` annotations setting `%s` found, "
"type `%R` is invalid",
name, type
);
return -1;
}
static int
constraints_update(Constraints *self, Meta *meta, PyObject *type) {
#define set_constraint(field) do { \
if (_set_constraint(meta->field, &(self->field), #field, type) < 0) return -1; \
} while (0)
set_constraint(gt);
set_constraint(ge);
set_constraint(lt);
set_constraint(le);
set_constraint(multiple_of);
set_constraint(regex);
set_constraint(min_length);
set_constraint(max_length);
set_constraint(tz);
if (self->gt != NULL && self->ge != NULL) {
PyErr_Format(
PyExc_TypeError,
"Cannot set both `gt` and `ge` on the same annotated type, "
"type `%R` is invalid",
type
);
return -1;
}
if (self->lt != NULL && self->le != NULL) {
PyErr_Format(
PyExc_TypeError,
"Cannot set both `lt` and `le` on the same annotated type, "
"type `%R` is invalid",
type
);
return -1;
}
return 0;
#undef set_constraint
}
enum constraint_kind {
CK_INT = 0,
CK_FLOAT = 1,
CK_STR = 2,
CK_BYTES = 3,
CK_TIME = 4,
CK_ARRAY = 5,
CK_MAP = 6,
CK_OTHER = 7,
};
static int
err_invalid_constraint(const char *name, const char *kind, PyObject *obj) {
PyErr_Format(
PyExc_TypeError,
"Can only set `%s` on a %s type - type `%R` is invalid",
name, kind, obj
);
return -1;
}
static bool
_constr_as_i64(PyObject *obj, int64_t *target, int offset) {
int overflow;
int64_t x = PyLong_AsLongLongAndOverflow(obj, &overflow);
if (overflow != 0) {
PyErr_SetString(
PyExc_ValueError,
"Integer bounds constraints (`ge`, `le`, ...) that don't fit in an "
"int64 are currently not supported. If you need this feature, please "
"open an issue on GitHub"
);
return false;
}
else if (x == -1 && PyErr_Occurred()) {
return false;
}
/* Do offsets for lt/gt */
if (offset == -1) {
if (x == (-1LL << 63)) {
PyErr_SetString(PyExc_ValueError, "lt <= -2**63 is not supported");
return false;
}
x -= 1;
}
else if (offset == 1) {
if (x == ((1ULL << 63) - 1)) {
PyErr_SetString(PyExc_ValueError, "gt >= 2**63 - 1 is not supported");
return false;
}
x += 1;
}
*target = x;
return true;
}
static bool
_constr_as_f64(PyObject *obj, double *target, int offset) {
/* Use PyFloat_AsDouble to also handle integers */
double x = PyFloat_AsDouble(obj);
/* Should never be hit, types already checked */
if (x == -1.0 && PyErr_Occurred()) return false;
if (offset == 1) {
x = nextafter(x, DBL_MAX);
}
else if (offset == -1) {
x = nextafter(x, -DBL_MAX);
}
*target = x;
return true;
}
static bool
_constr_as_py_ssize_t(PyObject *obj, Py_ssize_t *target) {
Py_ssize_t x = PyLong_AsSsize_t(obj);
/* Should never be hit, types already checked */
if (x == -1 && PyErr_Occurred()) return false;
*target = x;
return true;
}
static int
typenode_collect_constraints(
TypeNodeCollectState *state,
Constraints *constraints,
enum constraint_kind kind,
PyObject *obj
) {
/* If no constraints, do nothing */
if (constraints == NULL) return 0;
if (constraints_is_empty(constraints)) return 0;
/* Check that the constraints are valid for the corresponding type */
if (kind != CK_INT && kind != CK_FLOAT) {
if (constraints->gt != NULL) return err_invalid_constraint("gt", "numeric", obj);
if (constraints->ge != NULL) return err_invalid_constraint("ge", "numeric", obj);
if (constraints->lt != NULL) return err_invalid_constraint("lt", "numeric", obj);
if (constraints->le != NULL) return err_invalid_constraint("le", "numeric", obj);
if (constraints->multiple_of != NULL) return err_invalid_constraint("multiple_of", "numeric", obj);
}
if (kind != CK_STR) {
if (constraints->regex != NULL) return err_invalid_constraint("pattern", "str", obj);
}
if (kind != CK_STR && kind != CK_BYTES && kind != CK_ARRAY && kind != CK_MAP) {
if (constraints->min_length != NULL) return err_invalid_constraint("min_length", "str, bytes, or collection", obj);
if (constraints->max_length != NULL) return err_invalid_constraint("max_length", "str, bytes, or collection", obj);
}
if (kind != CK_TIME) {
if (constraints->tz != NULL) return err_invalid_constraint("tz", "datetime or time", obj);
}
/* Next attempt to fill in the state. */
if (kind == CK_INT) {
if (constraints->gt != NULL) {
state->types |= MS_CONSTR_INT_MIN;
if (!_constr_as_i64(constraints->gt, &(state->c_int_min), 1)) return -1;
}
else if (constraints->ge != NULL) {
state->types |= MS_CONSTR_INT_MIN;
if (!_constr_as_i64(constraints->ge, &(state->c_int_min), 0)) return -1;
}
if (constraints->lt != NULL) {
state->types |= MS_CONSTR_INT_MAX;
if (!_constr_as_i64(constraints->lt, &(state->c_int_max), -1)) return -1;
}
else if (constraints->le != NULL) {
state->types |= MS_CONSTR_INT_MAX;
if (!_constr_as_i64(constraints->le, &(state->c_int_max), 0)) return -1;
}
if (constraints->multiple_of != NULL) {
state->types |= MS_CONSTR_INT_MULTIPLE_OF;
if (!_constr_as_i64(constraints->multiple_of, &(state->c_int_multiple_of), 0)) return -1;
}
}
else if (kind == CK_FLOAT) {
if (constraints->gt != NULL) {
state->types |= MS_CONSTR_FLOAT_GT;
if (!_constr_as_f64(constraints->gt, &(state->c_float_min), 1)) return -1;
}
else if (constraints->ge != NULL) {
state->types |= MS_CONSTR_FLOAT_GE;
if (!_constr_as_f64(constraints->ge, &(state->c_float_min), 0)) return -1;
}
if (constraints->lt != NULL) {
state->types |= MS_CONSTR_FLOAT_LT;
if (!_constr_as_f64(constraints->lt, &(state->c_float_max), -1)) return -1;
}
else if (constraints->le != NULL) {
state->types |= MS_CONSTR_FLOAT_LE;
if (!_constr_as_f64(constraints->le, &(state->c_float_max), 0)) return -1;
}
if (constraints->multiple_of != NULL) {
state->types |= MS_CONSTR_FLOAT_MULTIPLE_OF;
if (!_constr_as_f64(constraints->multiple_of, &(state->c_float_multiple_of), 0)) return -1;
}
}
else if (kind == CK_STR) {
if (constraints->regex != NULL) {
state->types |= MS_CONSTR_STR_REGEX;
Py_INCREF(constraints->regex);
state->c_str_regex = constraints->regex;
}
if (constraints->min_length != NULL) {
state->types |= MS_CONSTR_STR_MIN_LENGTH;
if (!_constr_as_py_ssize_t(constraints->min_length, &(state->c_str_min_length))) return -1;
}
if (constraints->max_length != NULL) {
state->types |= MS_CONSTR_STR_MAX_LENGTH;
if (!_constr_as_py_ssize_t(constraints->max_length, &(state->c_str_max_length))) return -1;
}
}
else if (kind == CK_BYTES) {
if (constraints->min_length != NULL) {
state->types |= MS_CONSTR_BYTES_MIN_LENGTH;
if (!_constr_as_py_ssize_t(constraints->min_length, &(state->c_bytes_min_length))) return -1;
}
if (constraints->max_length != NULL) {
state->types |= MS_CONSTR_BYTES_MAX_LENGTH;
if (!_constr_as_py_ssize_t(constraints->max_length, &(state->c_bytes_max_length))) return -1;
}
}
else if (kind == CK_TIME) {
if (constraints->tz != NULL) {
if (constraints->tz == Py_True) {
state->types |= MS_CONSTR_TZ_AWARE;
}
else {
state->types |= MS_CONSTR_TZ_NAIVE;
}
}
}
else if (kind == CK_ARRAY) {
if (constraints->min_length != NULL) {
state->types |= MS_CONSTR_ARRAY_MIN_LENGTH;
if (!_constr_as_py_ssize_t(constraints->min_length, &(state->c_array_min_length))) return -1;
}
if (constraints->max_length != NULL) {
state->types |= MS_CONSTR_ARRAY_MAX_LENGTH;
if (!_constr_as_py_ssize_t(constraints->max_length, &(state->c_array_max_length))) return -1;
}
}
else if (kind == CK_MAP) {
if (constraints->min_length != NULL) {
state->types |= MS_CONSTR_MAP_MIN_LENGTH;
if (!_constr_as_py_ssize_t(constraints->min_length, &(state->c_map_min_length))) return -1;
}
if (constraints->max_length != NULL) {
state->types |= MS_CONSTR_MAP_MAX_LENGTH;
if (!_constr_as_py_ssize_t(constraints->max_length, &(state->c_map_max_length))) return -1;
}
}
return 0;
}
static int typenode_collect_type(TypeNodeCollectState*, PyObject*);
static TypeNode *
typenode_from_collect_state(TypeNodeCollectState *state) {
Py_ssize_t e_ind, n_extra = 0, fixtuple_size = 0;
bool has_fixtuple = false;
n_extra = ms_popcount(
state->types & (
MS_TYPE_STRUCT | MS_TYPE_STRUCT_ARRAY |
MS_TYPE_STRUCT_UNION | MS_TYPE_STRUCT_ARRAY_UNION |
MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC |
MS_TYPE_INTENUM | MS_TYPE_INTLITERAL |
MS_TYPE_ENUM | MS_TYPE_STRLITERAL |
MS_TYPE_TYPEDDICT | MS_TYPE_DATACLASS |
MS_TYPE_NAMEDTUPLE |
MS_CONSTR_STR_REGEX |
MS_TYPE_DICT |
MS_TYPE_LIST | MS_TYPE_SET | MS_TYPE_FROZENSET | MS_TYPE_VARTUPLE |
MS_CONSTR_INT_MIN |
MS_CONSTR_INT_MAX |
MS_CONSTR_INT_MULTIPLE_OF |
MS_CONSTR_FLOAT_GT | MS_CONSTR_FLOAT_GE |
MS_CONSTR_FLOAT_LT | MS_CONSTR_FLOAT_LE |
MS_CONSTR_FLOAT_MULTIPLE_OF |
MS_CONSTR_STR_MIN_LENGTH |
MS_CONSTR_STR_MAX_LENGTH |
MS_CONSTR_BYTES_MIN_LENGTH |
MS_CONSTR_BYTES_MAX_LENGTH |
MS_CONSTR_ARRAY_MIN_LENGTH |
MS_CONSTR_ARRAY_MAX_LENGTH |
MS_CONSTR_MAP_MIN_LENGTH |
MS_CONSTR_MAP_MAX_LENGTH
)
);
if (state->types & MS_TYPE_FIXTUPLE) {
has_fixtuple = true;
fixtuple_size = PyTuple_GET_SIZE(state->array_el_obj);
n_extra += fixtuple_size + 1;
}
if (n_extra == 0) {
TypeNode *out = (TypeNode *)PyMem_Malloc(sizeof(TypeNode));
if (out == NULL) {
PyErr_NoMemory();
return NULL;
}
out->types = state->types;
return out;
}
/* Use calloc so that `out->details` is initialized, easing cleanup on error */
TypeNode *out = (TypeNode *)PyMem_Calloc(
1, sizeof(TypeNode) + n_extra * sizeof(TypeDetail)
);
if (out == NULL) {
PyErr_NoMemory();
return NULL;
}
out->types = state->types;
/* Populate `details` fields in order */
e_ind = 0;
if (state->custom_obj != NULL) {
Py_INCREF(state->custom_obj);
/* Add `Any` to the type node, so the individual decode functions can
* check for `Any` alone, and only have to handle custom types in one
* location (e.g. `mpack_decode`). */
out->types |= MS_TYPE_ANY;
out->details[e_ind++].pointer = state->custom_obj;
}
if (state->struct_info != NULL) {
Py_INCREF(state->struct_info);
out->details[e_ind++].pointer = state->struct_info;
}
if (state->structs_lookup != NULL) {
Py_INCREF(state->structs_lookup);
out->details[e_ind++].pointer = state->structs_lookup;
}
if (state->intenum_obj != NULL) {
PyObject *lookup = PyObject_GetAttr(state->intenum_obj, state->mod->str___msgspec_cache__);
if (lookup == NULL) {
/* IntLookup isn't created yet, create and store on enum class */
PyErr_Clear();
PyObject *member_map = PyObject_GetAttr(state->intenum_obj, state->mod->str__value2member_map_);
if (member_map == NULL) goto error;
lookup = IntLookup_New(member_map, NULL, state->intenum_obj, false);
Py_DECREF(member_map);
if (lookup == NULL) goto error;
if (PyObject_SetAttr(state->intenum_obj, state->mod->str___msgspec_cache__, lookup) < 0) {
Py_DECREF(lookup);
goto error;
}
}
else if (!Lookup_IsIntLookup(lookup)) {
/* the lookup attribute has been overwritten, error */
Py_DECREF(lookup);
PyErr_Format(
PyExc_RuntimeError,
"%R.__msgspec_cache__ has been overwritten",
state->intenum_obj
);
goto error;
}
out->details[e_ind++].pointer = lookup;
}
if (state->literal_int_lookup != NULL) {
Py_INCREF(state->literal_int_lookup);
out->details[e_ind++].pointer = state->literal_int_lookup;
}
if (state->enum_obj != NULL) {
PyObject *lookup = PyObject_GetAttr(state->enum_obj, state->mod->str___msgspec_cache__);
if (lookup == NULL) {
/* StrLookup isn't created yet, create and store on enum class */
PyErr_Clear();
PyObject *member_map = PyObject_GetAttr(state->enum_obj, state->mod->str__value2member_map_);
if (member_map == NULL) goto error;
lookup = StrLookup_New(member_map, NULL, state->enum_obj, false);
Py_DECREF(member_map);
if (lookup == NULL) goto error;
if (PyObject_SetAttr(state->enum_obj, state->mod->str___msgspec_cache__, lookup) < 0) {
Py_DECREF(lookup);
goto error;
}
}
else if (Py_TYPE(lookup) != &StrLookup_Type) {
/* the lookup attribute has been overwritten, error */
Py_DECREF(lookup);
PyErr_Format(
PyExc_RuntimeError,
"%R.__msgspec_cache__ has been overwritten",
state->enum_obj
);
goto error;
}
out->details[e_ind++].pointer = lookup;
}
if (state->literal_str_lookup != NULL) {
Py_INCREF(state->literal_str_lookup);
out->details[e_ind++].pointer = state->literal_str_lookup;
}
if (state->typeddict_obj != NULL) {
PyObject *info = TypedDictInfo_Convert(state->typeddict_obj);
if (info == NULL) goto error;
out->details[e_ind++].pointer = info;
}
if (state->dataclass_obj != NULL) {
PyObject *info = DataclassInfo_Convert(state->dataclass_obj);
if (info == NULL) goto error;
out->details[e_ind++].pointer = info;
}
if (state->namedtuple_obj != NULL) {
PyObject *info = NamedTupleInfo_Convert(state->namedtuple_obj);
if (info == NULL) goto error;
out->details[e_ind++].pointer = info;
}
if (state->types & MS_CONSTR_STR_REGEX) {
Py_INCREF(state->c_str_regex);
out->details[e_ind++].pointer = state->c_str_regex;
}
if (state->dict_key_obj != NULL) {
TypeNode *temp = TypeNode_Convert(state->dict_key_obj);
if (temp == NULL) goto error;
out->details[e_ind++].pointer = temp;
temp = TypeNode_Convert(state->dict_val_obj);
if (temp == NULL) goto error;
out->details[e_ind++].pointer = temp;
}
if (state->array_el_obj != NULL) {
if (has_fixtuple) {
out->details[e_ind++].py_ssize_t = fixtuple_size;
for (Py_ssize_t i = 0; i < fixtuple_size; i++) {
TypeNode *temp = TypeNode_Convert(
PyTuple_GET_ITEM(state->array_el_obj, i)
);
if (temp == NULL) goto error;
out->details[e_ind++].pointer = temp;
}
}
else {
TypeNode *temp = TypeNode_Convert(state->array_el_obj);
if (temp == NULL) goto error;
out->details[e_ind++].pointer = temp;
}
}
if (state->types & MS_CONSTR_INT_MIN) {
out->details[e_ind++].i64 = state->c_int_min;
}
if (state->types & MS_CONSTR_INT_MAX) {
out->details[e_ind++].i64 = state->c_int_max;
}
if (state->types & MS_CONSTR_INT_MULTIPLE_OF) {
out->details[e_ind++].i64 = state->c_int_multiple_of;
}
if (state->types & (MS_CONSTR_FLOAT_GT | MS_CONSTR_FLOAT_GE)) {
out->details[e_ind++].f64 = state->c_float_min;
}
if (state->types & (MS_CONSTR_FLOAT_LT | MS_CONSTR_FLOAT_LE)) {
out->details[e_ind++].f64 = state->c_float_max;
}
if (state->types & MS_CONSTR_FLOAT_MULTIPLE_OF) {
out->details[e_ind++].f64 = state->c_float_multiple_of;
}
if (state->types & MS_CONSTR_STR_MIN_LENGTH) {
out->details[e_ind++].py_ssize_t = state->c_str_min_length;
}
if (state->types & MS_CONSTR_STR_MAX_LENGTH) {
out->details[e_ind++].py_ssize_t = state->c_str_max_length;
}
if (state->types & MS_CONSTR_BYTES_MIN_LENGTH) {
out->details[e_ind++].py_ssize_t = state->c_bytes_min_length;
}
if (state->types & MS_CONSTR_BYTES_MAX_LENGTH) {
out->details[e_ind++].py_ssize_t = state->c_bytes_max_length;
}
if (state->types & MS_CONSTR_ARRAY_MIN_LENGTH) {
out->details[e_ind++].py_ssize_t = state->c_array_min_length;
}
if (state->types & MS_CONSTR_ARRAY_MAX_LENGTH) {
out->details[e_ind++].py_ssize_t = state->c_array_max_length;
}
if (state->types & MS_CONSTR_MAP_MIN_LENGTH) {
out->details[e_ind++].py_ssize_t = state->c_map_min_length;
}
if (state->types & MS_CONSTR_MAP_MAX_LENGTH) {
out->details[e_ind++].py_ssize_t = state->c_map_max_length;
}
return (TypeNode *)out;
error:
TypeNode_Free((TypeNode *)out);
return NULL;
}
static bool
get_msgspec_cache(MsgspecState *mod, PyObject *obj, PyTypeObject *type, PyObject **out) {
PyObject *cached = PyObject_GenericGetAttr(obj, mod->str___msgspec_cache__);
if (cached != NULL) {
if (Py_TYPE(cached) != type) {
Py_DECREF(cached);
PyErr_Format(
PyExc_RuntimeError,
"%R.__msgspec_cache__ has been overwritten",
obj
);
}
else {
*out = cached;
}
return true;
}
PyErr_Clear();
return false;
}
static int
typenode_collect_err_unique(TypeNodeCollectState *state, const char *kind) {
PyErr_Format(
PyExc_TypeError,
"Type unions may not contain more than one %s type - "
"type `%R` is not supported",
kind,
state->context
);
return -1;
}
static int
typenode_collect_check_invariants(TypeNodeCollectState *state) {
/* If a custom type is used, this node may only contain that type and `None */
if (
state->custom_obj != NULL &&
state->types & ~(MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC | MS_TYPE_NONE)
) {
PyErr_Format(
PyExc_TypeError,
"Type unions containing a custom type may not contain any "
"additional types other than `None` - type `%R` is not supported",
state->context
);
return -1;
}
/* Ensure at most one array-like type in the union */
if (ms_popcount(
state->types & (
MS_TYPE_STRUCT_ARRAY | MS_TYPE_STRUCT_ARRAY_UNION |
MS_TYPE_LIST | MS_TYPE_SET | MS_TYPE_FROZENSET |
MS_TYPE_VARTUPLE | MS_TYPE_FIXTUPLE | MS_TYPE_NAMEDTUPLE
)
) > 1
) {
PyErr_Format(
PyExc_TypeError,
"Type unions may not contain more than one array-like type "
"(`Struct(array_like=True)`, `list`, `set`, `frozenset`, `tuple`, "
"`NamedTuple`) - type `%R` is not supported",
state->context
);
return -1;
}
/* Ensure at most one dict-like type in the union */
int ndictlike = ms_popcount(
state->types & (
MS_TYPE_STRUCT | MS_TYPE_STRUCT_UNION |
MS_TYPE_TYPEDDICT | MS_TYPE_DATACLASS
)
);
if (state->types & MS_TYPE_DICT) {
ndictlike++;
}
if (ndictlike > 1) {
PyErr_Format(
PyExc_TypeError,
"Type unions may not contain more than one dict-like type "
"(`Struct`, `dict`, `TypedDict`, `dataclass`) - type `%R` "
"is not supported",
state->context
);
return -1;
}
/* If int & int literals are both present, drop literals */
if (state->types & MS_TYPE_INT && state->literal_int_lookup) {
state->types &= ~MS_TYPE_INTLITERAL;
Py_CLEAR(state->literal_int_lookup);
}
/* If str & str literals are both present, drop literals */
if (state->types & MS_TYPE_STR && state->literal_str_lookup) {
state->types &= ~MS_TYPE_STRLITERAL;
Py_CLEAR(state->literal_str_lookup);
}
/* Ensure int-like types don't conflict */
if (ms_popcount(state->types & (MS_TYPE_INT | MS_TYPE_INTLITERAL | MS_TYPE_INTENUM)) > 1) {
PyErr_Format(
PyExc_TypeError,
"Type unions may not contain more than one int-like type (`int`, "
"`Enum`, `Literal[int values]`) - type `%R` is not supported",
state->context
);
return -1;
}
/* Ensure str-like types don't conflict */
if (ms_popcount(
state->types & (
MS_TYPE_STR | MS_TYPE_STRLITERAL | MS_TYPE_ENUM |
MS_TYPE_BYTES | MS_TYPE_BYTEARRAY | MS_TYPE_MEMORYVIEW |
MS_TYPE_DATETIME | MS_TYPE_DATE | MS_TYPE_TIME |
MS_TYPE_TIMEDELTA | MS_TYPE_UUID | MS_TYPE_DECIMAL
)
) > 1
) {
PyErr_Format(
PyExc_TypeError,
"Type unions may not contain more than one str-like type (`str`, "
"`Enum`, `Literal[str values]`, `datetime`, `date`, `time`, `timedelta`, "
"`uuid`, `decimal`, `bytes`, `bytearray`) - type `%R` is not supported",
state->context
);
return -1;
}
return 0;
}
static int
typenode_collect_enum(TypeNodeCollectState *state, PyObject *obj) {
bool is_intenum;
if (PyType_IsSubtype((PyTypeObject *)obj, &PyLong_Type)) {
is_intenum = true;
}
else if (PyType_IsSubtype((PyTypeObject *)obj, &PyUnicode_Type)) {
is_intenum = false;
}
else {
PyObject *members = PyObject_GetAttr(obj, state->mod->str__value2member_map_);
if (members == NULL) return -1;
if (!PyDict_Check(members)) {
Py_DECREF(members);
PyErr_SetString(
PyExc_RuntimeError, "Expected _value2member_map_ to be a dict"
);
return -1;
}
/* Traverse _value2member_map_ to determine key type */
Py_ssize_t pos = 0;
PyObject *key;
bool all_ints = true;
bool all_strs = true;
while (PyDict_Next(members, &pos, &key, NULL)) {
all_ints &= PyLong_CheckExact(key);
all_strs &= PyUnicode_CheckExact(key);
}
Py_CLEAR(members);
if (all_ints) {
is_intenum = true;
}
else if (all_strs) {
is_intenum = false;
}
else {
PyErr_Format(
PyExc_TypeError,
"Enums must contain either all str or all int values - "
"type `%R` is not supported",
state->context
);
return -1;
}
}
if (is_intenum) {
if (state->intenum_obj != NULL) {
return typenode_collect_err_unique(state, "int enum");
}
state->types |= MS_TYPE_INTENUM;
Py_INCREF(obj);
state->intenum_obj = obj;
}
else {
if (state->enum_obj != NULL) {
return typenode_collect_err_unique(state, "str enum");
}
state->types |= MS_TYPE_ENUM;
Py_INCREF(obj);
state->enum_obj = obj;
}
return 0;
}
static int
typenode_collect_dict(TypeNodeCollectState *state, PyObject *key, PyObject *val) {
if (state->dict_key_obj != NULL) {
return typenode_collect_err_unique(state, "dict");
}
state->types |= MS_TYPE_DICT;
Py_INCREF(key);
state->dict_key_obj = key;
Py_INCREF(val);
state->dict_val_obj = val;
return 0;
}
static int
typenode_collect_array(TypeNodeCollectState *state, uint64_t type, PyObject *obj) {
if (state->array_el_obj != NULL) {
return typenode_collect_err_unique(
state, "array-like (list, set, tuple)"
);
}
state->types |= type;
Py_INCREF(obj);
state->array_el_obj = obj;
return 0;
}
static int
typenode_collect_custom(TypeNodeCollectState *state, uint64_t type, PyObject *obj) {
if (state->custom_obj != NULL) {
return typenode_collect_err_unique(state, "custom");
}
state->types |= type;
Py_INCREF(obj);
state->custom_obj = obj;
return 0;
}
static int
typenode_collect_typevar(TypeNodeCollectState *state, PyObject *obj) {
int out;
PyObject *bound = PyObject_GetAttr(obj, state->mod->str___bound__);
if (bound == NULL) return -1;
if (bound == Py_None) {
Py_DECREF(bound);
/* No `bound`, check for constraints */
PyObject *constraints = PyObject_GetAttr(obj, state->mod->str___constraints__);
if (constraints == NULL) return -1;
if (
!(
(constraints == Py_None) ||
(PyTuple_CheckExact(constraints) && (PyTuple_GET_SIZE(constraints) == 0))
)
) {
PyErr_Format(
PyExc_TypeError,
"Unbound TypeVar `%R` has constraints `%R` - constraints are "
"currently unsupported. If possible, either explicitly bind "
"the parameter, or use `bound` instead of constraints.",
obj, constraints
);
Py_DECREF(constraints);
return -1;
}
Py_DECREF(constraints);
/* No constraints either, use `Any` */
out = typenode_collect_type(state, state->mod->typing_any);
}
else {
/* Bound, substitute in the bound type */
out = typenode_collect_type(state, bound);
Py_DECREF(bound);
}
return out;
}
static int
typenode_collect_struct(TypeNodeCollectState *state, PyObject *obj) {
if (state->struct_obj == NULL && state->structs_set == NULL) {
/* First struct found, store it directly */
Py_INCREF(obj);
state->struct_obj = obj;
}
else {
if (state->structs_set == NULL) {
/* Second struct found, create a set and move the existing struct there */
state->structs_set = PyFrozenSet_New(NULL);
if (state->structs_set == NULL) return -1;
if (PySet_Add(state->structs_set, state->struct_obj) < 0) return -1;
Py_CLEAR(state->struct_obj);
}
if (PySet_Add(state->structs_set, obj) < 0) return -1;
}
return 0;
}
static int
typenode_collect_typeddict(TypeNodeCollectState *state, PyObject *obj) {
if (state->typeddict_obj != NULL) {
return typenode_collect_err_unique(state, "TypedDict");
}
state->types |= MS_TYPE_TYPEDDICT;
Py_INCREF(obj);
state->typeddict_obj = obj;
return 0;
}
static int
typenode_collect_dataclass(TypeNodeCollectState *state, PyObject *obj) {
if (state->dataclass_obj != NULL) {
return typenode_collect_err_unique(state, "dataclass or attrs");
}
state->types |= MS_TYPE_DATACLASS;
Py_INCREF(obj);
state->dataclass_obj = obj;
return 0;
}
static int
typenode_collect_namedtuple(TypeNodeCollectState *state, PyObject *obj) {
if (state->namedtuple_obj != NULL) {
return typenode_collect_err_unique(state, "NamedTuple");
}
state->types |= MS_TYPE_NAMEDTUPLE;
Py_INCREF(obj);
state->namedtuple_obj = obj;
return 0;
}
static int
typenode_collect_literal(TypeNodeCollectState *state, PyObject *literal) {
PyObject *args = PyObject_GetAttr(literal, state->mod->str___args__);
/* This should never happen, since we know this is a `Literal` object */
if (args == NULL) return -1;
Py_ssize_t size = PyTuple_GET_SIZE(args);
if (size < 0) return -1;
if (size == 0) {
PyErr_Format(
PyExc_TypeError,
"Literal types must have at least one item, %R is invalid",
literal
);
return -1;
}
for (Py_ssize_t i = 0; i < size; i++) {
PyObject *obj = PyTuple_GET_ITEM(args, i);
PyTypeObject *type = Py_TYPE(obj);
if (obj == Py_None || obj == NONE_TYPE) {
state->literal_none = true;
}
else if (type == &PyLong_Type) {
if (state->literal_int_values == NULL) {
state->literal_int_values = PySet_New(NULL);
if (state->literal_int_values == NULL) goto error;
}
if (PySet_Add(state->literal_int_values, obj) < 0) goto error;
}
else if (type == &PyUnicode_Type) {
if (state->literal_str_values == NULL) {
state->literal_str_values = PySet_New(NULL);
if (state->literal_str_values == NULL) goto error;
}
if (PySet_Add(state->literal_str_values, obj) < 0) goto error;
}
else {
/* Check for nested Literal */
PyObject *origin = PyObject_GetAttr(obj, state->mod->str___origin__);
if (origin == NULL) {
PyErr_Clear();
goto invalid;
}
else if (origin != state->mod->typing_literal) {
Py_DECREF(origin);
goto invalid;
}
Py_DECREF(origin);
if (typenode_collect_literal(state, obj) < 0) goto error;
}
}
Py_DECREF(args);
return 0;
invalid:
PyErr_Format(
PyExc_TypeError,
"Literal may only contain None/integers/strings - %R is not supported",
literal
);
error:
Py_DECREF(args);
return -1;
}
static int
typenode_collect_convert_literals(TypeNodeCollectState *state) {
if (state->literals == NULL) {
/* Nothing to do */
return 0;
}
Py_ssize_t n = PyList_GET_SIZE(state->literals);
if (n == 1) {
PyObject *literal = PyList_GET_ITEM(state->literals, 0);
PyObject *cached = NULL;
if (get_msgspec_cache(state->mod, literal, &LiteralInfo_Type, &cached)) {
if (cached == NULL) return -1;
LiteralInfo *info = (LiteralInfo *)cached;
if (info->int_lookup != NULL) {
state->types |= MS_TYPE_INTLITERAL;
Py_INCREF(info->int_lookup);
state->literal_int_lookup = info->int_lookup;
}
if (info->str_lookup != NULL) {
state->types |= MS_TYPE_STRLITERAL;
Py_INCREF(info->str_lookup);
state->literal_str_lookup = info->str_lookup;
}
if (info->literal_none) {
state->types |= MS_TYPE_NONE;
}
Py_DECREF(cached);
return 0;
}
}
/* Collect all values in all literals */
for (Py_ssize_t i = 0; i < n; i++) {
PyObject *literal = PyList_GET_ITEM(state->literals, i);
if (typenode_collect_literal(state, literal) < 0) return -1;
}
/* Convert values to lookup objects (if values exist for each type) */
if (state->literal_int_values != NULL) {
state->types |= MS_TYPE_INTLITERAL;
state->literal_int_lookup = IntLookup_New(
state->literal_int_values, NULL, NULL, false
);
if (state->literal_int_lookup == NULL) return -1;
}
if (state->literal_str_values != NULL) {
state->types |= MS_TYPE_STRLITERAL;
state->literal_str_lookup = StrLookup_New(
state->literal_str_values, NULL, NULL, false
);
if (state->literal_str_lookup == NULL) return -1;
}
if (state->literal_none) {
state->types |= MS_TYPE_NONE;
}
if (n == 1) {
/* A single `Literal` object, cache the lookups on it */
LiteralInfo *info = PyObject_GC_New(LiteralInfo, &LiteralInfo_Type);
if (info == NULL) return -1;
Py_XINCREF(state->literal_int_lookup);
info->int_lookup = state->literal_int_lookup;
Py_XINCREF(state->literal_str_lookup);
info->str_lookup = state->literal_str_lookup;
info->literal_none = state->literal_none;
PyObject_GC_Track(info);
PyObject *literal = PyList_GET_ITEM(state->literals, 0);
int status = PyObject_SetAttr(
literal, state->mod->str___msgspec_cache__, (PyObject *)info
);
Py_DECREF(info);
return status;
}
return 0;
}
static int
typenode_collect_convert_structs(TypeNodeCollectState *state) {
if (state->struct_obj == NULL && state->structs_set == NULL) {
return 0;
}
else if (state->struct_obj != NULL) {
/* Single struct */
state->struct_info = StructInfo_Convert(state->struct_obj);
if (state->struct_info == NULL) return -1;
if (((StructInfo *)state->struct_info)->class->array_like == OPT_TRUE) {
state->types |= MS_TYPE_STRUCT_ARRAY;
}
else {
state->types |= MS_TYPE_STRUCT;
}
return 0;
}
/* Multiple structs.
*
* Try looking the structs_set up in the cache first, to avoid building a
* new one below.
*/
PyObject *lookup = PyDict_GetItem(
state->mod->struct_lookup_cache, state->structs_set
);
if (lookup != NULL) {
/* Lookup was in the cache, update the state and return */
Py_INCREF(lookup);
state->structs_lookup = lookup;
if (Lookup_array_like(lookup)) {
state->types |= MS_TYPE_STRUCT_ARRAY_UNION;
}
else {
state->types |= MS_TYPE_STRUCT_UNION;
}
return 0;
}
/* Here we check a number of restrictions before building a lookup table
* from struct tags to their matching classes.
*
* Validation checks:
* - All structs in the set are tagged.
* - All structs in the set have the same `array_like` status
* - All structs in the set have the same `tag_field`
* - All structs in the set have a unique `tag_value`
*
* If any of these checks fails, an appropriate error is returned.
*/
PyObject *tag_mapping = NULL, *tag_field = NULL, *set_iter = NULL, *set_item = NULL;
PyObject *struct_info = NULL;
bool array_like = false;
bool tags_are_strings = true;
int status = -1;
tag_mapping = PyDict_New();
if (tag_mapping == NULL) goto cleanup;
set_iter = PyObject_GetIter(state->structs_set);
while ((set_item = PyIter_Next(set_iter))) {
struct_info = StructInfo_Convert(set_item);
if (struct_info == NULL) goto cleanup;
StructMetaObject *struct_type = ((StructInfo *)struct_info)->class;
PyObject *item_tag_field = struct_type->struct_tag_field;
PyObject *item_tag_value = struct_type->struct_tag_value;
bool item_array_like = struct_type->array_like == OPT_TRUE;
if (item_tag_value == NULL) {
PyErr_Format(
PyExc_TypeError,
"If a type union contains multiple Struct types, all Struct "
"types must be tagged (via `tag` or `tag_field` kwarg) - type "
"`%R` is not supported",
state->context
);
goto cleanup;
}
if (tag_field == NULL) {
array_like = struct_type->array_like == OPT_TRUE;
tag_field = struct_type->struct_tag_field;
tags_are_strings = PyUnicode_CheckExact(item_tag_value);
}
else {
if (array_like != item_array_like) {
PyErr_Format(
PyExc_TypeError,
"Type unions may not contain Struct types with `array_like=True` "
"and `array_like=False` - type `%R` is not supported",
state->context
);
goto cleanup;
}
if (tags_are_strings != PyUnicode_CheckExact(item_tag_value)) {
PyErr_Format(
PyExc_TypeError,
"Type unions may not contain Struct types with both `int` "
"and `str` tags - type `%R` is not supported",
state->context
);
goto cleanup;
}
int compare = PyUnicode_Compare(item_tag_field, tag_field);
if (compare == -1 && PyErr_Occurred()) goto cleanup;
if (compare != 0) {
PyErr_Format(
PyExc_TypeError,
"If a type union contains multiple Struct types, all Struct types "
"must have the same `tag_field` - type `%R` is not supported",
state->context
);
goto cleanup;
}
}
if (PyDict_GetItem(tag_mapping, item_tag_value) != NULL) {
PyErr_Format(
PyExc_TypeError,
"If a type union contains multiple Struct types, all Struct types "
"must have unique `tag` values - type `%R` is not supported",
state->context
);
goto cleanup;
}
int ok = PyDict_SetItem(tag_mapping, item_tag_value, struct_info) == 0;
Py_CLEAR(struct_info);
if (!ok) goto cleanup;
}
/* Build a lookup from tag_value -> struct_info */
if (tags_are_strings) {
lookup = StrLookup_New(tag_mapping, tag_field, NULL, array_like);
}
else {
lookup = IntLookup_New(tag_mapping, tag_field, NULL, array_like);
}
if (lookup == NULL) goto cleanup;
state->structs_lookup = lookup;
/* Check if the cache is full, if so clear the oldest item */
if (PyDict_GET_SIZE(state->mod->struct_lookup_cache) == 64) {
PyObject *key;
Py_ssize_t pos = 0;
if (PyDict_Next(state->mod->struct_lookup_cache, &pos, &key, NULL)) {
if (PyDict_DelItem(state->mod->struct_lookup_cache, key) < 0) {
goto cleanup;
}
}
}
/* Add the new lookup to the cache */
if (PyDict_SetItem(state->mod->struct_lookup_cache, state->structs_set, lookup) < 0) {
goto cleanup;
}
/* Update the `types` */
if (array_like) {
state->types |= MS_TYPE_STRUCT_ARRAY_UNION;
}
else {
state->types |= MS_TYPE_STRUCT_UNION;
}
status = 0;
cleanup:
Py_XDECREF(set_iter);
Py_XDECREF(tag_mapping);
Py_XDECREF(struct_info);
return status;
}
static void
typenode_collect_clear_state(TypeNodeCollectState *state) {
Py_CLEAR(state->struct_obj);
Py_CLEAR(state->struct_info);
Py_CLEAR(state->structs_set);
Py_CLEAR(state->structs_lookup);
Py_CLEAR(state->intenum_obj);
Py_CLEAR(state->enum_obj);
Py_CLEAR(state->custom_obj);
Py_CLEAR(state->array_el_obj);
Py_CLEAR(state->dict_key_obj);
Py_CLEAR(state->dict_val_obj);
Py_CLEAR(state->typeddict_obj);
Py_CLEAR(state->dataclass_obj);
Py_CLEAR(state->namedtuple_obj);
Py_CLEAR(state->literals);
Py_CLEAR(state->literal_int_values);
Py_CLEAR(state->literal_int_lookup);
Py_CLEAR(state->literal_str_values);
Py_CLEAR(state->literal_str_lookup);
Py_CLEAR(state->c_str_regex);
}
/* This decomposes an input type `obj`, stripping out any "wrapper" types
* (Annotated/NewType). It returns the following components:
*
* - `t` (return value): the first "concrete" type found in the type tree.
* - `origin`: `__origin__` on `t` (if present), with a few normalizations
* applied to work around differences in type spelling (List vs list) and
* python version.
* - `args`: `__args__` on `t` (if present)
* - `constraints`: Any constraints from `Meta` objects annotated on the type
*/
static PyObject *
typenode_origin_args_metadata(
TypeNodeCollectState *state, PyObject *obj,
PyObject **out_origin, PyObject **out_args, Constraints *constraints
) {
PyObject *origin = NULL, *args = NULL;
PyObject *t = obj;
Py_INCREF(t);
/* First strip out meta "wrapper" types (Annotated, NewType, Final) */
while (true) {
assert(t != NULL && origin == NULL && args == NULL);
/* Before inspecting attributes, try looking up the object in the
* abstract -> concrete mapping. If present, this is an unparametrized
* collection of some form. This helps avoid compatibility issues in
* Python 3.8, where unparametrized collections still have __args__. */
origin = PyDict_GetItemWithError(state->mod->concrete_types, t);
if (origin != NULL) {
Py_INCREF(origin);
break;
}
else {
/* Ignore all errors in this initial check */
PyErr_Clear();
}
/* If `t` is a type instance, no need to inspect further */
if (PyType_CheckExact(t)) {
/* t is a concrete type object. */
break;
}
origin = PyObject_GetAttr(t, state->mod->str___origin__);
if (origin != NULL) {
if (Py_TYPE(t) == (PyTypeObject *)(state->mod->typing_annotated_alias)) {
/* Handle typing.Annotated[...] */
PyObject *metadata = PyObject_GetAttr(t, state->mod->str___metadata__);
if (metadata == NULL) goto error;
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(metadata); i++) {
PyObject *annot = PyTuple_GET_ITEM(metadata, i);
if (Py_TYPE(annot) == &Meta_Type) {
if (constraints_update(constraints, (Meta *)annot, obj) < 0) {
Py_DECREF(metadata);
goto error;
}
}
}
Py_DECREF(metadata);
Py_DECREF(t);
t = origin;
origin = NULL;
continue;
}
else {
args = PyObject_GetAttr(t, state->mod->str___args__);
if (args != NULL) {
if (!PyTuple_Check(args)) {
PyErr_SetString(PyExc_TypeError, "__args__ must be a tuple");
goto error;
}
if (origin == state->mod->typing_final) {
/* Handle typing.Final[...] */
PyObject *temp = PyTuple_GetItem(args, 0);
if (temp == NULL) goto error;
Py_CLEAR(args);
Py_CLEAR(origin);
Py_DECREF(t);
Py_INCREF(temp);
t = temp;
continue;
}
/* Check for parametrized TypeAliasType if Python 3.12+ */
#if PY312_PLUS
if (Py_TYPE(origin) == (PyTypeObject *)(state->mod->typing_typealiastype)) {
PyObject *value = PyObject_GetAttr(origin, state->mod->str___value__);
if (value == NULL) goto error;
PyObject *temp = PyObject_GetItem(value, args);
Py_DECREF(value);
if (temp == NULL) goto error;
Py_CLEAR(args);
Py_CLEAR(origin);
Py_DECREF(t);
t = temp;
continue;
}
#endif
}
else {
/* Custom non-parametrized generics won't have __args__
* set. Ignore __args__ error */
PyErr_Clear();
}
/* Lookup __origin__ in the mapping, in case it's a supported
* abstract type. Equal to `origin = mapping.get(origin, origin)` */
PyObject *temp = PyDict_GetItem(state->mod->concrete_types, origin);
if (temp != NULL) {
Py_DECREF(origin);
Py_INCREF(temp);
origin = temp;
}
break;
}
}
else {
PyErr_Clear();
/* Check for NewType */
PyObject *supertype = PyObject_GetAttr(t, state->mod->str___supertype__);
if (supertype != NULL) {
/* It's a newtype, use the wrapped type and loop again */
Py_DECREF(t);
t = supertype;
continue;
}
PyErr_Clear();
/* Check for TypeAliasType if Python 3.12+ */
#if PY312_PLUS
if (Py_TYPE(t) == (PyTypeObject *)(state->mod->typing_typealiastype)) {
PyObject *value = PyObject_GetAttr(t, state->mod->str___value__);
if (value == NULL) goto error;
Py_DECREF(t);
t = value;
continue;
}
#endif
break;
}
}
#if PY310_PLUS
if (Py_TYPE(t) == (PyTypeObject *)(state->mod->types_uniontype)) {
/* Handle types.UnionType unions (`int | float | ...`) */
args = PyObject_GetAttr(t, state->mod->str___args__);
if (args == NULL) goto error;
origin = state->mod->typing_union;
Py_INCREF(origin);
}
#endif
*out_origin = origin;
*out_args = args;
return t;
error:
Py_XDECREF(t);
Py_XDECREF(origin);
Py_XDECREF(args);
return NULL;
}
static bool
is_namedtuple_class(TypeNodeCollectState *state, PyObject *t) {
return (
PyType_Check(t)
&& PyType_IsSubtype((PyTypeObject *)t, &PyTuple_Type)
&& PyObject_HasAttr(t, state->mod->str__fields)
);
}
static bool
is_typeddict_class(TypeNodeCollectState *state, PyObject *t) {
return (
PyType_Check(t)
&& PyType_IsSubtype((PyTypeObject *)t, &PyDict_Type)
&& PyObject_HasAttr(t, state->mod->str___total__)
);
}
static bool
is_dataclass_or_attrs_class(TypeNodeCollectState *state, PyObject *t) {
return (
PyType_Check(t) && (
PyObject_HasAttr(t, state->mod->str___dataclass_fields__) ||
PyObject_HasAttr(t, state->mod->str___attrs_attrs__)
)
);
}
static int
typenode_collect_type(TypeNodeCollectState *state, PyObject *obj) {
int out = 0;
PyObject *t = NULL, *origin = NULL, *args = NULL;
Constraints constraints = {0};
enum constraint_kind kind = CK_OTHER;
/* If `Any` type already encountered, nothing to do */
if (state->types & MS_TYPE_ANY) return 0;
t = typenode_origin_args_metadata(state, obj, &origin, &args, &constraints);
if (t == NULL) return -1;
if (t == state->mod->typing_any) {
/* Any takes precedence, drop all existing and update type flags */
typenode_collect_clear_state(state);
state->types = MS_TYPE_ANY;
}
else if (t == Py_None || t == NONE_TYPE) {
state->types |= MS_TYPE_NONE;
}
else if (t == (PyObject *)(&PyBool_Type)) {
state->types |= MS_TYPE_BOOL;
}
else if (t == (PyObject *)(&PyLong_Type)) {
state->types |= MS_TYPE_INT;
kind = CK_INT;
}
else if (t == (PyObject *)(&PyFloat_Type)) {
state->types |= MS_TYPE_FLOAT;
kind = CK_FLOAT;
}
else if (t == (PyObject *)(&PyUnicode_Type)) {
state->types |= MS_TYPE_STR;
kind = CK_STR;
}
else if (t == (PyObject *)(&PyBytes_Type)) {
state->types |= MS_TYPE_BYTES;
kind = CK_BYTES;
}
else if (t == (PyObject *)(&PyByteArray_Type)) {
state->types |= MS_TYPE_BYTEARRAY;
kind = CK_BYTES;
}
else if (t == (PyObject *)(&PyMemoryView_Type)) {
state->types |= MS_TYPE_MEMORYVIEW;
kind = CK_BYTES;
}
else if (t == (PyObject *)(PyDateTimeAPI->DateTimeType)) {
state->types |= MS_TYPE_DATETIME;
kind = CK_TIME;
}
else if (t == (PyObject *)(PyDateTimeAPI->DateType)) {
state->types |= MS_TYPE_DATE;
}
else if (t == (PyObject *)(PyDateTimeAPI->TimeType)) {
state->types |= MS_TYPE_TIME;
kind = CK_TIME;
}
else if (t == (PyObject *)(PyDateTimeAPI->DeltaType)) {
state->types |= MS_TYPE_TIMEDELTA;
}
else if (t == state->mod->UUIDType) {
state->types |= MS_TYPE_UUID;
}
else if (t == state->mod->DecimalType) {
state->types |= MS_TYPE_DECIMAL;
}
else if (t == (PyObject *)(&Ext_Type)) {
state->types |= MS_TYPE_EXT;
}
else if (t == (PyObject *)(&Raw_Type)) {
/* Raw is marked with a typecode of 0, nothing to do */
}
else if (Py_TYPE(t) == (PyTypeObject *)(state->mod->typing_typevar)) {
out = typenode_collect_typevar(state, t);
}
else if (
Py_TYPE(t) == &StructMetaType ||
(origin != NULL && Py_TYPE(origin) == &StructMetaType)
) {
out = typenode_collect_struct(state, t);
}
else if (Py_TYPE(t) == state->mod->EnumMetaType) {
out = typenode_collect_enum(state, t);
}
else if (origin == (PyObject*)(&PyDict_Type)) {
kind = CK_MAP;
if (args != NULL && PyTuple_GET_SIZE(args) != 2) goto invalid;
out = typenode_collect_dict(
state,
(args == NULL) ? state->mod->typing_any : PyTuple_GET_ITEM(args, 0),
(args == NULL) ? state->mod->typing_any : PyTuple_GET_ITEM(args, 1)
);
}
else if (origin == (PyObject*)(&PyList_Type)) {
kind = CK_ARRAY;
if (args != NULL && PyTuple_GET_SIZE(args) != 1) goto invalid;
out = typenode_collect_array(
state,
MS_TYPE_LIST,
(args == NULL) ? state->mod->typing_any : PyTuple_GET_ITEM(args, 0)
);
}
else if (origin == (PyObject*)(&PySet_Type)) {
kind = CK_ARRAY;
if (args != NULL && PyTuple_GET_SIZE(args) != 1) goto invalid;
out = typenode_collect_array(
state,
MS_TYPE_SET,
(args == NULL) ? state->mod->typing_any : PyTuple_GET_ITEM(args, 0)
);
}
else if (origin == (PyObject*)(&PyFrozenSet_Type)) {
kind = CK_ARRAY;
if (args != NULL && PyTuple_GET_SIZE(args) != 1) goto invalid;
out = typenode_collect_array(
state,
MS_TYPE_FROZENSET,
(args == NULL) ? state->mod->typing_any : PyTuple_GET_ITEM(args, 0)
);
}
else if (origin == (PyObject*)(&PyTuple_Type)) {
if (args == NULL) {
kind = CK_ARRAY;
out = typenode_collect_array(
state, MS_TYPE_VARTUPLE, state->mod->typing_any
);
}
else if (PyTuple_GET_SIZE(args) == 2 && PyTuple_GET_ITEM(args, 1) == Py_Ellipsis) {
kind = CK_ARRAY;
out = typenode_collect_array(
state, MS_TYPE_VARTUPLE, PyTuple_GET_ITEM(args, 0)
);
}
else if (
PyTuple_GET_SIZE(args) == 1 &&
PyTuple_CheckExact(PyTuple_GET_ITEM(args, 0)) &&
PyTuple_GET_SIZE(PyTuple_GET_ITEM(args, 0)) == 0
) {
/* XXX: this case handles a weird compatibility issue:
* - Tuple[()].__args__ == ((),)
* - tuple[()].__args__ == ()
*/
out = typenode_collect_array(
state, MS_TYPE_FIXTUPLE, PyTuple_GET_ITEM(args, 0)
);
}
else {
out = typenode_collect_array(state, MS_TYPE_FIXTUPLE, args);
}
}
else if (origin == state->mod->typing_union) {
if (Py_EnterRecursiveCall(" while analyzing a type")) {
out = -1;
goto done;
}
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(args); i++) {
PyObject *arg = PyTuple_GET_ITEM(args, i);
/* Ignore UnsetType in unions */
if (arg == (PyObject *)(&Unset_Type)) continue;
out = typenode_collect_type(state, arg);
if (out < 0) break;
}
Py_LeaveRecursiveCall();
}
else if (origin == state->mod->typing_literal) {
if (state->literals == NULL) {
state->literals = PyList_New(0);
if (state->literals == NULL) goto done;
}
out = PyList_Append(state->literals, t);
}
else if (
is_typeddict_class(state, t) ||
(origin != NULL && is_typeddict_class(state, origin))
) {
out = typenode_collect_typeddict(state, t);
}
else if (
is_namedtuple_class(state, t) ||
(origin != NULL && is_namedtuple_class(state, origin))
) {
out = typenode_collect_namedtuple(state, t);
}
else if (
is_dataclass_or_attrs_class(state, t) ||
(origin != NULL && is_dataclass_or_attrs_class(state, origin))
) {
out = typenode_collect_dataclass(state, t);
}
else {
if (origin != NULL) {
if (!PyType_Check(origin)) goto invalid;
}
else {
if (!PyType_Check(t)) goto invalid;
}
out = typenode_collect_custom(
state,
(origin != NULL) ? MS_TYPE_CUSTOM_GENERIC : MS_TYPE_CUSTOM,
t
);
}
done:
Py_XDECREF(t);
Py_XDECREF(origin);
Py_XDECREF(args);
if (out == 0) {
out = typenode_collect_constraints(state, &constraints, kind, obj);
}
return out;
invalid:
PyErr_Format(PyExc_TypeError, "Type '%R' is not supported", t);
out = -1;
goto done;
}
static TypeNode *
TypeNode_Convert(PyObject *obj) {
TypeNode *out = NULL;
TypeNodeCollectState state = {0};
state.mod = msgspec_get_global_state();
state.context = obj;
if (Py_EnterRecursiveCall(" while analyzing a type")) return NULL;
/* Traverse `obj` to collect all type annotations at this level */
if (typenode_collect_type(&state, obj) < 0) goto done;
/* Handle structs in a second pass */
if (typenode_collect_convert_structs(&state) < 0) goto done;
/* Handle literals in a second pass */
if (typenode_collect_convert_literals(&state) < 0) goto done;
/* Check type invariants to ensure Union types are valid */
if (typenode_collect_check_invariants(&state) < 0) goto done;
/* Populate a new TypeNode, recursing into subtypes as needed */
out = typenode_from_collect_state(&state);
done:
typenode_collect_clear_state(&state);
Py_LeaveRecursiveCall();
return out;
}
#define ms_raise_validation_error(path, format, ...) \
do { \
MsgspecState *st = msgspec_get_global_state(); \
PyObject *suffix = PathNode_ErrSuffix(path); \
if (suffix != NULL) { \
PyErr_Format(st->ValidationError, format, __VA_ARGS__, suffix); \
Py_DECREF(suffix); \
} \
} while (0)
static MS_NOINLINE PyObject *
ms_validation_error(const char *got, TypeNode *type, PathNode *path) {
PyObject *type_repr = typenode_simple_repr(type);
if (type_repr != NULL) {
ms_raise_validation_error(path, "Expected `%U`, got `%s`%U", type_repr, got);
Py_DECREF(type_repr);
}
return NULL;
}
static void
ms_missing_required_field(PyObject *field, PathNode *path) {
ms_raise_validation_error(
path,
"Object missing required field `%U`%U",
field
);
}
static PyObject *
ms_invalid_cstr_value(const char *cstr, Py_ssize_t size, PathNode *path) {
PyObject *str = PyUnicode_DecodeUTF8(cstr, size, NULL);
if (str == NULL) return NULL;
ms_raise_validation_error(path, "Invalid value '%U'%U", str);
Py_DECREF(str);
return NULL;
}
static PyObject *
ms_invalid_cint_value(int64_t val, PathNode *path) {
ms_raise_validation_error(path, "Invalid value %lld%U", val);
return NULL;
}
static PyObject *
ms_invalid_cuint_value(uint64_t val, PathNode *path) {
ms_raise_validation_error(path, "Invalid value %llu%U", val);
return NULL;
}
static MS_NOINLINE PyObject *
ms_error_unknown_field(const char *key, Py_ssize_t key_size, PathNode *path) {
PyObject *field = PyUnicode_FromStringAndSize(key, key_size);
if (field == NULL) return NULL;
ms_raise_validation_error(
path, "Object contains unknown field `%U`%U", field
);
Py_DECREF(field);
return NULL;
}
/* Same as ms_raise_validation_error, except doesn't require any format arguments. */
static PyObject *
ms_error_with_path(const char *msg, PathNode *path) {
MsgspecState *st = msgspec_get_global_state();
PyObject *suffix = PathNode_ErrSuffix(path);
if (suffix != NULL) {
PyErr_Format(st->ValidationError, msg, suffix);
Py_DECREF(suffix);
}
return NULL;
}
static MS_NOINLINE void
ms_maybe_wrap_validation_error(PathNode *path) {
PyObject *exc_type, *exc, *tb;
/* Fetch the exception state */
PyErr_Fetch(&exc_type, &exc, &tb);
/* If null, some other c-extension has borked, just return */
if (exc_type == NULL) return;
/* If it's a TypeError or ValueError, wrap it in a ValidationError.
* Otherwise we reraise the original error below */
if (
PyType_IsSubtype(
(PyTypeObject *)exc_type, (PyTypeObject *)PyExc_ValueError
) ||
PyType_IsSubtype(
(PyTypeObject *)exc_type, (PyTypeObject *)PyExc_TypeError
)
) {
PyObject *exc_type2, *exc2, *tb2;
/* Normalize the original exception */
PyErr_NormalizeException(&exc_type, &exc, &tb);
if (tb != NULL) {
PyException_SetTraceback(exc, tb);
Py_DECREF(tb);
}
Py_DECREF(exc_type);
/* Raise a new validation error with context based on the
* original exception */
ms_raise_validation_error(path, "%S%U", exc);
/* Fetch the new exception */
PyErr_Fetch(&exc_type2, &exc2, &tb2);
/* Normalize the new exception */
PyErr_NormalizeException(&exc_type2, &exc2, &tb2);
/* Set the original exception as the cause and context */
Py_INCREF(exc);
PyException_SetCause(exc2, exc);
PyException_SetContext(exc2, exc);
/* At this point the original exc_type/exc/tb are all dropped,
* replace them with the new values */
exc_type = exc_type2;
exc = exc2;
tb = tb2;
}
/* Restore the new exception state */
PyErr_Restore(exc_type, exc, tb);
}
static PyTypeObject StructMixinType;
/* Note this always allocates an UNTRACKED object */
static PyObject *
Struct_alloc(PyTypeObject *type) {
PyObject *obj;
bool is_gc = MS_TYPE_IS_GC(type);
if (is_gc) {
obj = PyObject_GC_New(PyObject, type);
}
else {
obj = PyObject_New(PyObject, type);
}
if (obj == NULL) return NULL;
/* Zero out slot fields */
memset((char *)obj + sizeof(PyObject), '\0', type->tp_basicsize - sizeof(PyObject));
return obj;
}
/* Mirrored from cpython Objects/typeobject.c */
static void
clear_slots(PyTypeObject *type, PyObject *self)
{
Py_ssize_t i, n;
PyMemberDef *mp;
n = Py_SIZE(type);
mp = MS_PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
for (i = 0; i < n; i++, mp++) {
if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
char *addr = (char *)self + mp->offset;
PyObject *obj = *(PyObject **)addr;
if (obj != NULL) {
*(PyObject **)addr = NULL;
Py_DECREF(obj);
}
}
}
}
static void
Struct_dealloc_nogc(PyObject *self) {
PyTypeObject *type = Py_TYPE(self);
/* Maybe call a finalizer */
if (type->tp_finalize) {
/* If resurrected, exit early */
if (PyObject_CallFinalizerFromDealloc(self) < 0) return;
}
/* Maybe clear weakrefs */
if (type->tp_weaklistoffset) {
PyObject_ClearWeakRefs(self);
}
/* Clear all slots */
PyTypeObject *base = type;
while (base != NULL) {
if (Py_SIZE(base)) {
clear_slots(base, self);
}
base = base->tp_base;
}
type->tp_free(self);
/* Decref the object type immediately */
Py_DECREF(type);
}
static PyObject *
StructMeta_get_field_name(PyObject *self, Py_ssize_t field_index) {
return PyTuple_GET_ITEM(
((StructMetaObject *)self)->struct_encode_fields, field_index
);
}
static MS_INLINE Py_ssize_t
StructMeta_get_field_index(
StructMetaObject *self, const char * key, Py_ssize_t key_size, Py_ssize_t *pos
) {
const char *field;
Py_ssize_t nfields, field_size, i, offset = *pos;
nfields = PyTuple_GET_SIZE(self->struct_encode_fields);
for (i = offset; i < nfields; i++) {
field = unicode_str_and_size_nocheck(
PyTuple_GET_ITEM(self->struct_encode_fields, i), &field_size
);
if (key_size == field_size && memcmp(key, field, key_size) == 0) {
*pos = i < (nfields - 1) ? (i + 1) : 0;
return i;
}
}
for (i = 0; i < offset; i++) {
field = unicode_str_and_size_nocheck(
PyTuple_GET_ITEM(self->struct_encode_fields, i), &field_size
);
if (key_size == field_size && memcmp(key, field, key_size) == 0) {
*pos = i + 1;
return i;
}
}
/* Not a field, check if it matches the tag field (if present) */
if (MS_UNLIKELY(self->struct_tag_field != NULL)) {
Py_ssize_t tag_field_size;
const char *tag_field;
tag_field = unicode_str_and_size_nocheck(self->struct_tag_field, &tag_field_size);
if (key_size == tag_field_size && memcmp(key, tag_field, key_size) == 0) {
return -2;
}
}
return -1;
}
static int
dict_discard(PyObject *dict, PyObject *key) {
int status = PyDict_Contains(dict, key);
if (status < 0)
return status;
return (status == 1) ? PyDict_DelItem(dict, key) : 0;
}
static PyObject *
Struct_vectorcall(PyTypeObject *cls, PyObject *const *args, size_t nargsf, PyObject *kwnames);
/* setattr for frozen=True types */
static int
Struct_setattro_frozen(PyObject *self, PyObject *key, PyObject *value) {
PyErr_Format(
PyExc_AttributeError, "immutable type: '%s'", Py_TYPE(self)->tp_name
);
return -1;
}
/* setattr for frozen=False types */
static int
Struct_setattro_default(PyObject *self, PyObject *key, PyObject *value) {
if (PyObject_GenericSetAttr(self, key, value) < 0) return -1;
if (
value != NULL &&
MS_OBJECT_IS_GC(self) &&
!MS_IS_TRACKED(self) &&
MS_MAYBE_TRACKED(value)
)
PyObject_GC_Track(self);
return 0;
}
static PyObject*
rename_lower(PyObject *rename, PyObject *field) {
return PyObject_CallMethod(field, "lower", NULL);
}
static PyObject*
rename_upper(PyObject *rename, PyObject *field) {
return PyObject_CallMethod(field, "upper", NULL);
}
static PyObject*
rename_kebab(PyObject *rename, PyObject *field) {
PyObject *underscore = NULL, *dash = NULL, *temp = NULL, *out = NULL;
underscore = PyUnicode_FromStringAndSize("_", 1);
if (underscore == NULL) goto error;
dash = PyUnicode_FromStringAndSize("-", 1);
if (dash == NULL) goto error;
temp = PyObject_CallMethod(field, "strip", "s", "_");
if (temp == NULL) goto error;
out = PyUnicode_Replace(temp, underscore, dash, -1);
error:
Py_XDECREF(underscore);
Py_XDECREF(dash);
Py_XDECREF(temp);
return out;
}
static PyObject*
rename_camel_inner(PyObject *field, bool cap_first) {
PyObject *parts = NULL, *out = NULL, *empty = NULL;
PyObject *underscore = PyUnicode_FromStringAndSize("_", 1);
if (underscore == NULL) return NULL;
parts = PyUnicode_Split(field, underscore, -1);
if (parts == NULL) goto cleanup;
if (PyList_GET_SIZE(parts) == 1 && !cap_first) {
Py_INCREF(field);
out = field;
goto cleanup;
}
bool first = true;
for (Py_ssize_t i = 0; i < PyList_GET_SIZE(parts); i++) {
PyObject *part = PyList_GET_ITEM(parts, i);
if (first && (PyUnicode_GET_LENGTH(part) == 0)) {
/* Preserve leading underscores */
Py_INCREF(underscore);
Py_DECREF(part);
PyList_SET_ITEM(parts, i, underscore);
}
else {
if (!first || cap_first) {
/* convert part to title case, inplace in the list */
PyObject *part_title = PyObject_CallMethod(part, "title", NULL);
if (part_title == NULL) goto cleanup;
Py_DECREF(part);
PyList_SET_ITEM(parts, i, part_title);
}
first = false;
}
}
empty = PyUnicode_FromStringAndSize("", 0);
if (empty == NULL) goto cleanup;
out = PyUnicode_Join(empty, parts);
cleanup:
Py_XDECREF(empty);
Py_XDECREF(underscore);
Py_XDECREF(parts);
return out;
}
static PyObject*
rename_camel(PyObject *rename, PyObject *field) {
return rename_camel_inner(field, false);
}
static PyObject*
rename_pascal(PyObject *rename, PyObject *field) {
return rename_camel_inner(field, true);
}
static PyObject*
rename_callable(PyObject *rename, PyObject *field) {
PyObject *temp = PyObject_CallOneArg(rename, field);
if (temp == NULL) return NULL;
if (PyUnicode_CheckExact(temp)) return temp;
if (temp == Py_None) {
Py_DECREF(temp);
Py_INCREF(field);
return field;
}
PyErr_Format(
PyExc_TypeError,
"Expected calling `rename` to return a `str` or `None`, got `%.200s`",
Py_TYPE(temp)->tp_name
);
Py_DECREF(temp);
return NULL;
}
static PyObject*
rename_mapping(PyObject *rename, PyObject *field) {
PyObject *temp = PyObject_GetItem(rename, field);
if (temp == NULL) {
PyErr_Clear();
Py_INCREF(field);
return field;
}
else if (temp == Py_None) {
Py_DECREF(temp);
Py_INCREF(field);
return field;
}
else if (PyUnicode_CheckExact(temp)) {
return temp;
}
PyErr_Format(
PyExc_TypeError,
"Expected `rename[field]` to return a `str` or `None`, got `%.200s`",
Py_TYPE(temp)->tp_name
);
Py_DECREF(temp);
return NULL;
}
typedef struct {
/* Temporary state. All owned references. */
PyObject *defaults_lk;
PyObject *offsets_lk;
PyObject *kwonly_fields;
PyObject *slots;
PyObject *namespace;
PyObject *renamed_fields;
/* Output values. All owned references. */
PyObject *fields;
PyObject *encode_fields;
PyObject *defaults;
PyObject *match_args;
PyObject *tag;
PyObject *tag_field;
PyObject *tag_value;
Py_ssize_t *offsets;
Py_ssize_t nkwonly;
Py_ssize_t n_trailing_defaults;
/* Configuration values. All borrowed references. */
PyObject *name;
PyObject *temp_tag_field;
PyObject *temp_tag;
PyObject *rename;
int omit_defaults;
int forbid_unknown_fields;
int frozen;
int eq;
int order;
int repr_omit_defaults;
int array_like;
int gc;
int weakref;
bool already_has_weakref;
int dict;
bool already_has_dict;
int cache_hash;
Py_ssize_t hash_offset;
bool has_non_slots_bases;
} StructMetaInfo;
static int
structmeta_check_namespace(PyObject *namespace) {
static const char *attrs[] = {"__init__", "__new__", "__slots__"};
Py_ssize_t nattrs = 3;
for (Py_ssize_t i = 0; i < nattrs; i++) {
if (PyDict_GetItemString(namespace, attrs[i]) != NULL) {
PyErr_Format(PyExc_TypeError, "Struct types cannot define %s", attrs[i]);
return -1;
}
}
return 0;
}
static PyObject *
structmeta_get_module_ns(MsgspecState *mod, StructMetaInfo *info) {
PyObject *name = PyDict_GetItemString(info->namespace, "__module__");
if (name == NULL) return NULL;
PyObject *modules = PySys_GetObject("modules");
if (modules == NULL) return NULL;
PyObject *module = PyDict_GetItem(modules, name);
if (mod == NULL) return NULL;
return PyObject_GetAttr(module, mod->str___dict__);
}
static int
structmeta_collect_base(StructMetaInfo *info, MsgspecState *mod, PyObject *base) {
if ((PyTypeObject *)base == &StructMixinType) return 0;
if (((PyTypeObject *)base)->tp_weaklistoffset) {
info->already_has_weakref = true;
}
if (((PyTypeObject *)base)->tp_dictoffset) {
info->already_has_dict = true;
}
if (!PyType_Check(base)) {
/* CPython's metaclass conflict check will catch this issue earlier on,
* but it's still good to have this check in place in case that's ever
* removed */
PyErr_SetString(PyExc_TypeError, "All base classes must be types");
return -1;
}
if (Py_TYPE(base) != &StructMetaType) {
if (((PyTypeObject *)base)->tp_dictoffset) {
info->has_non_slots_bases = true;
}
static const char *attrs[] = {"__init__", "__new__"};
Py_ssize_t nattrs = 2;
PyObject *tp_dict = MS_GET_TYPE_DICT((PyTypeObject *)base);
for (Py_ssize_t i = 0; i < nattrs; i++) {
if (PyDict_GetItemString(tp_dict, attrs[i]) != NULL) {
PyErr_Format(PyExc_TypeError, "Struct base classes cannot define %s", attrs[i]);
return -1;
}
}
return 0;
}
StructMetaObject *st_type = (StructMetaObject *)base;
/* Check if a hash_cache slot already exists */
if (st_type->hash_offset != 0) {
info->hash_offset = st_type->hash_offset;
}
/* Inherit config fields */
if (st_type->struct_tag_field != NULL) {
info->temp_tag_field = st_type->struct_tag_field;
}
if (st_type->struct_tag != NULL) {
info->temp_tag = st_type->struct_tag;
}
if (st_type->rename != NULL) {
info->rename = st_type->rename;
}
info->frozen = STRUCT_MERGE_OPTIONS(info->frozen, st_type->frozen);
info->eq = STRUCT_MERGE_OPTIONS(info->eq, st_type->eq);
info->order = STRUCT_MERGE_OPTIONS(info->order, st_type->order);
info->array_like = STRUCT_MERGE_OPTIONS(info->array_like, st_type->array_like);
info->gc = STRUCT_MERGE_OPTIONS(info->gc, st_type->gc);
info->omit_defaults = STRUCT_MERGE_OPTIONS(info->omit_defaults, st_type->omit_defaults);
info->repr_omit_defaults = STRUCT_MERGE_OPTIONS(
info->repr_omit_defaults, st_type->repr_omit_defaults
);
info->forbid_unknown_fields = STRUCT_MERGE_OPTIONS(
info->forbid_unknown_fields, st_type->forbid_unknown_fields
);
PyObject *fields = st_type->struct_fields;
PyObject *encode_fields = st_type->struct_encode_fields;
PyObject *defaults = st_type->struct_defaults;
Py_ssize_t *offsets = st_type->struct_offsets;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
Py_ssize_t nkwonly = st_type->nkwonly;
Py_ssize_t ndefaults = PyTuple_GET_SIZE(defaults);
Py_ssize_t defaults_offset = nfields - ndefaults;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *field = PyTuple_GET_ITEM(fields, i);
PyObject *encode_field = PyTuple_GET_ITEM(encode_fields, i);
PyObject *default_val = NODEFAULT;
if (i >= defaults_offset) {
default_val = PyTuple_GET_ITEM(defaults, i - defaults_offset);
}
if (PyDict_SetItem(info->defaults_lk, field, default_val) < 0) return -1;
/* Mark the field as kwonly or not */
if (i >= (nfields - nkwonly)) {
if (PySet_Add(info->kwonly_fields, field) < 0) return -1;
}
else {
if (PySet_Discard(info->kwonly_fields, field) < 0) return -1;
}
/* Propagate any renamed fields */
if (field != encode_field) {
if (PyDict_SetItem(info->renamed_fields, field, encode_field) < 0) return -1;
}
PyObject *offset = PyLong_FromSsize_t(offsets[i]);
if (offset == NULL) return -1;
bool errored = PyDict_SetItem(info->offsets_lk, field, offset) < 0;
Py_DECREF(offset);
if (errored) return -1;
}
return 0;
}
static int
structmeta_process_rename(
StructMetaInfo *info, PyObject *name, PyObject *default_value
) {
if (
default_value != NULL &&
Py_TYPE(default_value) == &Field_Type &&
((Field *)default_value)->name != NULL
) {
Field *field = (Field *)default_value;
if (PyUnicode_Compare(name, field->name) == 0) return 0;
return PyDict_SetItem(info->renamed_fields, name, field->name);
}
if (info->rename == NULL) return 0;
PyObject* (*method)(PyObject *, PyObject *);
if (PyUnicode_CheckExact(info->rename)) {
if (PyUnicode_CompareWithASCIIString(info->rename, "lower") == 0) {
method = &rename_lower;
}
else if (PyUnicode_CompareWithASCIIString(info->rename, "upper") == 0) {
method = &rename_upper;
}
else if (PyUnicode_CompareWithASCIIString(info->rename, "camel") == 0) {
method = &rename_camel;
}
else if (PyUnicode_CompareWithASCIIString(info->rename, "pascal") == 0) {
method = &rename_pascal;
}
else if (PyUnicode_CompareWithASCIIString(info->rename, "kebab") == 0) {
method = &rename_kebab;
}
else {
PyErr_Format(PyExc_ValueError, "rename='%U' is unsupported", info->rename);
return -1;
}
}
else if (PyCallable_Check(info->rename)) {
method = &rename_callable;
}
else if (PyMapping_Check(info->rename)) {
method = &rename_mapping;
}
else {
PyErr_SetString(PyExc_TypeError, "`rename` must be a str, callable, or mapping");
return -1;
}
PyObject *temp = method(info->rename, name);
if (temp == NULL) return -1;
int out = 0;
if (PyUnicode_Compare(name, temp) != 0) {
out = PyDict_SetItem(info->renamed_fields, name, temp);
}
Py_DECREF(temp);
return out;
}
static int
structmeta_process_default(StructMetaInfo *info, PyObject *name) {
PyObject *obj = PyDict_GetItem(info->namespace, name);
if (structmeta_process_rename(info, name, obj) < 0) return -1;
if (obj == NULL) {
return PyDict_SetItem(info->defaults_lk, name, NODEFAULT);
}
PyObject* default_val = NULL;
PyTypeObject *type = Py_TYPE(obj);
if (type == &Field_Type) {
Field *f = (Field *)obj;
/* Extract default or default_factory */
if (f->default_value != NODEFAULT) {
obj = f->default_value;
type = Py_TYPE(obj);
}
else if (f->default_factory != NODEFAULT) {
if (f->default_factory == (PyObject *)&PyTuple_Type) {
default_val = PyTuple_New(0);
}
else if (f->default_factory == (PyObject *)&PyFrozenSet_Type) {
default_val = PyFrozenSet_New(NULL);
}
else {
default_val = Factory_New(f->default_factory);
}
if (default_val == NULL) return -1;
goto done;
}
else {
default_val = NODEFAULT;
Py_INCREF(default_val);
goto done;
}
}
if (type == &PyDict_Type) {
if (PyDict_GET_SIZE(obj) != 0) goto error_nonempty;
default_val = Factory_New((PyObject*)(&PyDict_Type));
if (default_val == NULL) return -1;
}
else if (type == &PyList_Type) {
if (PyList_GET_SIZE(obj) != 0) goto error_nonempty;
default_val = Factory_New((PyObject*)(&PyList_Type));
if (default_val == NULL) return -1;
}
else if (type == &PySet_Type) {
if (PySet_GET_SIZE(obj) != 0) goto error_nonempty;
default_val = Factory_New((PyObject*)(&PySet_Type));
if (default_val == NULL) return -1;
}
else if (type == &PyByteArray_Type) {
if (PyByteArray_GET_SIZE(obj) != 0) goto error_nonempty;
default_val = Factory_New((PyObject*)(&PyByteArray_Type));
if (default_val == NULL) return -1;
}
else if (
(Py_TYPE(type) == &StructMetaType) &&
((StructMetaObject *)type)->frozen != OPT_TRUE
) {
goto error_mutable_struct;
}
else {
Py_INCREF(obj);
default_val = obj;
}
done:
if (dict_discard(info->namespace, name) < 0) {
Py_DECREF(default_val);
return -1;
}
int status = PyDict_SetItem(info->defaults_lk, name, default_val);
Py_DECREF(default_val);
return status;
error_nonempty:
PyErr_Format(
PyExc_TypeError,
"Using a non-empty mutable collection (%R) as a default value is unsafe. "
"Instead configure a `default_factory` for this field.",
obj
);
return -1;
error_mutable_struct:
PyErr_Format(
PyExc_TypeError,
"Using a mutable struct object (%R) as a default value is unsafe. "
"Either configure a `default_factory` for this field, or set "
"`frozen=True` on `%.200s`",
obj, type->tp_name
);
return -1;
}
static int
structmeta_is_classvar(
StructMetaInfo *info, MsgspecState *mod, PyObject *ann, PyObject **module_ns
) {
PyTypeObject *ann_type = Py_TYPE(ann);
if (ann_type == &PyUnicode_Type) {
Py_ssize_t ann_len;
const char *ann_buf = unicode_str_and_size(ann, &ann_len);
if (ann_len < 8) return 0;
if (memcmp(ann_buf, "ClassVar", 8) == 0) {
if (ann_len != 8 && ann_buf[8] != '[') return 0;
if (*module_ns == NULL) {
*module_ns = structmeta_get_module_ns(mod, info);
}
if (*module_ns == NULL) return 0;
PyObject *temp = PyDict_GetItemString(*module_ns, "ClassVar");
return temp == mod->typing_classvar;
}
if (ann_len < 15) return 0;
if (memcmp(ann_buf, "typing.ClassVar", 15) == 0) {
if (ann_len != 15 && ann_buf[15] != '[') return 0;
if (*module_ns == NULL) {
*module_ns = structmeta_get_module_ns(mod, info);
}
if (*module_ns == NULL) return 0;
PyObject *temp = PyDict_GetItemString(*module_ns, "typing");
if (temp == NULL) return 0;
temp = PyObject_GetAttrString(temp, "ClassVar");
int status = temp == mod->typing_classvar;
Py_DECREF(temp);
return status;
}
}
else {
if (ann == mod->typing_classvar) {
return 1;
}
else if ((PyObject *)ann_type == mod->typing_generic_alias) {
PyObject *temp = PyObject_GetAttr(ann, mod->str___origin__);
if (temp == NULL) return -1;
int status = temp == mod->typing_classvar;
Py_DECREF(temp);
return status;
}
return 0;
}
return 0;
}
static int
structmeta_collect_fields(StructMetaInfo *info, MsgspecState *mod, bool kwonly) {
PyObject *annotations = PyDict_GetItemString(
info->namespace, "__annotations__"
);
if (annotations == NULL) return 0;
if (!PyDict_Check(annotations)) {
PyErr_SetString(PyExc_TypeError, "__annotations__ must be a dict");
return -1;
}
PyObject *module_ns = NULL;
PyObject *field, *value;
Py_ssize_t i = 0;
while (PyDict_Next(annotations, &i, &field, &value)) {
if (!PyUnicode_CheckExact(field)) {
PyErr_SetString(
PyExc_TypeError, "__annotations__ keys must be strings"
);
goto error;
}
PyObject *invalid_field_names[] = {
mod->str___weakref__, mod->str___dict__, mod->str___msgspec_cached_hash__
};
for (int i = 0; i < 3; i++) {
if (PyUnicode_Compare(field, invalid_field_names[i]) == 0) {
PyErr_Format(
PyExc_TypeError,
"Cannot have a struct field named %R",
field
);
goto error;
}
}
int status = structmeta_is_classvar(info, mod, value, &module_ns);
if (status == 1) continue;
if (status == -1) goto error;
/* If the field is new, add it to slots */
if (PyDict_GetItem(info->defaults_lk, field) == NULL) {
if (PyList_Append(info->slots, field) < 0) goto error;
}
if (kwonly) {
if (PySet_Add(info->kwonly_fields, field) < 0) goto error;
}
else {
if (PySet_Discard(info->kwonly_fields, field) < 0) goto error;
}
if (structmeta_process_default(info, field) < 0) goto error;
}
return 0;
error:
Py_XDECREF(module_ns);
return -1;
}
static int
structmeta_construct_fields(StructMetaInfo *info, MsgspecState *mod) {
Py_ssize_t nfields = PyDict_GET_SIZE(info->defaults_lk);
Py_ssize_t nkwonly = PySet_GET_SIZE(info->kwonly_fields);
Py_ssize_t field_index = 0;
info->fields = PyTuple_New(nfields);
if (info->fields == NULL) return -1;
info->defaults = PyList_New(0);
/* First pass - handle all non-kwonly fields. */
PyObject *field, *default_val;
Py_ssize_t pos = 0;
while (PyDict_Next(info->defaults_lk, &pos, &field, &default_val)) {
int kwonly = PySet_Contains(info->kwonly_fields, field);
if (kwonly < 0) return -1;
if (kwonly) continue;
Py_INCREF(field);
PyTuple_SET_ITEM(info->fields, field_index, field);
if (default_val == NODEFAULT) {
if (PyList_GET_SIZE(info->defaults)) {
PyErr_Format(
PyExc_TypeError,
"Required field '%U' cannot follow optional fields. Either "
"reorder the struct fields, or set `kw_only=True` in the "
"struct definition.",
field
);
return -1;
}
}
else {
if (PyList_Append(info->defaults, default_val) < 0) return -1;
}
field_index++;
}
/* Next handle any kw_only fields */
if (nkwonly) {
PyObject *field, *default_val;
Py_ssize_t pos = 0;
while (PyDict_Next(info->defaults_lk, &pos, &field, &default_val)) {
int kwonly = PySet_Contains(info->kwonly_fields, field);
if (kwonly < 0) return -1;
if (!kwonly) continue;
Py_INCREF(field);
PyTuple_SET_ITEM(info->fields, field_index, field);
if (PyList_GET_SIZE(info->defaults) || default_val != NODEFAULT) {
if (PyList_Append(info->defaults, default_val) < 0) return -1;
}
field_index++;
}
}
/* Convert defaults list to tuple */
PyObject *temp_defaults = PyList_AsTuple(info->defaults);
Py_DECREF(info->defaults);
info->defaults = temp_defaults;
if (info->defaults == NULL) return -1;
/* Compute n_trailing_defaults */
info->nkwonly = nkwonly;
info->n_trailing_defaults = 0;
for (Py_ssize_t i = PyTuple_GET_SIZE(info->defaults) - 1; i >= 0; i--) {
if (PyTuple_GET_ITEM(info->defaults, i) == NODEFAULT) break;
info->n_trailing_defaults++;
}
/* Construct __match_args__ */
info->match_args = PyTuple_GetSlice(info->fields, 0, nfields - nkwonly);
if (info->match_args == NULL) return -1;
/* Construct __slots__ */
if (info->weakref == OPT_TRUE && !info->already_has_weakref) {
if (PyList_Append(info->slots, mod->str___weakref__) < 0) return -1;
}
else if (info->weakref == OPT_FALSE && info->already_has_weakref) {
PyErr_SetString(
PyExc_ValueError,
"Cannot set `weakref=False` if base class already has `weakref=True`"
);
return -1;
}
if (info->dict == OPT_TRUE && !info->already_has_dict) {
if (PyList_Append(info->slots, mod->str___dict__) < 0) return -1;
}
else if (info->dict == OPT_FALSE && info->already_has_dict) {
PyErr_SetString(
PyExc_ValueError,
"Cannot set `dict=False` if base class already has `dict=True`"
);
return -1;
}
if (info->cache_hash == OPT_TRUE && !info->hash_offset) {
if (PyList_Append(info->slots, mod->str___msgspec_cached_hash__) < 0) return -1;
}
else if (info->cache_hash == OPT_FALSE && info->hash_offset) {
PyErr_SetString(
PyExc_ValueError,
"Cannot set `cache_hash=False` if base class already has `cache_hash=True`"
);
return -1;
}
if (PyList_Sort(info->slots) < 0) return -1;
PyObject *slots = PyList_AsTuple(info->slots);
if (slots == NULL) return -1;
int out = PyDict_SetItemString(info->namespace, "__slots__", slots);
Py_DECREF(slots);
return out;
}
static int json_str_requires_escaping(PyObject *);
static int
structmeta_construct_encode_fields(StructMetaInfo *info)
{
if (PyDict_GET_SIZE(info->renamed_fields) == 0) {
/* Nothing to do, use original field tuple */
Py_INCREF(info->fields);
info->encode_fields = info->fields;
return 0;
}
info->encode_fields = PyTuple_New(PyTuple_GET_SIZE(info->fields));
if (info->encode_fields == NULL) return -1;
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(info->fields); i++) {
PyObject *name = PyTuple_GET_ITEM(info->fields, i);
PyObject *temp = PyDict_GetItem(info->renamed_fields, name);
if (temp == NULL) {
temp = name;
}
Py_INCREF(temp);
PyTuple_SET_ITEM(info->encode_fields, i, temp);
}
/* Ensure that renamed fields don't collide */
PyObject *fields_set = PySet_New(info->encode_fields);
if (fields_set == NULL) return -1;
bool unique = PySet_GET_SIZE(fields_set) == PyTuple_GET_SIZE(info->encode_fields);
Py_DECREF(fields_set);
if (!unique) {
PyErr_SetString(
PyExc_ValueError,
"Multiple fields rename to the same name, field names "
"must be unique"
);
return -1;
}
/* Ensure all renamed fields contain characters that don't require quoting
* in JSON. This isn't strictly required, but usage of such characters is
* extremely unlikely, and forbidding this allows us to optimize encoding */
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(info->encode_fields); i++) {
PyObject *field = PyTuple_GET_ITEM(info->encode_fields, i);
Py_ssize_t status = json_str_requires_escaping(field);
if (status == -1) return -1;
if (status == 1) {
PyErr_Format(
PyExc_ValueError,
"Renamed field names must not contain '\\', '\"', or control characters "
"('\\u0000' to '\\u001F') - '%U' is invalid",
field
);
return -1;
}
}
return 0;
}
/* Extracts the qualname for a class, and strips off any leading bits from a
* function namespace. Examples:
*
* - `Foo` -> `Foo`
* - `Foo.Bar` -> `Foo.Bar`
* - `fizz.<locals>.Foo.Bar` -> `Foo.Bar`
*
* This means that (nested) classes dynamically defined within functions should
* work the same as (nested) classes defined at the top level.
*/
static PyObject *simple_qualname(PyObject *cls) {
PyObject *qualname = NULL, *dotlocalsdot = NULL, *rsplits = NULL, *out = NULL;
qualname = PyObject_GetAttrString(cls, "__qualname__");
if (qualname == NULL) goto cleanup;
dotlocalsdot = PyUnicode_FromString(".<locals>.");
if (dotlocalsdot == NULL) goto cleanup;
rsplits = PyUnicode_RSplit(qualname, dotlocalsdot, 1);
if (rsplits == NULL) goto cleanup;
Py_ssize_t end = PyList_GET_SIZE(rsplits) - 1;
out = PyList_GET_ITEM(rsplits, end);
Py_INCREF(out);
cleanup:
Py_XDECREF(qualname);
Py_XDECREF(dotlocalsdot);
Py_XDECREF(rsplits);
return out;
}
static int
structmeta_construct_tag(StructMetaInfo *info, MsgspecState *mod, PyObject *cls) {
if (info->temp_tag == Py_False) return 0;
if (info->temp_tag == NULL && info->temp_tag_field == NULL) return 0;
Py_XINCREF(info->temp_tag);
info->tag = info->temp_tag;
/* Determine the tag value */
if (info->temp_tag == NULL || info->temp_tag == Py_True) {
info->tag_value = simple_qualname(cls);
if (info->tag_value == NULL) return -1;
}
else {
if (PyCallable_Check(info->temp_tag)) {
PyObject *qualname = simple_qualname(cls);
if (qualname == NULL) return -1;
info->tag_value = PyObject_CallOneArg(info->temp_tag, qualname);
Py_DECREF(qualname);
if (info->tag_value == NULL) return -1;
}
else {
Py_INCREF(info->temp_tag);
info->tag_value = info->temp_tag;
}
if (PyLong_CheckExact(info->tag_value)) {
int64_t val = PyLong_AsLongLong(info->tag_value);
if (val == -1 && PyErr_Occurred()) {
PyErr_SetString(
PyExc_ValueError,
"Integer `tag` values must be within [-2**63, 2**63 - 1]"
);
return -1;
}
}
else if (!PyUnicode_CheckExact(info->tag_value)) {
PyErr_SetString(PyExc_TypeError, "`tag` must be a `str` or an `int`");
return -1;
}
}
/* Next determine the tag_field to use. */
if (info->temp_tag_field == NULL) {
info->tag_field = mod->str_type;
Py_INCREF(info->tag_field);
}
else if (PyUnicode_CheckExact(info->temp_tag_field)) {
info->tag_field = info->temp_tag_field;
Py_INCREF(info->tag_field);
}
else {
PyErr_SetString(PyExc_TypeError, "`tag_field` must be a `str`");
return -1;
}
int contains = PySequence_Contains(info->encode_fields, info->tag_field);
if (contains < 0) return -1;
if (contains) {
PyErr_Format(
PyExc_ValueError,
"`tag_field='%U' conflicts with an existing field of that name",
info->tag_field
);
return -1;
}
return 0;
}
static int
structmeta_construct_offsets(
StructMetaInfo *info, MsgspecState *mod, StructMetaObject *cls
) {
PyMemberDef *mp = MS_PyHeapType_GET_MEMBERS(cls);
for (Py_ssize_t i = 0; i < Py_SIZE(cls); i++, mp++) {
PyObject *offset = PyLong_FromSsize_t(mp->offset);
if (offset == NULL) return -1;
bool errored = PyDict_SetItemString(info->offsets_lk, mp->name, offset) < 0;
Py_DECREF(offset);
if (errored) return -1;
}
info->offsets = PyMem_New(Py_ssize_t, PyTuple_GET_SIZE(info->fields));
if (info->offsets == NULL) return -1;
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(info->fields); i++) {
PyObject *field = PyTuple_GET_ITEM(info->fields, i);
PyObject *offset = PyDict_GetItem(info->offsets_lk, field);
if (offset == NULL) {
PyErr_Format(PyExc_RuntimeError, "Failed to get offset for %R", field);
return -1;
}
info->offsets[i] = PyLong_AsSsize_t(offset);
}
if (info->cache_hash == OPT_TRUE && info->hash_offset == 0) {
PyObject *offset = PyDict_GetItem(
info->offsets_lk, mod->str___msgspec_cached_hash__
);
if (offset == NULL) {
PyErr_Format(
PyExc_RuntimeError, "Failed to get offset for %R", mod->str___msgspec_cached_hash__
);
return -1;
}
info->hash_offset = PyLong_AsSsize_t(offset);
}
return 0;
}
static PyObject *
StructMeta_new_inner(
PyTypeObject *type, PyObject *name, PyObject *bases, PyObject *namespace,
PyObject *arg_tag_field, PyObject *arg_tag, PyObject *arg_rename,
int arg_omit_defaults, int arg_forbid_unknown_fields,
int arg_frozen, int arg_eq, int arg_order, bool arg_kw_only,
int arg_repr_omit_defaults, int arg_array_like,
int arg_gc, int arg_weakref, int arg_dict, int arg_cache_hash
) {
StructMetaObject *cls = NULL;
MsgspecState *mod = msgspec_get_global_state();
bool ok = false;
if (structmeta_check_namespace(namespace) < 0) return NULL;
StructMetaInfo info = {
.defaults_lk = NULL,
.offsets_lk = NULL,
.kwonly_fields = NULL,
.slots = NULL,
.namespace = NULL,
.renamed_fields = NULL,
.fields = NULL,
.encode_fields = NULL,
.defaults = NULL,
.match_args = NULL,
.tag = NULL,
.tag_field = NULL,
.tag_value = NULL,
.offsets = NULL,
.nkwonly = 0,
.n_trailing_defaults = 0,
.name = name,
.temp_tag_field = NULL,
.temp_tag = NULL,
.rename = NULL,
.omit_defaults = -1,
.forbid_unknown_fields = -1,
.frozen = -1,
.eq = -1,
.order = -1,
.repr_omit_defaults = -1,
.array_like = -1,
.gc = -1,
.weakref = arg_weakref,
.already_has_weakref = false,
.dict = arg_dict,
.already_has_dict = false,
.cache_hash = arg_cache_hash,
.hash_offset = 0,
.has_non_slots_bases = false,
};
info.defaults_lk = PyDict_New();
if (info.defaults_lk == NULL) goto cleanup;
info.offsets_lk = PyDict_New();
if (info.offsets_lk == NULL) goto cleanup;
info.kwonly_fields = PySet_New(NULL);
if (info.kwonly_fields == NULL) goto cleanup;
info.namespace = PyDict_Copy(namespace);
if (info.namespace == NULL) goto cleanup;
info.renamed_fields = PyDict_New();
if (info.renamed_fields == NULL) goto cleanup;
info.slots = PyList_New(0);
if (info.slots == NULL) goto cleanup;
/* Extract info from base classes in reverse MRO order */
for (Py_ssize_t i = PyTuple_GET_SIZE(bases) - 1; i >= 0; i--) {
PyObject *base = PyTuple_GET_ITEM(bases, i);
if (structmeta_collect_base(&info, mod, base) < 0) goto cleanup;
}
/* Process configuration options */
if (arg_tag != NULL && arg_tag != Py_None) {
info.temp_tag = arg_tag;
}
if (arg_tag_field != NULL && arg_tag_field != Py_None) {
info.temp_tag_field = arg_tag_field;
}
if (arg_rename != NULL) {
info.rename = arg_rename == Py_None ? NULL : arg_rename;
}
info.frozen = STRUCT_MERGE_OPTIONS(info.frozen, arg_frozen);
info.eq = STRUCT_MERGE_OPTIONS(info.eq, arg_eq);
info.order = STRUCT_MERGE_OPTIONS(info.order, arg_order);
info.repr_omit_defaults = STRUCT_MERGE_OPTIONS(info.repr_omit_defaults, arg_repr_omit_defaults);
info.array_like = STRUCT_MERGE_OPTIONS(info.array_like, arg_array_like);
info.gc = STRUCT_MERGE_OPTIONS(info.gc, arg_gc);
info.omit_defaults = STRUCT_MERGE_OPTIONS(info.omit_defaults, arg_omit_defaults);
info.forbid_unknown_fields = STRUCT_MERGE_OPTIONS(info.forbid_unknown_fields, arg_forbid_unknown_fields);
if (info.eq == OPT_FALSE && info.order == OPT_TRUE) {
PyErr_SetString(PyExc_ValueError, "Cannot set eq=False and order=True");
goto cleanup;
}
if (info.cache_hash == OPT_TRUE && info.frozen != OPT_TRUE) {
PyErr_SetString(PyExc_ValueError, "Cannot set cache_hash=True without frozen=True");
goto cleanup;
}
if (info.gc == OPT_FALSE) {
if (info.has_non_slots_bases) {
PyErr_SetString(
PyExc_ValueError,
"Cannot set gc=False when inheriting from non-struct types with a __dict__"
);
goto cleanup;
}
else if (info.dict == OPT_TRUE || info.already_has_dict) {
PyErr_SetString(PyExc_ValueError, "Cannot set gc=False and dict=True");
goto cleanup;
}
}
/* Collect new fields and defaults */
if (structmeta_collect_fields(&info, mod, arg_kw_only) < 0) goto cleanup;
/* Construct fields and defaults */
if (structmeta_construct_fields(&info, mod) < 0) goto cleanup;
/* Construct encode_fields */
if (structmeta_construct_encode_fields(&info) < 0) goto cleanup;
/* Construct type */
PyObject *args = Py_BuildValue("(OOO)", name, bases, info.namespace);
if (args == NULL) goto cleanup;
cls = (StructMetaObject *) PyType_Type.tp_new(type, args, NULL);
Py_CLEAR(args);
if (cls == NULL) goto cleanup;
/* Fill in type methods */
((PyTypeObject *)cls)->tp_vectorcall = (vectorcallfunc)Struct_vectorcall;
if (info.gc == OPT_FALSE) {
((PyTypeObject *)cls)->tp_flags &= ~Py_TPFLAGS_HAVE_GC;
((PyTypeObject *)cls)->tp_dealloc = &Struct_dealloc_nogc;
((PyTypeObject *)cls)->tp_free = &PyObject_Free;
}
else {
((PyTypeObject *)cls)->tp_flags |= Py_TPFLAGS_HAVE_GC;
((PyTypeObject *)cls)->tp_free = &PyObject_GC_Del;
}
if (info.frozen == OPT_TRUE) {
/* Frozen structs always override __setattr__ */
((PyTypeObject *)cls)->tp_setattro = &Struct_setattro_frozen;
}
else if (
((PyTypeObject *)cls)->tp_setattro == Struct_setattro_frozen ||
((PyTypeObject *)cls)->tp_setattro == PyObject_GenericSetAttr
) {
/* Only set non-frozen __setattr__ if it hasn't been defined by the
* user. All structs will inherit `Struct_setattro_default` from the
* base Struct class, so proper use of `super()` should still result in
* this being called. */
((PyTypeObject *)cls)->tp_setattro = &Struct_setattro_default;
}
/* Construct tag, tag_field, & tag_value */
if (structmeta_construct_tag(&info, mod, (PyObject *)cls) < 0) goto cleanup;
/* Fill in struct offsets */
if (structmeta_construct_offsets(&info, mod, cls) < 0) goto cleanup;
/* Cache access to __post_init__ (if defined). */
cls->post_init = PyObject_GetAttr((PyObject *)cls, mod->str___post_init__);
if (cls->post_init == NULL) {
PyErr_Clear();
}
cls->nkwonly = info.nkwonly;
cls->n_trailing_defaults = info.n_trailing_defaults;
cls->struct_offsets = info.offsets;
Py_INCREF(info.fields);
cls->struct_fields = info.fields;
Py_INCREF(info.defaults);
cls->struct_defaults = info.defaults;
Py_INCREF(info.encode_fields);
cls->struct_encode_fields = info.encode_fields;
Py_INCREF(info.match_args);
cls->match_args = info.match_args;
Py_XINCREF(info.tag);
cls->struct_tag = info.tag;
Py_XINCREF(info.tag_field);
cls->struct_tag_field = info.tag_field;
Py_XINCREF(info.tag_value);
cls->struct_tag_value = info.tag_value;
Py_XINCREF(info.rename);
cls->rename = info.rename;
cls->hash_offset = info.hash_offset;
cls->frozen = info.frozen;
cls->eq = info.eq;
cls->order = info.order;
cls->repr_omit_defaults = info.repr_omit_defaults;
cls->array_like = info.array_like;
cls->gc = info.gc;
cls->omit_defaults = info.omit_defaults;
cls->forbid_unknown_fields = info.forbid_unknown_fields;
ok = true;
cleanup:
/* Temporary structures */
Py_XDECREF(info.defaults_lk);
Py_XDECREF(info.offsets_lk);
Py_XDECREF(info.kwonly_fields);
Py_XDECREF(info.slots);
Py_XDECREF(info.namespace);
Py_XDECREF(info.renamed_fields);
/* Constructed outputs */
Py_XDECREF(info.fields);
Py_XDECREF(info.encode_fields);
Py_XDECREF(info.defaults);
Py_XDECREF(info.match_args);
Py_XDECREF(info.tag);
Py_XDECREF(info.tag_field);
Py_XDECREF(info.tag_value);
if (!ok) {
if (info.offsets != NULL) {
PyMem_Free(info.offsets);
}
Py_XDECREF(cls);
return NULL;
}
return (PyObject *) cls;
}
static PyObject *
StructMeta_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
PyObject *name = NULL, *bases = NULL, *namespace = NULL;
PyObject *arg_tag_field = NULL, *arg_tag = NULL, *arg_rename = NULL;
int arg_omit_defaults = -1, arg_forbid_unknown_fields = -1;
int arg_frozen = -1, arg_eq = -1, arg_order = -1, arg_repr_omit_defaults = -1;
int arg_array_like = -1, arg_gc = -1, arg_weakref = -1, arg_dict = -1;
int arg_kw_only = 0, arg_cache_hash = -1;
char *kwlist[] = {
"name", "bases", "dict",
"tag_field", "tag", "rename",
"omit_defaults", "forbid_unknown_fields",
"frozen", "eq", "order", "kw_only",
"repr_omit_defaults", "array_like",
"gc", "weakref", "dict", "cache_hash",
NULL
};
/* Parse arguments: (name, bases, dict) */
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "UO!O!|$OOOpppppppppppp:StructMeta.__new__", kwlist,
&name, &PyTuple_Type, &bases, &PyDict_Type, &namespace,
&arg_tag_field, &arg_tag, &arg_rename,
&arg_omit_defaults, &arg_forbid_unknown_fields,
&arg_frozen, &arg_eq, &arg_order, &arg_kw_only,
&arg_repr_omit_defaults, &arg_array_like,
&arg_gc, &arg_weakref, &arg_dict, &arg_cache_hash
)
)
return NULL;
return StructMeta_new_inner(
type, name, bases, namespace,
arg_tag_field, arg_tag, arg_rename,
arg_omit_defaults, arg_forbid_unknown_fields,
arg_frozen, arg_eq, arg_order, arg_kw_only,
arg_repr_omit_defaults, arg_array_like,
arg_gc, arg_weakref, arg_dict, arg_cache_hash
);
}
PyDoc_STRVAR(msgspec_defstruct__doc__,
"defstruct(name, fields, *, bases=None, module=None, namespace=None, "
"tag_field=None, tag=None, rename=None, omit_defaults=False, "
"forbid_unknown_fields=False, frozen=False, eq=True, order=False, "
"kw_only=False, repr_omit_defaults=False, array_like=False, gc=True, "
"weakref=False, dict=False, cache_hash=False)\n"
"--\n"
"\n"
"Dynamically define a new Struct class.\n"
"\n"
"Parameters\n"
"----------\n"
"name : str\n"
" The name of the new Struct class.\n"
"fields : iterable\n"
" An iterable of fields in the new class. Elements may be either ``name``,\n"
" tuples of ``(name, type)``, ``(name, type, default)``, or \n"
" ``(name, type, msgspec.field)``. Fields without a specified type will \n"
" default to ``typing.Any``.\n"
"bases : tuple, optional\n"
" A tuple of any Struct base classes to use when defining the new class.\n"
"module : str, optional\n"
" The module name to use for the new class. If not provided, will be inferred\n"
" from the caller's stack frame.\n"
"namespace : dict, optional\n"
" If provided, will be used as the base namespace for the new class. This may\n"
" be used to add additional methods to the class definition.\n"
"**kwargs :\n"
" Additional Struct configuration options. See the ``Struct`` docs for more\n"
" information.\n"
"\n"
"Examples\n"
"--------\n"
">>> from msgspec import defstruct, field\n"
">>> User = defstruct(\n"
"... 'User',\n"
"... [\n"
"... ('name', str),\n"
"... ('email', str | None, None),\n"
"... ('groups', set[str], field(default_factory=set)),\n"
"... ],\n"
"... )\n"
">>> User('alice')\n"
"User(name='alice', email=None, groups=set())\n"
"\n"
"See Also\n"
"--------\n"
"Struct"
);
static PyObject *
msgspec_defstruct(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *name = NULL, *fields = NULL, *bases = NULL, *module = NULL, *namespace = NULL;
PyObject *arg_tag_field = NULL, *arg_tag = NULL, *arg_rename = NULL;
PyObject *new_bases = NULL, *annotations = NULL, *fields_fast = NULL, *out = NULL;
int arg_omit_defaults = -1, arg_forbid_unknown_fields = -1;
int arg_frozen = -1, arg_eq = -1, arg_order = -1, arg_kw_only = 0;
int arg_repr_omit_defaults = -1, arg_array_like = -1;
int arg_gc = -1, arg_weakref = -1, arg_dict = -1, arg_cache_hash = -1;
char *kwlist[] = {
"name", "fields", "bases", "module", "namespace",
"tag_field", "tag", "rename",
"omit_defaults", "forbid_unknown_fields",
"frozen", "eq", "order", "kw_only",
"repr_omit_defaults", "array_like",
"gc", "weakref", "dict", "cache_hash",
NULL
};
/* Parse arguments: (name, bases, dict) */
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "UO|$OOOOOOpppppppppppp:defstruct", kwlist,
&name, &fields, &bases, &module, &namespace,
&arg_tag_field, &arg_tag, &arg_rename,
&arg_omit_defaults, &arg_forbid_unknown_fields,
&arg_frozen, &arg_eq, &arg_order, &arg_kw_only,
&arg_repr_omit_defaults, &arg_array_like,
&arg_gc, &arg_weakref, &arg_dict, &arg_cache_hash)
)
return NULL;
MsgspecState *mod = msgspec_get_state(self);
/* Handle namespace */
if (namespace == NULL || namespace == Py_None) {
namespace = PyDict_New();
}
else {
if (!PyDict_Check(namespace)) {
PyErr_SetString(PyExc_TypeError, "namespace must be a dict or None");
return NULL;
}
namespace = PyDict_Copy(namespace);
}
if (namespace == NULL) return NULL;
/* Handle module */
if (module != NULL && module != Py_None) {
if (!PyUnicode_CheckExact(module)) {
PyErr_SetString(PyExc_TypeError, "module must be a str or None");
goto cleanup;
}
if (PyDict_SetItemString(namespace, "__module__", module) < 0) goto cleanup;
}
/* Handle bases */
if (bases == NULL || bases == Py_None) {
new_bases = PyTuple_New(1);
if (new_bases == NULL) goto cleanup;
Py_INCREF(mod->StructType);
PyTuple_SET_ITEM(new_bases, 0, mod->StructType);
bases = new_bases;
}
else if (!PyTuple_CheckExact(bases)) {
PyErr_SetString(PyExc_TypeError, "bases must be a tuple or None");
goto cleanup;
}
annotations = PyDict_New();
if (annotations == NULL) goto cleanup;
fields_fast = PySequence_Fast(fields, "`fields` must be an iterable");
if (fields_fast == NULL) goto cleanup;
Py_ssize_t nfields = PySequence_Fast_GET_SIZE(fields_fast);
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *name = NULL, *type = NULL, *default_val = NULL;
PyObject *field = PySequence_Fast_GET_ITEM(fields_fast, i);
if (PyUnicode_Check(field)) {
name = field;
type = mod->typing_any;
}
else if (PyTuple_Check(field)) {
Py_ssize_t len = PyTuple_GET_SIZE(field);
if (len == 2) {
name = PyTuple_GET_ITEM(field, 0);
type = PyTuple_GET_ITEM(field, 1);
}
else if (len == 3) {
name = PyTuple_GET_ITEM(field, 0);
type = PyTuple_GET_ITEM(field, 1);
default_val = PyTuple_GET_ITEM(field, 2);
}
}
if (name == NULL || !PyUnicode_Check(name)) {
PyErr_SetString(
PyExc_TypeError,
"items in `fields` must be one of `str`, `tuple[str, type]`, or `tuple[str, type, Any]`"
);
goto cleanup;
}
if (PyDict_SetItem(annotations, name, type) < 0) goto cleanup;
if (default_val != NULL) {
if (PyDict_SetItem(namespace, name, default_val) < 0) goto cleanup;
}
}
if (PyDict_SetItemString(namespace, "__annotations__", annotations) < 0) goto cleanup;
out = StructMeta_new_inner(
&StructMetaType, name, bases, namespace,
arg_tag_field, arg_tag, arg_rename,
arg_omit_defaults, arg_forbid_unknown_fields,
arg_frozen, arg_eq, arg_order, arg_kw_only,
arg_repr_omit_defaults, arg_array_like,
arg_gc, arg_weakref, arg_dict, arg_cache_hash
);
cleanup:
Py_XDECREF(namespace);
Py_XDECREF(new_bases);
Py_XDECREF(annotations);
Py_XDECREF(fields_fast);
return out;
}
static int
StructInfo_traverse(StructInfo *self, visitproc visit, void *arg)
{
Py_VISIT(self->class);
for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
int out = TypeNode_traverse(self->types[i], visit, arg);
if (out != 0) return out;
}
return 0;
}
static int
StructInfo_clear(StructInfo *self)
{
Py_CLEAR(self->class);
for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
TypeNode_Free(self->types[i]);
self->types[i] = NULL;
}
return 0;
}
static void
StructInfo_dealloc(StructInfo *self)
{
PyObject_GC_UnTrack(self);
StructInfo_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyTypeObject StructInfo_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.StructInfo",
.tp_basicsize = sizeof(StructInfo),
.tp_itemsize = sizeof(TypeNode *),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_clear = (inquiry)StructInfo_clear,
.tp_traverse = (traverseproc)StructInfo_traverse,
.tp_dealloc = (destructor)StructInfo_dealloc,
};
static PyObject *
StructInfo_Convert(PyObject *obj) {
MsgspecState *mod = msgspec_get_global_state();
StructMetaObject *class;
PyObject *annotations = NULL;
StructInfo *info = NULL;
bool cache_set = false;
bool is_struct = Py_TYPE(obj) == &StructMetaType;
/* Check for a cached StructInfo, and return if one exists */
if (MS_LIKELY(is_struct)) {
class = (StructMetaObject *)obj;
if (class->struct_info != NULL) {
Py_INCREF(class->struct_info);
return (PyObject *)(class->struct_info);
}
Py_INCREF(class);
}
else {
PyObject *cached = NULL;
if (get_msgspec_cache(mod, obj, &StructInfo_Type, &cached)) {
return cached;
}
PyObject *origin = PyObject_GetAttr(obj, mod->str___origin__);
if (origin == NULL) return NULL;
if (Py_TYPE(origin) != &StructMetaType) {
Py_DECREF(origin);
PyErr_SetString(
PyExc_RuntimeError, "Expected __origin__ to be a Struct type"
);
return NULL;
}
class = (StructMetaObject *)origin;
}
/* At this point `class` is a StructMetaObject, and `obj` is a
* StructMetaObject or Generic. `class` has already been incref'd */
/* Ensure the StructMetaObject is fully initialized */
if (MS_UNLIKELY(class->struct_fields == NULL)) {
PyErr_Format(
PyExc_ValueError,
"Type `%R` isn't fully defined, and can't be used in any "
"`Decoder`/`decode` operations. This commonly happens when "
"trying to use the struct type within an `__init_subclass__` "
"method. If you believe what you're trying to do should work, "
"please raise an issue on GitHub.",
(PyObject *)class
);
goto error;
}
/* Extract annotations from the original type object */
annotations = PyObject_CallOneArg(mod->get_class_annotations, obj);
if (annotations == NULL) goto error;
/* Allocate and zero-out a new StructInfo */
Py_ssize_t nfields = PyTuple_GET_SIZE(class->struct_fields);
info = PyObject_GC_NewVar(StructInfo, &StructInfo_Type, nfields);
if (info == NULL) goto error;
for (Py_ssize_t i = 0; i < nfields; i++) {
info->types[i] = NULL;
}
Py_INCREF(class);
info->class = class;
/* Cache the new StuctInfo on the original type annotation */
if (is_struct) {
Py_INCREF(info);
class->struct_info = info;
}
else {
if (PyObject_SetAttr(obj, mod->str___msgspec_cache__, (PyObject *)info) < 0) goto error;
}
cache_set = true;
/* Process all the struct fields */
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *field = PyTuple_GET_ITEM(class->struct_fields, i);
PyObject *field_type = PyDict_GetItem(annotations, field);
if (field_type == NULL) goto error;
TypeNode *type = TypeNode_Convert(field_type);
if (type == NULL) goto error;
info->types[i] = type;
}
Py_DECREF(class);
Py_DECREF(annotations);
PyObject_GC_Track(info);
return (PyObject *)info;
error:
if (cache_set) {
/* An error occurred after the cache was created and set on the object.
* We need to delete the cached value. */
if (is_struct) {
Py_CLEAR(class->struct_info);
}
else {
/* Fetch and restore the original exception to avoid DelAttr
* silently clearing it on rare occasions. */
PyObject *err_type, *err_value, *err_tb;
PyErr_Fetch(&err_type, &err_value, &err_tb);
PyObject_DelAttr(obj, mod->str___msgspec_cache__);
PyErr_Restore(err_type, err_value, err_tb);
}
}
Py_DECREF(class);
Py_XDECREF(annotations);
Py_XDECREF(info);
return NULL;
}
static int
StructMeta_traverse(StructMetaObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->struct_fields);
Py_VISIT(self->struct_defaults);
Py_VISIT(self->struct_encode_fields);
Py_VISIT(self->struct_tag); /* May be a function */
Py_VISIT(self->rename); /* May be a function */
Py_VISIT(self->post_init);
Py_VISIT(self->struct_info);
return PyType_Type.tp_traverse((PyObject *)self, visit, arg);
}
static int
StructMeta_clear(StructMetaObject *self)
{
/* skip if clear already invoked */
if (self->struct_fields == NULL) return 0;
Py_CLEAR(self->struct_fields);
Py_CLEAR(self->struct_defaults);
Py_CLEAR(self->struct_encode_fields);
Py_CLEAR(self->struct_tag_field);
Py_CLEAR(self->struct_tag_value);
Py_CLEAR(self->struct_tag);
Py_CLEAR(self->rename);
Py_CLEAR(self->post_init);
Py_CLEAR(self->struct_info);
Py_CLEAR(self->match_args);
if (self->struct_offsets != NULL) {
PyMem_Free(self->struct_offsets);
self->struct_offsets = NULL;
}
return PyType_Type.tp_clear((PyObject *)self);
}
static void
StructMeta_dealloc(StructMetaObject *self)
{
/* The GC invariants require dealloc immediately untrack to avoid double
* deallocation. However, PyType_Type.tp_dealloc assumes the type is
* currently tracked. Hence the unfortunate untrack/retrack below. */
PyObject_GC_UnTrack(self);
StructMeta_clear(self);
PyObject_GC_Track(self);
PyType_Type.tp_dealloc((PyObject *)self);
}
static PyObject*
StructMeta_signature(StructMetaObject *self, void *closure)
{
Py_ssize_t nfields, ndefaults, npos, nkwonly, i;
MsgspecState *st;
PyObject *res = NULL;
PyObject *inspect = NULL;
PyObject *parameter_cls = NULL;
PyObject *parameter_empty = NULL;
PyObject *kind_positional = NULL;
PyObject *kind_kw_only = NULL;
PyObject *signature_cls = NULL;
PyObject *annotations = NULL;
PyObject *parameters = NULL;
PyObject *temp_args = NULL, *temp_kwargs = NULL;
PyObject *field, *kind, *default_val, *parameter, *annotation;
st = msgspec_get_global_state();
nfields = PyTuple_GET_SIZE(self->struct_fields);
ndefaults = PyTuple_GET_SIZE(self->struct_defaults);
npos = nfields - ndefaults;
nkwonly = self->nkwonly;
inspect = PyImport_ImportModule("inspect");
if (inspect == NULL) goto cleanup;
parameter_cls = PyObject_GetAttrString(inspect, "Parameter");
if (parameter_cls == NULL) goto cleanup;
parameter_empty = PyObject_GetAttrString(parameter_cls, "empty");
if (parameter_empty == NULL) goto cleanup;
kind_positional = PyObject_GetAttrString(parameter_cls, "POSITIONAL_OR_KEYWORD");
if (kind_positional == NULL) goto cleanup;
kind_kw_only = PyObject_GetAttrString(parameter_cls, "KEYWORD_ONLY");
if (kind_kw_only == NULL) goto cleanup;
signature_cls = PyObject_GetAttrString(inspect, "Signature");
if (signature_cls == NULL) goto cleanup;
annotations = PyObject_CallOneArg(st->get_type_hints, (PyObject *)self);
if (annotations == NULL) goto cleanup;
parameters = PyList_New(nfields);
if (parameters == NULL) return NULL;
temp_args = PyTuple_New(0);
if (temp_args == NULL) goto cleanup;
temp_kwargs = PyDict_New();
if (temp_kwargs == NULL) goto cleanup;
for (i = 0; i < nfields; i++) {
field = PyTuple_GET_ITEM(self->struct_fields, i);
if (i < npos) {
default_val = parameter_empty;
} else {
default_val = PyTuple_GET_ITEM(self->struct_defaults, i - npos);
if (default_val == NODEFAULT) {
default_val = parameter_empty;
}
}
if (i < (nfields - nkwonly)) {
kind = kind_positional;
} else {
kind = kind_kw_only;
}
annotation = PyDict_GetItem(annotations, field);
if (annotation == NULL) {
annotation = parameter_empty;
}
if (PyDict_SetItemString(temp_kwargs, "name", field) < 0) goto cleanup;
if (PyDict_SetItemString(temp_kwargs, "kind", kind) < 0) goto cleanup;
if (PyDict_SetItemString(temp_kwargs, "default", default_val) < 0) goto cleanup;
if (PyDict_SetItemString(temp_kwargs, "annotation", annotation) < 0) goto cleanup;
parameter = PyObject_Call(parameter_cls, temp_args, temp_kwargs);
if (parameter == NULL) goto cleanup;
PyList_SET_ITEM(parameters, i, parameter);
}
res = PyObject_CallOneArg(signature_cls, parameters);
cleanup:
Py_XDECREF(inspect);
Py_XDECREF(parameter_cls);
Py_XDECREF(parameter_empty);
Py_XDECREF(kind_positional);
Py_XDECREF(kind_kw_only);
Py_XDECREF(signature_cls);
Py_XDECREF(annotations);
Py_XDECREF(parameters);
Py_XDECREF(temp_args);
Py_XDECREF(temp_kwargs);
return res;
}
static PyObject*
StructConfig_frozen(StructConfig *self, void *closure)
{
if (self->st_type->frozen == OPT_TRUE) { Py_RETURN_TRUE; }
else { Py_RETURN_FALSE; }
}
static PyObject*
StructConfig_eq(StructConfig *self, void *closure)
{
if (self->st_type->eq == OPT_FALSE) { Py_RETURN_FALSE; }
else { Py_RETURN_TRUE; }
}
static PyObject*
StructConfig_order(StructConfig *self, void *closure)
{
if (self->st_type->order == OPT_TRUE) { Py_RETURN_TRUE; }
else { Py_RETURN_FALSE; }
}
static PyObject*
StructConfig_array_like(StructConfig *self, void *closure)
{
if (self->st_type->array_like == OPT_TRUE) { Py_RETURN_TRUE; }
else { Py_RETURN_FALSE; }
}
static PyObject*
StructConfig_gc(StructConfig *self, void *closure)
{
if (self->st_type->gc == OPT_FALSE) { Py_RETURN_FALSE; }
else { Py_RETURN_TRUE; }
}
static PyObject*
StructConfig_weakref(StructConfig *self, void *closure)
{
PyTypeObject *type = (PyTypeObject *)(self->st_type);
if (type->tp_weaklistoffset) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject*
StructConfig_dict(StructConfig *self, void *closure)
{
PyTypeObject *type = (PyTypeObject *)(self->st_type);
if (type->tp_dictoffset) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject*
StructConfig_cache_hash(StructConfig *self, void *closure)
{
StructMetaObject *type = (StructMetaObject *)(self->st_type);
if (type->hash_offset != 0) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject*
StructConfig_repr_omit_defaults(StructConfig *self, void *closure)
{
if (self->st_type->repr_omit_defaults == OPT_TRUE) { Py_RETURN_TRUE; }
else { Py_RETURN_FALSE; }
}
static PyObject*
StructConfig_omit_defaults(StructConfig *self, void *closure)
{
if (self->st_type->omit_defaults == OPT_TRUE) { Py_RETURN_TRUE; }
else { Py_RETURN_FALSE; }
}
static PyObject*
StructConfig_forbid_unknown_fields(StructConfig *self, void *closure)
{
if (self->st_type->forbid_unknown_fields == OPT_TRUE) { Py_RETURN_TRUE; }
else { Py_RETURN_FALSE; }
}
static PyObject*
StructConfig_tag_field(StructConfig *self, void *closure)
{
PyObject *out = self->st_type->struct_tag_field;
if (out == NULL) Py_RETURN_NONE;
Py_INCREF(out);
return out;
}
static PyObject*
StructConfig_tag(StructConfig *self, void *closure)
{
PyObject *out = self->st_type->struct_tag_value;
if (out == NULL) Py_RETURN_NONE;
Py_INCREF(out);
return out;
}
static PyGetSetDef StructConfig_getset[] = {
{"frozen", (getter) StructConfig_frozen, NULL, NULL, NULL},
{"eq", (getter) StructConfig_eq, NULL, NULL, NULL},
{"order", (getter) StructConfig_order, NULL, NULL, NULL},
{"repr_omit_defaults", (getter) StructConfig_repr_omit_defaults, NULL, NULL, NULL},
{"array_like", (getter) StructConfig_array_like, NULL, NULL, NULL},
{"gc", (getter) StructConfig_gc, NULL, NULL, NULL},
{"weakref", (getter) StructConfig_weakref, NULL, NULL, NULL},
{"dict", (getter) StructConfig_dict, NULL, NULL, NULL},
{"cache_hash", (getter) StructConfig_cache_hash, NULL, NULL, NULL},
{"omit_defaults", (getter) StructConfig_omit_defaults, NULL, NULL, NULL},
{"forbid_unknown_fields", (getter) StructConfig_forbid_unknown_fields, NULL, NULL, NULL},
{"tag", (getter) StructConfig_tag, NULL, NULL, NULL},
{"tag_field", (getter) StructConfig_tag_field, NULL, NULL, NULL},
{NULL},
};
static int
StructConfig_traverse(StructConfig *self, visitproc visit, void *arg) {
Py_VISIT(self->st_type);
return 0;
}
static int
StructConfig_clear(StructConfig *self) {
Py_CLEAR(self->st_type);
return 0;
}
static void
StructConfig_dealloc(StructConfig *self) {
PyObject_GC_UnTrack(self);
StructConfig_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
PyDoc_STRVAR(StructConfig__doc__,
"StructConfig()\n"
"--\n"
"\n"
"Configuration settings for a given Struct type.\n"
"\n"
"This object is accessible through the ``__struct_config__`` field on a struct\n"
"type or instance. It exposes the following attributes, matching the Struct\n"
"configuration parameters of the same name. See the `Struct` docstring for\n"
"details.\n"
"\n"
"Configuration\n"
"-------------\n"
"frozen: bool\n"
"eq: bool\n"
"order: bool\n"
"array_like: bool\n"
"gc: bool\n"
"repr_omit_defaults: bool\n"
"omit_defaults: bool\n"
"forbid_unknown_fields: bool\n"
"weakref: bool\n"
"dict: bool\n"
"cache_hash: bool\n"
"tag_field: str | None\n"
"tag: str | int | None"
);
static PyTypeObject StructConfig_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec.structs.StructConfig",
.tp_doc = StructConfig__doc__,
.tp_basicsize = sizeof(StructConfig),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_new = NULL,
.tp_dealloc = (destructor) StructConfig_dealloc,
.tp_clear = (inquiry) StructConfig_clear,
.tp_traverse = (traverseproc) StructConfig_traverse,
.tp_getset = StructConfig_getset,
};
static PyObject*
StructConfig_New(StructMetaObject *st_type)
{
StructConfig *out = (StructConfig *)StructConfig_Type.tp_alloc(&StructConfig_Type, 0);
if (out == NULL) return NULL;
out->st_type = st_type;
Py_INCREF(st_type);
return (PyObject *)out;
}
static PyObject*
StructMeta_config(StructMetaObject *self, void *closure) {
return StructConfig_New(self);
}
static PyMemberDef StructMeta_members[] = {
{"__struct_fields__", T_OBJECT_EX, offsetof(StructMetaObject, struct_fields), READONLY, "Struct fields"},
{"__struct_defaults__", T_OBJECT_EX, offsetof(StructMetaObject, struct_defaults), READONLY, "Struct defaults"},
{"__struct_encode_fields__", T_OBJECT_EX, offsetof(StructMetaObject, struct_encode_fields), READONLY, "Struct encoded field names"},
{"__match_args__", T_OBJECT_EX, offsetof(StructMetaObject, match_args), READONLY, "Positional match args"},
{NULL},
};
static PyGetSetDef StructMeta_getset[] = {
{"__signature__", (getter) StructMeta_signature, NULL, NULL, NULL},
{"__struct_config__", (getter) StructMeta_config, NULL, "Struct configuration", NULL},
{NULL},
};
static PyTypeObject StructMetaType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.StructMeta",
.tp_basicsize = sizeof(StructMetaObject),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_TYPE_SUBCLASS | Py_TPFLAGS_HAVE_GC | _Py_TPFLAGS_HAVE_VECTORCALL,
.tp_new = StructMeta_new,
.tp_dealloc = (destructor) StructMeta_dealloc,
.tp_clear = (inquiry) StructMeta_clear,
.tp_traverse = (traverseproc) StructMeta_traverse,
.tp_members = StructMeta_members,
.tp_getset = StructMeta_getset,
.tp_call = PyVectorcall_Call,
.tp_vectorcall_offset = offsetof(PyTypeObject, tp_vectorcall),
};
static PyObject *
get_default(PyObject *obj) {
PyTypeObject *type = Py_TYPE(obj);
if (type == &Factory_Type) {
return Factory_Call(obj);
}
Py_INCREF(obj);
return obj;
}
static MS_INLINE bool
is_default(PyObject *x, PyObject *d) {
if (x == d) return true;
if (Py_TYPE(d) == &Factory_Type) {
PyTypeObject *factory = (PyTypeObject *)(((Factory *)d)->factory);
if (Py_TYPE(x) != factory) return false;
if (factory == &PyList_Type && PyList_GET_SIZE(x) == 0) return true;
if (factory == &PyDict_Type && PyDict_GET_SIZE(x) == 0) return true;
if (factory == &PySet_Type && PySet_GET_SIZE(x) == 0) return true;
}
return false;
}
/* Set field #index on obj. Steals a reference to val */
static inline void
Struct_set_index(PyObject *obj, Py_ssize_t index, PyObject *val) {
StructMetaObject *cls;
char *addr;
PyObject *old;
cls = (StructMetaObject *)Py_TYPE(obj);
addr = (char *)obj + cls->struct_offsets[index];
old = *(PyObject **)addr;
Py_XDECREF(old);
*(PyObject **)addr = val;
}
/* Get field #index or NULL on obj. Returns a borrowed reference */
static inline PyObject*
Struct_get_index_noerror(PyObject *obj, Py_ssize_t index) {
StructMetaObject *cls = (StructMetaObject *)Py_TYPE(obj);
char *addr = (char *)obj + cls->struct_offsets[index];
return *(PyObject **)addr;
}
/* Get field #index on obj. Returns a borrowed reference */
static inline PyObject*
Struct_get_index(PyObject *obj, Py_ssize_t index) {
PyObject *val = Struct_get_index_noerror(obj, index);
if (val == NULL) {
StructMetaObject *cls = (StructMetaObject *)Py_TYPE(obj);
PyErr_Format(PyExc_AttributeError,
"Struct field %R is unset",
PyTuple_GET_ITEM(cls->struct_fields, index));
}
return val;
}
static MS_INLINE int
Struct_post_init(StructMetaObject *st_type, PyObject *obj) {
if (st_type->post_init != NULL) {
PyObject *res = PyObject_CallOneArg(st_type->post_init, obj);
if (res == NULL) return -1;
Py_DECREF(res);
}
return 0;
}
static MS_INLINE int
Struct_decode_post_init(StructMetaObject *st_type, PyObject *obj, PathNode *path) {
if (MS_UNLIKELY(Struct_post_init(st_type, obj) < 0)) {
ms_maybe_wrap_validation_error(path);
return -1;
}
return 0;
}
/* ASSUMPTION - obj is untracked and allocated via Struct_alloc */
static int
Struct_fill_in_defaults(StructMetaObject *st_type, PyObject *obj, PathNode *path) {
Py_ssize_t nfields, ndefaults, i;
bool is_gc, should_untrack;
nfields = PyTuple_GET_SIZE(st_type->struct_encode_fields);
ndefaults = PyTuple_GET_SIZE(st_type->struct_defaults);
is_gc = MS_TYPE_IS_GC(st_type);
should_untrack = is_gc;
for (i = 0; i < nfields; i++) {
PyObject *val = Struct_get_index_noerror(obj, i);
if (val == NULL) {
if (MS_UNLIKELY(i < (nfields - ndefaults))) goto missing_required;
val = PyTuple_GET_ITEM(
st_type->struct_defaults, i - (nfields - ndefaults)
);
if (MS_UNLIKELY(val == NODEFAULT)) goto missing_required;
val = get_default(val);
if (MS_UNLIKELY(val == NULL)) return -1;
Struct_set_index(obj, i, val);
}
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(val);
}
}
if (is_gc && !should_untrack)
PyObject_GC_Track(obj);
if (Struct_decode_post_init(st_type, obj, path) < 0) return -1;
return 0;
missing_required:
ms_missing_required_field(
PyTuple_GET_ITEM(st_type->struct_encode_fields, i), path
);
return -1;
}
static PyObject *
Struct_vectorcall(PyTypeObject *cls, PyObject *const *args, size_t nargsf, PyObject *kwnames) {
Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
StructMetaObject *st_type = (StructMetaObject *)cls;
PyObject *fields = st_type->struct_fields;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
PyObject *defaults = st_type->struct_defaults;
Py_ssize_t ndefaults = PyTuple_GET_SIZE(defaults);
Py_ssize_t nkwonly = st_type->nkwonly;
Py_ssize_t npos = nfields - ndefaults;
if (MS_UNLIKELY(nargs > (nfields - nkwonly))) {
PyErr_SetString(PyExc_TypeError, "Extra positional arguments provided");
return NULL;
}
bool is_gc = MS_TYPE_IS_GC(cls);
bool should_untrack = is_gc;
PyObject *self = Struct_alloc(cls);
if (self == NULL) return NULL;
/* First, process all positional arguments */
for (Py_ssize_t i = 0; i < nargs; i++) {
PyObject *val = args[i];
char *addr = (char *)self + st_type->struct_offsets[i];
Py_INCREF(val);
*(PyObject **)addr = val;
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(val);
}
}
/* Next, process all kwargs */
for (Py_ssize_t i = 0; i < nkwargs; i++) {
char *addr;
PyObject *val;
Py_ssize_t field_index;
PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
/* Since keyword names are interned, first loop with pointer
* comparisons only. */
for (field_index = nargs; field_index < nfields; field_index++) {
PyObject *field = PyTuple_GET_ITEM(fields, field_index);
if (MS_LIKELY(kwname == field)) goto kw_found;
}
/* Fast path failed. It's more likely that this is an invalid kwarg
* than that the kwname wasn't interned. Loop from 0 this time to also
* check for parameters passed both as arg and kwarg */
for (field_index = 0; field_index < nfields; field_index++) {
PyObject *field = PyTuple_GET_ITEM(fields, field_index);
if (MS_UNICODE_EQ(kwname, field)) {
if (MS_UNLIKELY(field_index < nargs)) {
PyErr_Format(
PyExc_TypeError,
"Argument '%U' given by name and position",
kwname
);
goto error;
}
goto kw_found;
}
}
/* Unknown keyword */
PyErr_Format(PyExc_TypeError, "Unexpected keyword argument '%U'", kwname);
goto error;
kw_found:
val = args[i + nargs];
addr = (char *)self + st_type->struct_offsets[field_index];
Py_INCREF(val);
*(PyObject **)addr = val;
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(val);
}
}
/* Finally, fill in missing defaults */
if (nargs + nkwargs < nfields) {
for (Py_ssize_t field_index = nargs; field_index < nfields; field_index++) {
char *addr = (char *)self + st_type->struct_offsets[field_index];
if (MS_LIKELY(*(PyObject **)addr == NULL)) {
if (MS_LIKELY(field_index >= npos)) {
PyObject *val = PyTuple_GET_ITEM(defaults, field_index - npos);
if (MS_LIKELY(val != NODEFAULT)) {
val = get_default(val);
if (MS_UNLIKELY(val == NULL)) goto error;
*(PyObject **)addr = val;
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(val);
}
continue;
}
}
PyErr_Format(
PyExc_TypeError,
"Missing required argument '%U'",
PyTuple_GET_ITEM(fields, field_index)
);
goto error;
}
}
}
if (is_gc && !should_untrack)
PyObject_GC_Track(self);
if (Struct_post_init(st_type, self) < 0) goto error;
return self;
error:
Py_DECREF(self);
return NULL;
}
static PyObject *
Struct_repr(PyObject *self) {
StructMetaObject *st_type = (StructMetaObject *)(Py_TYPE(self));
bool omit_defaults = st_type->repr_omit_defaults == OPT_TRUE;
PyObject *fields = st_type->struct_fields;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
PyObject *defaults = NULL;
Py_ssize_t nunchecked = nfields;
if (omit_defaults) {
defaults = st_type->struct_defaults;
nunchecked = nfields - PyTuple_GET_SIZE(defaults);
}
int recursive = Py_ReprEnter(self);
if (recursive != 0) {
return (recursive < 0) ? NULL : PyUnicode_FromString("..."); /* cpylint-ignore */
}
strbuilder builder = {0};
bool first = true;
const char *name = Py_TYPE(self)->tp_name;
if (!strbuilder_extend(&builder, name, strlen(name))) goto error;
if (!strbuilder_extend_literal(&builder, "(")) goto error;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *field = PyTuple_GET_ITEM(fields, i);
PyObject *val = Struct_get_index(self, i);
if (val == NULL) goto error;
if (i >= nunchecked) {
PyObject *default_val = PyTuple_GET_ITEM(defaults, i - nunchecked);
if (is_default(val, default_val)) continue;
}
if (first) {
first = false;
}
else {
if (!strbuilder_extend_literal(&builder, ", ")) goto error;
}
if (!strbuilder_extend_unicode(&builder, field)) goto error;
if (!strbuilder_extend_literal(&builder, "=")) goto error;
PyObject *repr = PyObject_Repr(val);
if (repr == NULL) goto error;
bool ok = strbuilder_extend_unicode(&builder, repr);
Py_DECREF(repr);
if (!ok) goto error;
}
if (!strbuilder_extend_literal(&builder, ")")) goto error;
PyObject *out = strbuilder_build(&builder);
Py_ReprLeave(self);
return out;
error:
strbuilder_reset(&builder);
Py_ReprLeave(self);
return NULL;
}
static Py_hash_t
Struct_hash(PyObject *self) {
PyObject *val;
Py_ssize_t i, nfields;
Py_uhash_t acc = MS_HASH_XXPRIME_5;
StructMetaObject *st_type = (StructMetaObject *)Py_TYPE(self);
if (MS_UNLIKELY(st_type->eq == OPT_FALSE)) {
/* If `__eq__` isn't implemented, then the default pointer-based
* `__hash__` should be used */
return PyBaseObject_Type.tp_hash(self);
}
if (MS_UNLIKELY(st_type->frozen != OPT_TRUE)) {
/* If `__eq__` is implemented, only frozen types can be hashed */
return PyObject_HashNotImplemented(self);
}
if (MS_UNLIKELY(st_type->hash_offset != 0)) {
PyObject *cached_hash = *(PyObject **)((char *)self + st_type->hash_offset);
if (cached_hash != NULL) {
/* Use the cached hash */
return PyLong_AsSsize_t(cached_hash);
}
}
/* First hash the type by its pointer */
size_t type_id = (size_t)((void *)st_type);
/* The lower bits are likely to be 0; rotate by 4 */
type_id = (type_id >> 4) | (type_id << (8 * sizeof(void *) - 4));
acc += type_id * MS_HASH_XXPRIME_2;
acc = MS_HASH_XXROTATE(acc);
acc *= MS_HASH_XXPRIME_1;
/* Then hash all the fields */
nfields = StructMeta_GET_NFIELDS(Py_TYPE(self));
for (i = 0; i < nfields; i++) {
val = Struct_get_index(self, i);
if (val == NULL) return -1;
Py_uhash_t item_hash = PyObject_Hash(val);
if (item_hash == (Py_uhash_t)-1) return -1;
acc += item_hash * MS_HASH_XXPRIME_2;
acc = MS_HASH_XXROTATE(acc);
acc *= MS_HASH_XXPRIME_1;
}
acc += (1 + nfields) ^ (MS_HASH_XXPRIME_5 ^ 3527539UL);
Py_uhash_t hash = (acc == (Py_uhash_t)-1) ? 1546275796 : acc;
if (MS_UNLIKELY(st_type->hash_offset != 0)) {
/* Cache the hash */
char *addr = (char *)self + st_type->hash_offset;
PyObject *cached_hash = PyLong_FromSsize_t(hash);
if (cached_hash == NULL) return -1;
*(PyObject **)addr = cached_hash;
}
return hash;
}
static PyObject *
Struct_richcompare(PyObject *self, PyObject *other, int op) {
if (Py_TYPE(self) != Py_TYPE(other)) {
Py_RETURN_NOTIMPLEMENTED;
}
StructMetaObject *st_type = (StructMetaObject *)(Py_TYPE(self));
if (op == Py_EQ || op == Py_NE) {
if (MS_UNLIKELY(st_type->eq == OPT_FALSE)) {
Py_RETURN_NOTIMPLEMENTED;
}
}
else if (st_type->order != OPT_TRUE) {
Py_RETURN_NOTIMPLEMENTED;
}
if (
MS_UNLIKELY(op == Py_NE && (Py_TYPE(self)->tp_richcompare != Struct_richcompare))
) {
/* This case is hit when a subclass has manually defined `__eq__` but
* not `__ne__`. In this case we want to dispatch to `__eq__` and invert
* the result, rather than relying on the default `__ne__` implementation.
*/
PyObject *out = Py_TYPE(self)->tp_richcompare(self, other, Py_EQ);
if (out != NULL && out != Py_NotImplemented) {
int is_true = PyObject_IsTrue(out);
Py_DECREF(out);
if (is_true < 0) {
out = NULL;
}
else {
out = is_true ? Py_False : Py_True;
Py_INCREF(out);
}
}
return out;
}
int equal = 1;
PyObject *left = NULL, *right = NULL;
/* Only need to loop if self is not other` */
if (MS_LIKELY(self != other)) {
Py_ssize_t nfields = StructMeta_GET_NFIELDS(st_type);
for (Py_ssize_t i = 0; i < nfields; i++) {
left = Struct_get_index(self, i);
if (left == NULL) return NULL;
right = Struct_get_index(other, i);
if (right == NULL) return NULL;
equal = PyObject_RichCompareBool(left, right, Py_EQ);
if (equal < 0) return NULL;
if (equal == 0) break;
}
}
if (equal) {
if (op == Py_EQ || op == Py_GE || op == Py_LE) {
Py_RETURN_TRUE;
}
else if (op == Py_NE) {
Py_RETURN_FALSE;
}
else if (left == NULL) {
/* < or > on two 0-field or identical structs */
Py_RETURN_FALSE;
}
}
else if (op == Py_EQ) {
Py_RETURN_FALSE;
}
else if (op == Py_NE) {
Py_RETURN_TRUE;
}
/* Need to compare final element again to determine proper result */
return PyObject_RichCompare(left, right, op);
}
static PyObject *
Struct_copy(PyObject *self, PyObject *args)
{
Py_ssize_t i, nfields;
PyObject *val, *res = NULL;
res = Struct_alloc(Py_TYPE(self));
if (res == NULL)
return NULL;
nfields = StructMeta_GET_NFIELDS(Py_TYPE(self));
for (i = 0; i < nfields; i++) {
val = Struct_get_index(self, i);
if (val == NULL)
goto error;
Py_INCREF(val);
Struct_set_index(res, i, val);
}
/* If self is tracked, then copy is tracked */
if (MS_OBJECT_IS_GC(self) && MS_IS_TRACKED(self))
PyObject_GC_Track(res);
return res;
error:
Py_DECREF(res);
return NULL;
}
static PyObject *
Struct_replace(
PyObject *self,
PyObject *const *args,
Py_ssize_t nargs,
PyObject *kwnames
) {
Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
if (!check_positional_nargs(nargs, 0, 0)) return NULL;
StructMetaObject *struct_type = (StructMetaObject *)Py_TYPE(self);
PyObject *fields = struct_type->struct_fields;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
bool is_gc = MS_TYPE_IS_GC(struct_type);
bool should_untrack = is_gc;
PyObject *out = Struct_alloc((PyTypeObject *)struct_type);
if (out == NULL) return NULL;
for (Py_ssize_t i = 0; i < nkwargs; i++) {
PyObject *val;
Py_ssize_t field_index;
PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
/* Since keyword names are interned, first loop with pointer
* comparisons only. */
for (field_index = 0; field_index < nfields; field_index++) {
PyObject *field = PyTuple_GET_ITEM(fields, field_index);
if (MS_LIKELY(kwname == field)) goto kw_found;
}
for (field_index = 0; field_index < nfields; field_index++) {
PyObject *field = PyTuple_GET_ITEM(fields, field_index);
if (MS_UNICODE_EQ(kwname, field)) goto kw_found;
}
/* Unknown keyword */
PyErr_Format(
PyExc_TypeError, "`%.200s` has no field '%U'",
((PyTypeObject *)struct_type)->tp_name, kwname
);
goto error;
kw_found:
val = args[i];
Py_INCREF(val);
Struct_set_index(out, field_index, val);
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(val);
}
}
for (Py_ssize_t i = 0; i < nfields; i++) {
if (Struct_get_index_noerror(out, i) == NULL) {
PyObject *val = Struct_get_index(self, i);
if (val == NULL) goto error;
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(val);
}
Py_INCREF(val);
Struct_set_index(out, i, val);
}
}
if (is_gc && !should_untrack) {
PyObject_GC_Track(out);
}
return out;
error:
Py_DECREF(out);
return NULL;
}
static AssocList *
AssocList_FromStruct(PyObject *obj) {
if (Py_EnterRecursiveCall(" while serializing an object")) return NULL;
bool ok = false;
StructMetaObject *struct_type = (StructMetaObject *)Py_TYPE(obj);
PyObject *tag_field = struct_type->struct_tag_field;
PyObject *tag_value = struct_type->struct_tag_value;
PyObject *fields = struct_type->struct_encode_fields;
PyObject *defaults = struct_type->struct_defaults;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
Py_ssize_t npos = nfields - PyTuple_GET_SIZE(defaults);
bool omit_defaults = struct_type->omit_defaults == OPT_TRUE;
AssocList *out = AssocList_New(nfields + (tag_value != NULL));
if (out == NULL) goto cleanup;
if (tag_value != NULL) {
if (AssocList_Append(out, tag_field, tag_value) < 0) goto cleanup;
}
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *key = PyTuple_GET_ITEM(fields, i);
PyObject *val = Struct_get_index(obj, i);
if (MS_UNLIKELY(val == NULL)) goto cleanup;
if (MS_UNLIKELY(val == UNSET)) continue;
if (
!omit_defaults ||
i < npos ||
!is_default(val, PyTuple_GET_ITEM(defaults, i - npos))
) {
if (AssocList_Append(out, key, val) < 0) goto cleanup;
}
}
ok = true;
cleanup:
Py_LeaveRecursiveCall();
if (!ok) {
AssocList_Free(out);
}
return out;
}
PyDoc_STRVAR(struct_replace__doc__,
"replace(struct, / **changes)\n"
"--\n"
"\n"
"Create a new struct instance of the same type as ``struct``, replacing fields\n"
"with values from ``**changes``.\n"
"\n"
"Parameters\n"
"----------\n"
"struct: Struct\n"
" The original struct instance.\n"
"**changes:\n"
" Fields and values that should be replaced in the new struct instance.\n"
"\n"
"Returns\n"
"-------\n"
"new_struct: Struct\n"
" A new struct instance of the same type as ``struct``.\n"
"\n"
"Examples\n"
"--------\n"
">>> class Point(msgspec.Struct):\n"
"... x: int\n"
"... y: int\n"
">>> obj = Point(x=1, y=2)\n"
">>> msgspec.structs.replace(obj, x=3)\n"
"Point(x=3, y=2)\n"
"\n"
"See Also\n"
"--------\n"
"copy.replace\n"
"dataclasses.replace"
);
static PyObject*
struct_replace(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
if (!check_positional_nargs(nargs, 1, 1)) return NULL;
PyObject *obj = args[0];
if (Py_TYPE(Py_TYPE(obj)) != &StructMetaType) {
PyErr_SetString(PyExc_TypeError, "`struct` must be a `msgspec.Struct`");
return NULL;
}
return Struct_replace(obj, args + 1, 0, kwnames);
}
PyDoc_STRVAR(struct_asdict__doc__,
"asdict(struct)\n"
"--\n"
"\n"
"Convert a struct to a dict.\n"
"\n"
"Parameters\n"
"----------\n"
"struct: Struct\n"
" The struct instance.\n"
"\n"
"Returns\n"
"-------\n"
"dict\n"
"\n"
"Examples\n"
"--------\n"
">>> class Point(msgspec.Struct):\n"
"... x: int\n"
"... y: int\n"
">>> obj = Point(x=1, y=2)\n"
">>> msgspec.structs.asdict(obj)\n"
"{'x': 1, 'y': 2}\n"
"\n"
"See Also\n"
"--------\n"
"msgspec.structs.astuple\n"
"msgspec.to_builtins"
);
static PyObject*
struct_asdict(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
{
if (!check_positional_nargs(nargs, 1, 1)) return NULL;
PyObject *obj = args[0];
if (Py_TYPE(Py_TYPE(obj)) != &StructMetaType) {
PyErr_SetString(PyExc_TypeError, "`struct` must be a `msgspec.Struct`");
return NULL;
}
StructMetaObject *struct_type = (StructMetaObject *)Py_TYPE(obj);
PyObject *fields = struct_type->struct_fields;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
PyObject *out = PyDict_New();
if (out == NULL) return NULL;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *key = PyTuple_GET_ITEM(fields, i);
PyObject *val = Struct_get_index(obj, i);
if (val == NULL) goto error;
if (PyDict_SetItem(out, key, val) < 0) goto error;
}
return out;
error:
Py_DECREF(out);
return NULL;
}
PyDoc_STRVAR(struct_astuple__doc__,
"astuple(struct)\n"
"--\n"
"\n"
"Convert a struct to a tuple.\n"
"\n"
"Parameters\n"
"----------\n"
"struct: Struct\n"
" The struct instance.\n"
"\n"
"Returns\n"
"-------\n"
"tuple\n"
"\n"
"Examples\n"
"--------\n"
">>> class Point(msgspec.Struct):\n"
"... x: int\n"
"... y: int\n"
">>> obj = Point(x=1, y=2)\n"
">>> msgspec.structs.astuple(obj)\n"
"(1, 2)\n"
"\n"
"See Also\n"
"--------\n"
"msgspec.structs.asdict\n"
"msgspec.to_builtins"
);
static PyObject*
struct_astuple(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
{
if (!check_positional_nargs(nargs, 1, 1)) return NULL;
PyObject *obj = args[0];
if (Py_TYPE(Py_TYPE(obj)) != &StructMetaType) {
PyErr_SetString(PyExc_TypeError, "`struct` must be a `msgspec.Struct`");
return NULL;
}
StructMetaObject *struct_type = (StructMetaObject *)Py_TYPE(obj);
Py_ssize_t nfields = PyTuple_GET_SIZE(struct_type->struct_fields);
PyObject *out = PyTuple_New(nfields);
if (out == NULL) return NULL;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *val = Struct_get_index(obj, i);
if (val == NULL) goto error;
Py_INCREF(val);
PyTuple_SET_ITEM(out, i, val);
}
return out;
error:
Py_DECREF(out);
return NULL;
}
PyDoc_STRVAR(struct_force_setattr__doc__,
"force_setattr(struct, name, value)\n"
"--\n"
"\n"
"Set an attribute on a struct, even if the struct is frozen.\n"
"\n"
"The main use case for this is modifying a frozen struct in a ``__post_init__``\n"
"method before returning.\n"
"\n"
".. warning::\n\n"
" This function violates the guarantees of a frozen struct, and is potentially\n"
" unsafe. Only use it if you know what you're doing!\n"
"\n"
"Parameters\n"
"----------\n"
"struct: Struct\n"
" The struct instance.\n"
"name: str\n"
" The attribute name.\n"
"value: Any\n"
" The attribute value."
);
static PyObject*
struct_force_setattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
{
if (!check_positional_nargs(nargs, 3, 3)) return NULL;
PyObject *obj = args[0];
PyObject *name = args[1];
PyObject *value = args[2];
if (Py_TYPE(Py_TYPE(obj)) != &StructMetaType) {
PyErr_SetString(PyExc_TypeError, "`struct` must be a `msgspec.Struct`");
return NULL;
}
if (PyObject_GenericSetAttr(obj, name, value) < 0) {
return NULL;
}
Py_RETURN_NONE;
}
static PyObject *
Struct_reduce(PyObject *self, PyObject *args)
{
PyObject *values = NULL, *out = NULL;
StructMetaObject *st_type = (StructMetaObject *)(Py_TYPE(self));
Py_ssize_t nfields = PyTuple_GET_SIZE(st_type->struct_fields);
if (st_type->nkwonly) {
MsgspecState *mod = msgspec_get_global_state();
values = PyDict_New();
if (values == NULL) return NULL;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *field = PyTuple_GET_ITEM(st_type->struct_fields, i);
PyObject *val = Struct_get_index(self, i);
if (val == NULL) goto cleanup;
if (PyDict_SetItem(values, field, val) < 0) goto cleanup;
}
out = Py_BuildValue("O(OO)", mod->rebuild, Py_TYPE(self), values);
}
else {
values = PyTuple_New(nfields);
if (values == NULL) return NULL;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *val = Struct_get_index(self, i);
if (val == NULL) goto cleanup;
Py_INCREF(val);
PyTuple_SET_ITEM(values, i, val);
}
out = PyTuple_Pack(2, Py_TYPE(self), values);
}
cleanup:
Py_DECREF(values);
return out;
}
static PyObject *
Struct_rich_repr(PyObject *self, PyObject *args) {
StructMetaObject *st_type = (StructMetaObject *)(Py_TYPE(self));
bool omit_defaults = st_type->repr_omit_defaults == OPT_TRUE;
PyObject *fields = st_type->struct_fields;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
PyObject *defaults = NULL;
Py_ssize_t nunchecked = nfields;
if (omit_defaults) {
defaults = st_type->struct_defaults;
nunchecked = nfields - PyTuple_GET_SIZE(defaults);
}
PyObject *out = PyList_New(0);
if (out == NULL) return NULL;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *field = PyTuple_GET_ITEM(fields, i);
PyObject *val = Struct_get_index(self, i);
if (i >= nunchecked) {
PyObject *default_val = PyTuple_GET_ITEM(defaults, i - nunchecked);
if (is_default(val, default_val)) continue;
}
if (val == NULL) goto error;
PyObject *part = PyTuple_Pack(2, field, val);
if (part == NULL) goto error;
int status = PyList_Append(out, part);
Py_DECREF(part);
if (status < 0) goto error;
}
return out;
error:
Py_DECREF(out);
return NULL;
}
static PyObject *
StructMixin_fields(PyObject *self, void *closure) {
PyObject *out = ((StructMetaObject *)Py_TYPE(self))->struct_fields;
Py_INCREF(out);
return out;
}
static PyObject *
StructMixin_encode_fields(PyObject *self, void *closure) {
PyObject *out = ((StructMetaObject *)Py_TYPE(self))->struct_encode_fields;
Py_INCREF(out);
return out;
}
static PyObject *
StructMixin_defaults(PyObject *self, void *closure) {
PyObject *out = ((StructMetaObject *)Py_TYPE(self))->struct_defaults;
Py_INCREF(out);
return out;
}
static PyObject*
StructMixin_config(StructMetaObject *self, void *closure) {
return StructConfig_New((StructMetaObject *)Py_TYPE(self));
}
static PyMethodDef Struct_methods[] = {
{"__copy__", Struct_copy, METH_NOARGS, "copy a struct"},
{"__replace__", (PyCFunction) Struct_replace, METH_FASTCALL | METH_KEYWORDS, "create a new struct with replacements" },
{"__reduce__", Struct_reduce, METH_NOARGS, "reduce a struct"},
{"__rich_repr__", Struct_rich_repr, METH_NOARGS, "rich repr"},
{NULL, NULL},
};
static PyGetSetDef StructMixin_getset[] = {
{"__struct_fields__", (getter) StructMixin_fields, NULL, "Struct fields", NULL},
{"__struct_encode_fields__", (getter) StructMixin_encode_fields, NULL, "Struct encoded field names", NULL},
{"__struct_defaults__", (getter) StructMixin_defaults, NULL, "Struct defaults", NULL},
{"__struct_config__", (getter) StructMixin_config, NULL, "Struct configuration", NULL},
{NULL},
};
static PyTypeObject StructMixinType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core._StructMixin",
.tp_basicsize = 0,
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_setattro = Struct_setattro_default,
.tp_repr = Struct_repr,
.tp_richcompare = Struct_richcompare,
.tp_hash = Struct_hash,
.tp_methods = Struct_methods,
.tp_getset = StructMixin_getset,
};
PyDoc_STRVAR(Struct__doc__,
"A base class for defining efficient serializable objects.\n"
"\n"
"Fields are defined using type annotations. Fields may optionally have\n"
"default values, which result in keyword parameters to the constructor.\n"
"\n"
"Structs automatically define ``__init__``, ``__eq__``, ``__repr__``, and\n"
"``__copy__`` methods. Additional methods can be defined on the class as\n"
"needed. Note that ``__init__``/``__new__`` cannot be overridden, but other\n"
"methods can. A tuple of the field names is available on the class via the\n"
"``__struct_fields__`` attribute if needed.\n"
"\n"
"Additional class options can be enabled by passing keywords to the class\n"
"definition (see example below). These configuration options may also be\n"
"inspected at runtime through the ``__struct_config__`` attribute.\n"
"\n"
"Configuration\n"
"-------------\n"
"frozen: bool, default False\n"
" Whether instances of this type are pseudo-immutable. If true, attribute\n"
" assignment is disabled and a corresponding ``__hash__`` is defined.\n"
"order: bool, default False\n"
" If True, ``__lt__``, `__le__``, ``__gt__``, and ``__ge__`` methods\n"
" will be generated for this type.\n"
"eq: bool, default True\n"
" If True (the default), an ``__eq__`` method will be generated for this\n"
" type. Set to False to compare based on instance identity alone.\n"
"kw_only: bool, default False\n"
" If True, all fields will be treated as keyword-only arguments in the\n"
" generated ``__init__`` method. Default is False.\n"
"omit_defaults: bool, default False\n"
" Whether fields should be omitted from encoding if the corresponding value\n"
" is the default for that field. Enabling this may reduce message size, and\n"
" often also improve encoding & decoding performance.\n"
"forbid_unknown_fields: bool, default False\n"
" If True, an error is raised if an unknown field is encountered while\n"
" decoding structs of this type. If False (the default), no error is raised\n"
" and the unknown field is skipped.\n"
"tag: str, int, bool, callable, or None, default None\n"
" Used along with ``tag_field`` for configuring tagged union support. If\n"
" either are non-None, then the struct is considered \"tagged\". In this case,\n"
" an extra field (the ``tag_field``) and value (the ``tag``) are added to the\n"
" encoded message, which can be used to differentiate message types during\n"
" decoding.\n"
"\n"
" Set ``tag=True`` to enable the default tagged configuration (``tag_field``\n"
" is ``\"type\"``, ``tag`` is the class name). Alternatively, you can provide\n"
" a string (or less commonly int) value directly to be used as the tag\n"
" (e.g. ``tag=\"my-tag-value\"``).``tag`` can also be passed a callable that\n"
" takes the class qualname and returns a valid tag value (e.g.\n"
" ``tag=str.lower``). See the docs for more information.\n"
"tag_field: str or None, default None\n"
" The field name to use for tagged union support. If ``tag`` is non-None,\n"
" then this defaults to ``\"type\"``. See the ``tag`` docs above for more\n"
" information.\n"
"rename: str, mapping, callable, or None, default None\n"
" Controls renaming the field names used when encoding/decoding the struct.\n"
" May be one of ``\"lower\"``, ``\"upper\"``, ``\"camel\"``, ``\"pascal\"``, or\n"
" ``\"kebab\"`` to rename in lowercase, UPPERCASE, camelCase, PascalCase,\n"
" or kebab-case respectively. May also be a mapping from field names to the\n"
" renamed names (missing fields are not renamed). Alternatively, may be a\n"
" callable that takes the field name and returns a new name or ``None`` to\n"
" not rename that field. Default is ``None`` for no field renaming.\n"
"repr_omit_defaults: bool, default False\n"
" Whether fields should be omitted from the generated repr if the\n"
" corresponding value is the default for that field.\n"
"array_like: bool, default False\n"
" If True, this struct type will be treated as an array-like type during\n"
" encoding/decoding, rather than a dict-like type (the default). This may\n"
" improve performance, at the cost of a more inscrutable message encoding.\n"
"gc: bool, default True\n"
" Whether garbage collection is enabled for this type. Disabling this *may*\n"
" help reduce GC pressure, but will prevent reference cycles composed of only\n"
" ``gc=False`` from being collected. It is the user's responsibility to ensure\n"
" that reference cycles don't occur when setting ``gc=False``.\n"
"weakref: bool, default False\n"
" Whether instances of this type support weak references. Defaults to False.\n"
"dict: bool, default False\n"
" Whether instances of this type will include a ``__dict__``. Setting this to\n"
" True will allow adding additional undeclared attributes to a struct instance,\n"
" which may be useful for holding private runtime state. Defaults to False.\n"
"cache_hash: bool, default False\n"
" If enabled, the hash of a frozen struct instance will be computed at most\n"
" once, and then cached on the instance for further reuse. For expensive\n"
" hash values this can improve performance at the cost of a small amount of\n"
" memory usage.\n"
"\n"
"Examples\n"
"--------\n"
"Here we define a new `Struct` type for describing a dog. It has three fields;\n"
"two required and one optional.\n"
"\n"
">>> class Dog(Struct):\n"
"... name: str\n"
"... breed: str\n"
"... is_good_boy: bool = True\n"
"...\n"
">>> Dog('snickers', breed='corgi')\n"
"Dog(name='snickers', breed='corgi', is_good_boy=True)\n"
"\n"
"Additional struct options can be set as part of the class definition. Here\n"
"we define a new `Struct` type for a frozen `Point` object.\n"
"\n"
">>> class Point(Struct, frozen=True):\n"
"... x: float\n"
"... y: float\n"
"...\n"
">>> {Point(1.5, 2.0): 1} # frozen structs are hashable\n"
"{Point(x=1.5, y=2.0): 1}"
);
static int
LiteralInfo_traverse(LiteralInfo *self, visitproc visit, void *arg)
{
Py_VISIT(self->str_lookup);
Py_VISIT(self->int_lookup);
return 0;
}
static int
LiteralInfo_clear(LiteralInfo *self)
{
Py_CLEAR(self->str_lookup);
Py_CLEAR(self->int_lookup);
return 0;
}
static void
LiteralInfo_dealloc(LiteralInfo *self)
{
PyObject_GC_UnTrack(self);
LiteralInfo_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyTypeObject LiteralInfo_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.LiteralInfo",
.tp_basicsize = sizeof(LiteralInfo),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_clear = (inquiry)LiteralInfo_clear,
.tp_traverse = (traverseproc)LiteralInfo_traverse,
.tp_dealloc = (destructor)LiteralInfo_dealloc,
};
static PyObject *
TypedDictInfo_Convert(PyObject *obj) {
PyObject *annotations = NULL, *required = NULL;
TypedDictInfo *info = NULL;
MsgspecState *mod = msgspec_get_global_state();
bool cache_set = false, succeeded = false;
PyObject *cached = NULL;
if (get_msgspec_cache(mod, obj, &TypedDictInfo_Type, &cached)) {
return cached;
}
/* Not cached, extract fields from TypedDict object */
PyObject *temp = PyObject_CallOneArg(mod->get_typeddict_info, obj);
if (temp == NULL) return NULL;
annotations = PyTuple_GET_ITEM(temp, 0);
Py_INCREF(annotations);
required = PyTuple_GET_ITEM(temp, 1);
Py_INCREF(required);
Py_DECREF(temp);
/* Allocate and zero-out a new TypedDictInfo object */
Py_ssize_t nfields = PyDict_GET_SIZE(annotations);
info = PyObject_GC_NewVar(TypedDictInfo, &TypedDictInfo_Type, nfields);
if (info == NULL) goto cleanup;
for (Py_ssize_t i = 0; i < nfields; i++) {
info->fields[i].key = NULL;
info->fields[i].type = NULL;
}
/* Initialize nrequired to -1 as a flag in case of a recursive TypedDict
* definition. */
info->nrequired = -1;
/* If not already cached, then cache on TypedDict object _before_
* traversing fields. This is to ensure self-referential TypedDicts work. */
if (PyObject_SetAttr(obj, mod->str___msgspec_cache__, (PyObject *)info) < 0) {
goto cleanup;
}
cache_set = true;
/* Traverse fields and initialize TypedDictInfo */
Py_ssize_t pos = 0, i = 0;
PyObject *key, *val;
while (PyDict_Next(annotations, &pos, &key, &val)) {
TypeNode *type = TypeNode_Convert(val);
if (type == NULL) goto cleanup;
Py_INCREF(key);
info->fields[i].key = key;
info->fields[i].type = type;
int contains = PySet_Contains(required, key);
if (contains == -1) goto cleanup;
if (contains) { type->types |= MS_EXTRA_FLAG; }
i++;
}
info->nrequired = PySet_GET_SIZE(required);
PyObject_GC_Track(info);
succeeded = true;
cleanup:
if (!succeeded) {
Py_CLEAR(info);
if (cache_set) {
/* An error occurred after the cache was created and set on the
* TypedDict. We need to delete the attribute. Fetch and restore the
* original exception to avoid DelAttr silently clearing it on rare
* occasions. */
PyObject *err_type, *err_value, *err_tb;
PyErr_Fetch(&err_type, &err_value, &err_tb);
PyObject_DelAttr(obj, mod->str___msgspec_cache__);
PyErr_Restore(err_type, err_value, err_tb);
}
}
Py_XDECREF(annotations);
Py_XDECREF(required);
return (PyObject *)info;
}
static MS_INLINE PyObject *
TypedDictInfo_lookup_key(
TypedDictInfo *self, const char * key, Py_ssize_t key_size,
TypeNode **type, Py_ssize_t *pos
) {
const char *field;
Py_ssize_t nfields, field_size, i, offset = *pos;
nfields = Py_SIZE(self);
for (i = offset; i < nfields; i++) {
field = unicode_str_and_size_nocheck(self->fields[i].key, &field_size);
if (key_size == field_size && memcmp(key, field, key_size) == 0) {
*pos = i < (nfields - 1) ? (i + 1) : 0;
*type = self->fields[i].type;
return self->fields[i].key;
}
}
for (i = 0; i < offset; i++) {
field = unicode_str_and_size_nocheck(self->fields[i].key, &field_size);
if (key_size == field_size && memcmp(key, field, key_size) == 0) {
*pos = i + 1;
*type = self->fields[i].type;
return self->fields[i].key;
}
}
return NULL;
}
static void
TypedDictInfo_error_missing(TypedDictInfo *self, PyObject *dict, PathNode *path) {
Py_ssize_t nfields = Py_SIZE(self);
for (Py_ssize_t i = 0; i < nfields; i++) {
if (self->fields[i].type->types & MS_EXTRA_FLAG) {
PyObject *field = self->fields[i].key;
int contains = PyDict_Contains(dict, field);
if (contains < 0) return;
if (contains == 0) {
ms_missing_required_field(field, path);
return;
}
}
}
}
static int
TypedDictInfo_traverse(TypedDictInfo *self, visitproc visit, void *arg)
{
for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
TypedDictField *field = &(self->fields[i]);
if (field->key != NULL) {
int out = TypeNode_traverse(field->type, visit, arg);
if (out != 0) return out;
}
}
return 0;
}
static int
TypedDictInfo_clear(TypedDictInfo *self)
{
for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
Py_CLEAR(self->fields[i].key);
TypeNode_Free(self->fields[i].type);
self->fields[i].type = NULL;
}
return 0;
}
static void
TypedDictInfo_dealloc(TypedDictInfo *self)
{
PyObject_GC_UnTrack(self);
TypedDictInfo_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyTypeObject TypedDictInfo_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.TypedDictInfo",
.tp_basicsize = sizeof(TypedDictInfo),
.tp_itemsize = sizeof(TypedDictField),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_clear = (inquiry)TypedDictInfo_clear,
.tp_traverse = (traverseproc)TypedDictInfo_traverse,
.tp_dealloc = (destructor)TypedDictInfo_dealloc,
};
static PyObject *
DataclassInfo_Convert(PyObject *obj) {
PyObject *cls = NULL, *fields = NULL, *field_defaults = NULL;
PyObject *pre_init = NULL, *post_init = NULL;
DataclassInfo *info = NULL;
MsgspecState *mod = msgspec_get_global_state();
bool cache_set = false, succeeded = false;
PyObject *cached = NULL;
if (get_msgspec_cache(mod, obj, &DataclassInfo_Type, &cached)) {
return cached;
}
/* Not cached, extract fields from Dataclass object */
PyObject *temp = PyObject_CallOneArg(mod->get_dataclass_info, obj);
if (temp == NULL) return NULL;
cls = PyTuple_GET_ITEM(temp, 0);
Py_INCREF(cls);
fields = PyTuple_GET_ITEM(temp, 1);
Py_INCREF(fields);
field_defaults = PyTuple_GET_ITEM(temp, 2);
Py_INCREF(field_defaults);
pre_init = PyTuple_GET_ITEM(temp, 3);
Py_INCREF(pre_init);
post_init = PyTuple_GET_ITEM(temp, 4);
Py_INCREF(post_init);
Py_DECREF(temp);
/* Allocate and zero-out a new DataclassInfo object */
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
info = PyObject_GC_NewVar(DataclassInfo, &DataclassInfo_Type, nfields);
if (info == NULL) goto cleanup;
for (Py_ssize_t i = 0; i < nfields; i++) {
info->fields[i].key = NULL;
info->fields[i].type = NULL;
}
Py_INCREF(field_defaults);
info->defaults = field_defaults;
Py_INCREF(cls);
info->class = cls;
if (pre_init == Py_None) {
info->pre_init = NULL;
}
else {
Py_INCREF(pre_init);
info->pre_init = pre_init;
}
if (post_init == Py_None) {
info->post_init = NULL;
}
else {
Py_INCREF(post_init);
info->post_init = post_init;
}
/* If not already cached, then cache on Dataclass object _before_
* traversing fields. This is to ensure self-referential Dataclasses work. */
if (PyObject_SetAttr(obj, mod->str___msgspec_cache__, (PyObject *)info) < 0) {
goto cleanup;
}
cache_set = true;
/* Traverse fields and initialize DataclassInfo */
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *field = PyTuple_GET_ITEM(fields, i);
TypeNode *type = TypeNode_Convert(PyTuple_GET_ITEM(field, 1));
if (type == NULL) goto cleanup;
/* If field has a default factory, set extra flag bit */
if (PyObject_IsTrue(PyTuple_GET_ITEM(field, 2))) {
type->types |= MS_EXTRA_FLAG;
}
info->fields[i].type = type;
info->fields[i].key = PyTuple_GET_ITEM(field, 0);
Py_INCREF(info->fields[i].key);
}
PyObject_GC_Track(info);
succeeded = true;
cleanup:
if (!succeeded) {
Py_CLEAR(info);
if (cache_set) {
/* An error occurred after the cache was created and set on the
* Dataclass. We need to delete the attribute. Fetch and restore the
* original exception to avoid DelAttr silently clearing it on rare
* occasions. */
PyObject *err_type, *err_value, *err_tb;
PyErr_Fetch(&err_type, &err_value, &err_tb);
PyObject_DelAttr(obj, mod->str___msgspec_cache__);
PyErr_Restore(err_type, err_value, err_tb);
}
}
Py_XDECREF(cls);
Py_XDECREF(fields);
Py_XDECREF(field_defaults);
Py_XDECREF(pre_init);
Py_XDECREF(post_init);
return (PyObject *)info;
}
static MS_INLINE PyObject *
DataclassInfo_lookup_key(
DataclassInfo *self, const char * key, Py_ssize_t key_size,
TypeNode **type, Py_ssize_t *pos
) {
const char *field;
Py_ssize_t nfields, field_size, i, offset = *pos;
nfields = Py_SIZE(self);
for (i = offset; i < nfields; i++) {
field = unicode_str_and_size_nocheck(self->fields[i].key, &field_size);
if (key_size == field_size && memcmp(key, field, key_size) == 0) {
*pos = i < (nfields - 1) ? (i + 1) : 0;
*type = self->fields[i].type;
return self->fields[i].key;
}
}
for (i = 0; i < offset; i++) {
field = unicode_str_and_size_nocheck(self->fields[i].key, &field_size);
if (key_size == field_size && memcmp(key, field, key_size) == 0) {
*pos = i + 1;
*type = self->fields[i].type;
return self->fields[i].key;
}
}
return NULL;
}
static int
DataclassInfo_post_decode(DataclassInfo *self, PyObject *obj, PathNode *path) {
Py_ssize_t nfields = Py_SIZE(self);
Py_ssize_t ndefaults = PyTuple_GET_SIZE(self->defaults);
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *name = self->fields[i].key;
if (!PyObject_HasAttr(obj, name)) {
if (i < (nfields - ndefaults)) {
ms_missing_required_field(name, path);
return -1;
}
else {
PyObject *default_value = PyTuple_GET_ITEM(
self->defaults, i - (nfields - ndefaults)
);
bool is_factory = self->fields[i].type->types & MS_EXTRA_FLAG;
if (is_factory) {
default_value = PyObject_CallNoArgs(default_value);
if (default_value == NULL) return -1;
}
int status = PyObject_GenericSetAttr(obj, name, default_value);
if (is_factory) {
Py_DECREF(default_value);
}
if (status < 0) return -1;
}
}
}
if (self->post_init != NULL) {
PyObject *res = PyObject_CallOneArg(self->post_init, obj);
if (res == NULL) {
ms_maybe_wrap_validation_error(path);
return -1;
}
Py_DECREF(res);
}
return 0;
}
static int
DataclassInfo_traverse(DataclassInfo *self, visitproc visit, void *arg)
{
for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
DataclassField *field = &(self->fields[i]);
if (field->key != NULL) {
int out = TypeNode_traverse(field->type, visit, arg);
if (out != 0) return out;
}
}
Py_VISIT(self->defaults);
Py_VISIT(self->class);
Py_VISIT(self->pre_init);
Py_VISIT(self->post_init);
return 0;
}
static int
DataclassInfo_clear(DataclassInfo *self)
{
for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
Py_CLEAR(self->fields[i].key);
TypeNode_Free(self->fields[i].type);
self->fields[i].type = NULL;
}
Py_CLEAR(self->defaults);
Py_CLEAR(self->class);
Py_CLEAR(self->pre_init);
Py_CLEAR(self->post_init);
return 0;
}
static void
DataclassInfo_dealloc(DataclassInfo *self)
{
PyObject_GC_UnTrack(self);
DataclassInfo_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyTypeObject DataclassInfo_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.DataclassInfo",
.tp_basicsize = sizeof(DataclassInfo),
.tp_itemsize = sizeof(DataclassField),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_clear = (inquiry)DataclassInfo_clear,
.tp_traverse = (traverseproc)DataclassInfo_traverse,
.tp_dealloc = (destructor)DataclassInfo_dealloc,
};
static PyObject *
NamedTupleInfo_Convert(PyObject *obj) {
MsgspecState *mod = msgspec_get_global_state();
NamedTupleInfo *info = NULL;
PyObject *annotations = NULL, *cls = NULL, *fields = NULL;
PyObject *defaults = NULL, *defaults_list = NULL;
bool cache_set = false, succeeded = false;
PyObject *cached = NULL;
if (get_msgspec_cache(mod, obj, &NamedTupleInfo_Type, &cached)) {
return cached;
}
/* Not cached, extract fields from NamedTuple object */
annotations = PyObject_CallOneArg(mod->get_class_annotations, obj);
if (annotations == NULL) goto cleanup;
if (PyType_Check(obj)) {
Py_INCREF(obj);
cls = obj;
}
else {
cls = PyObject_GetAttr(obj, mod->str___origin__);
if (cls == NULL) goto cleanup;
}
fields = PyObject_GetAttr(cls, mod->str__fields);
if (fields == NULL) goto cleanup;
defaults = PyObject_GetAttr(cls, mod->str__field_defaults);
if (defaults == NULL) goto cleanup;
/* Allocate and zero-out a new NamedTupleInfo object */
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
info = PyObject_GC_NewVar(NamedTupleInfo, &NamedTupleInfo_Type, nfields);
if (info == NULL) goto cleanup;
info->class = NULL;
info->defaults = NULL;
for (Py_ssize_t i = 0; i < nfields; i++) {
info->types[i] = NULL;
}
/* If not already cached, then cache on NamedTuple object _before_
* traversing fields. This is to ensure self-referential NamedTuple work. */
if (PyObject_SetAttr(obj, mod->str___msgspec_cache__, (PyObject *)info) < 0) {
goto cleanup;
}
cache_set = true;
/* Traverse fields and initialize NamedTupleInfo */
defaults_list = PyList_New(0);
if (defaults_list == NULL) goto cleanup;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *field = PyTuple_GET_ITEM(fields, i);
/* Get the field type, defaulting to Any */
PyObject *type_obj = PyDict_GetItem(annotations, field);
if (type_obj == NULL) {
type_obj = mod->typing_any;
}
/* Convert the type to a TypeNode */
TypeNode *type = TypeNode_Convert(type_obj);
if (type == NULL) goto cleanup;
info->types[i] = type;
/* Get the field default (if any), and append it to the list */
PyObject *default_obj = PyDict_GetItem(defaults, field);
if (default_obj != NULL) {
if (PyList_Append(defaults_list, default_obj) < 0) goto cleanup;
}
}
Py_INCREF(cls);
info->class = cls;
info->defaults = PyList_AsTuple(defaults_list);
if (info->defaults == NULL) goto cleanup;
PyObject_GC_Track(info);
succeeded = true;
cleanup:
if (!succeeded) {
Py_CLEAR(info);
if (cache_set) {
/* An error occurred after the cache was created and set on the
* NamedTuple. We need to delete the attribute. Fetch and restore
* the original exception to avoid DelAttr silently clearing it
* on rare occasions. */
PyObject *err_type, *err_value, *err_tb;
PyErr_Fetch(&err_type, &err_value, &err_tb);
PyObject_DelAttr(obj, mod->str___msgspec_cache__);
PyErr_Restore(err_type, err_value, err_tb);
}
}
Py_XDECREF(cls);
Py_XDECREF(annotations);
Py_XDECREF(fields);
Py_XDECREF(defaults);
Py_XDECREF(defaults_list);
return (PyObject *)info;
}
static int
NamedTupleInfo_traverse(NamedTupleInfo *self, visitproc visit, void *arg)
{
Py_VISIT(self->class);
Py_VISIT(self->defaults);
for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
int out = TypeNode_traverse(self->types[i], visit, arg);
if (out != 0) return out;
}
return 0;
}
static int
NamedTupleInfo_clear(NamedTupleInfo *self)
{
Py_CLEAR(self->class);
Py_CLEAR(self->defaults);
for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
TypeNode_Free(self->types[i]);
self->types[i] = NULL;
}
return 0;
}
static void
NamedTupleInfo_dealloc(NamedTupleInfo *self)
{
PyObject_GC_UnTrack(self);
NamedTupleInfo_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyTypeObject NamedTupleInfo_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec._core.NamedTupleInfo",
.tp_basicsize = sizeof(NamedTupleInfo),
.tp_itemsize = sizeof(TypeNode *),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_clear = (inquiry)NamedTupleInfo_clear,
.tp_traverse = (traverseproc)NamedTupleInfo_traverse,
.tp_dealloc = (destructor)NamedTupleInfo_dealloc,
};
/*************************************************************************
* Ext *
*************************************************************************/
typedef struct Ext {
PyObject_HEAD
long code;
PyObject *data;
} Ext;
static PyObject *
Ext_New(long code, PyObject *data) {
Ext *out = (Ext *)Ext_Type.tp_alloc(&Ext_Type, 0);
if (out == NULL)
return NULL;
out->code = code;
Py_INCREF(data);
out->data = data;
return (PyObject *)out;
}
PyDoc_STRVAR(Ext__doc__,
"Ext(code, data)\n"
"--\n"
"\n"
"A record representing a MessagePack Extension Type.\n"
"\n"
"Parameters\n"
"----------\n"
"code : int\n"
" The integer type code for this extension. Must be between -128 and 127.\n"
"data : bytes, bytearray, or memoryview\n"
" The byte buffer for this extension. One of bytes, bytearray, memoryview,\n"
" or any object that implements the buffer protocol."
);
static PyObject *
Ext_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
PyObject *pycode, *data;
long code;
Py_ssize_t nargs, nkwargs;
nargs = PyTuple_GET_SIZE(args);
nkwargs = (kwargs == NULL) ? 0 : PyDict_GET_SIZE(kwargs);
if (nkwargs != 0) {
PyErr_SetString(
PyExc_TypeError,
"Ext takes no keyword arguments"
);
return NULL;
}
else if (nargs != 2) {
PyErr_Format(
PyExc_TypeError,
"Ext expected 2 arguments, got %zd",
nargs
);
return NULL;
}
pycode = PyTuple_GET_ITEM(args, 0);
data = PyTuple_GET_ITEM(args, 1);
if (PyLong_CheckExact(pycode)) {
code = PyLong_AsLong(pycode);
if ((code == -1 && PyErr_Occurred()) || code > 127 || code < -128) {
PyErr_SetString(
PyExc_ValueError,
"code must be an int between -128 and 127"
);
return NULL;
}
}
else {
PyErr_Format(
PyExc_TypeError,
"code must be an int, got %.200s",
Py_TYPE(pycode)->tp_name
);
return NULL;
}
if (!(PyBytes_CheckExact(data) || PyByteArray_CheckExact(data) || PyObject_CheckBuffer(data))) {
PyErr_Format(
PyExc_TypeError,
"data must be a bytes, bytearray, or buffer-like object, got %.200s",
Py_TYPE(data)->tp_name
);
return NULL;
}
return Ext_New(code, data);
}
static void
Ext_dealloc(Ext *self)
{
Py_XDECREF(self->data);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyMemberDef Ext_members[] = {
{"code", T_INT, offsetof(Ext, code), READONLY, "The extension type code"},
{"data", T_OBJECT_EX, offsetof(Ext, data), READONLY, "The extension data payload"},
{NULL},
};
static PyObject *
Ext_reduce(PyObject *self, PyObject *unused)
{
return Py_BuildValue("O(bO)", Py_TYPE(self), ((Ext*)self)->code, ((Ext*)self)->data);
}
static PyObject *
Ext_richcompare(PyObject *self, PyObject *other, int op) {
int status;
PyObject *out;
Ext *ex_self, *ex_other;
if (Py_TYPE(other) != &Ext_Type) {
Py_RETURN_NOTIMPLEMENTED;
}
if (op != Py_EQ && op != Py_NE) {
Py_RETURN_NOTIMPLEMENTED;
}
ex_self = (Ext *)self;
ex_other = (Ext *)other;
status = ex_self->code == ex_other->code;
if (!status) {
out = (op == Py_EQ) ? Py_False : Py_True;
}
else {
status = PyObject_RichCompareBool(ex_self->data, ex_other->data, op);
if (status == -1) return NULL;
out = status ? Py_True : Py_False;
}
Py_INCREF(out);
return out;
}
static PyMethodDef Ext_methods[] = {
{"__reduce__", Ext_reduce, METH_NOARGS, "reduce an Ext"},
{NULL, NULL},
};
static PyTypeObject Ext_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec.msgpack.Ext",
.tp_doc = Ext__doc__,
.tp_basicsize = sizeof(Ext),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_new = Ext_new,
.tp_dealloc = (destructor) Ext_dealloc,
.tp_richcompare = Ext_richcompare,
.tp_members = Ext_members,
.tp_methods = Ext_methods
};
/*************************************************************************
* Dataclass Utilities *
*************************************************************************/
typedef struct {
PyObject *obj;
PyObject *fields;
PyObject *dict;
Py_ssize_t fields_pos;
Py_ssize_t dict_pos;
bool fastpath;
bool standard_getattr;
} DataclassIter;
static bool
dataclass_iter_setup(DataclassIter *iter, PyObject *obj, PyObject *fields) {
iter->dict = NULL;
if (MS_UNLIKELY(!PyDict_CheckExact(fields))) {
PyErr_Format(PyExc_RuntimeError, "%R.__dataclass_fields__ is not a dict", obj);
return false;
}
iter->obj = obj;
iter->fields = fields;
iter->fields_pos = 0;
iter->dict_pos = 0;
iter->fastpath = false;
iter->standard_getattr = (
Py_TYPE(obj)->tp_getattro == PyObject_GenericGetAttr
);
if (iter->standard_getattr) {
iter->dict = PyObject_GenericGetDict(obj, NULL);
if (iter->dict == NULL) {
PyErr_Clear();
}
else if (PyDict_GET_SIZE(fields) == PyDict_GET_SIZE(iter->dict)) {
iter->fastpath = true;
}
}
return true;
}
static void
dataclass_iter_cleanup(DataclassIter *iter) {
Py_XDECREF(iter->dict);
}
static MS_INLINE bool
dataclass_iter_next(
DataclassIter *iter,
PyObject **field_name,
PyObject **field_val
) {
PyObject *name, *key, *val;
next_field:
if (!PyDict_Next(iter->fields, &(iter->fields_pos), &name, NULL)) {
return false;
}
if (MS_UNLIKELY(!PyUnicode_CheckExact(name))) goto next_field;
if (MS_LIKELY(iter->fastpath)) {
if (
PyDict_Next(iter->dict, &(iter->dict_pos), &key, &val) &&
(key == name)
) {
Py_INCREF(val);
goto found_val;
}
else {
iter->fastpath = false;
}
}
PyTypeObject *type = Py_TYPE(iter->obj);
if (MS_LIKELY(iter->standard_getattr)) {
if (iter->dict != NULL) {
/* We know it's already hashed, it came from a dict */
Py_hash_t hash = ((PyASCIIObject *)name)->hash;
val = _PyDict_GetItem_KnownHash(iter->dict, name, hash);
if (val != NULL) {
Py_INCREF(val);
goto found_val;
}
}
PyObject *descr = _PyType_Lookup(type, name);
if (descr != NULL) {
descrgetfunc get = Py_TYPE(descr)->tp_descr_get;
descrsetfunc set = Py_TYPE(descr)->tp_descr_set;
if (get != NULL && set != NULL) {
Py_INCREF(descr);
val = get(descr, iter->obj, (PyObject *)type);
Py_DECREF(descr);
if (val != NULL) goto found_val;
PyErr_Clear();
}
}
goto next_field;
}
else {
val = type->tp_getattro(iter->obj, name);
if (val == NULL) {
PyErr_Clear();
goto next_field;
}
goto found_val;
}
found_val:
if (MS_UNLIKELY(val == UNSET)) {
Py_DECREF(val);
goto next_field;
}
*field_name = name;
*field_val = val;
return true;
}
static AssocList *
AssocList_FromDataclass(PyObject *obj, PyObject *fields)
{
if (Py_EnterRecursiveCall(" while serializing an object")) return NULL;
bool ok = false;
AssocList *out = NULL;
DataclassIter iter;
if (!dataclass_iter_setup(&iter, obj, fields)) goto cleanup;
out = AssocList_New(PyDict_GET_SIZE(fields));
if (out == NULL) goto cleanup;
PyObject *field, *val;
while (dataclass_iter_next(&iter, &field, &val)) {
int status = AssocList_Append(out, field, val);
Py_DECREF(val);
if (status < 0) goto cleanup;
}
ok = true;
cleanup:
Py_LeaveRecursiveCall();
dataclass_iter_cleanup(&iter);
if (!ok) {
AssocList_Free(out);
return NULL;
}
return out;
}
/*************************************************************************
* Object Utilities *
*************************************************************************/
static AssocList *
AssocList_FromObject(PyObject *obj) {
bool ok = false;
PyObject *dict = NULL;
AssocList *out = NULL;
if (Py_EnterRecursiveCall(" while serializing an object")) return NULL;
dict = PyObject_GenericGetDict(obj, NULL);
if (MS_UNLIKELY(dict == NULL)) {
PyErr_Clear();
}
/* Determine max size of AssocList needed */
Py_ssize_t max_size = (dict == NULL) ? 0 : PyDict_GET_SIZE(dict);
PyTypeObject *type = Py_TYPE(obj);
while (type != NULL) {
max_size += Py_SIZE(type);
type = type->tp_base;
}
out = AssocList_New(max_size);
if (out == NULL) goto cleanup;
/* Append everything in `__dict__` */
if (dict != NULL) {
PyObject *key, *val;
Py_ssize_t pos = 0;
while (PyDict_Next(dict, &pos, &key, &val)) {
if (MS_LIKELY(PyUnicode_CheckExact(key))) {
Py_ssize_t key_len;
if (MS_UNLIKELY(val == UNSET)) continue;
const char* key_buf = unicode_str_and_size(key, &key_len);
if (MS_UNLIKELY(key_buf == NULL)) goto cleanup;
if (MS_UNLIKELY(*key_buf == '_')) continue;
if (MS_UNLIKELY(AssocList_Append(out, key, val) < 0)) goto cleanup;
}
}
}
/* Then append everything in slots */
type = Py_TYPE(obj);
while (type != NULL) {
Py_ssize_t n = Py_SIZE(type);
if (n) {
PyMemberDef *mp = MS_PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
for (Py_ssize_t i = 0; i < n; i++, mp++) {
if (MS_LIKELY(mp->type == T_OBJECT_EX && !(mp->flags & READONLY))) {
char *addr = (char *)obj + mp->offset;
PyObject *val = *(PyObject **)addr;
if (MS_UNLIKELY(val == UNSET)) continue;
if (MS_UNLIKELY(val == NULL)) continue;
if (MS_UNLIKELY(*mp->name == '_')) continue;
AssocList_AppendCStr(out, mp->name, val);
}
}
}
type = type->tp_base;
}
ok = true;
cleanup:
Py_XDECREF(dict);
Py_LeaveRecursiveCall();
if (!ok) {
AssocList_Free(out);
return NULL;
}
return out;
}
/*************************************************************************
* Shared Encoder structs/methods *
*************************************************************************/
#define ENC_INIT_BUFSIZE 32
#define ENC_LINES_INIT_BUFSIZE 1024
enum decimal_format {
DECIMAL_FORMAT_STRING = 0,
DECIMAL_FORMAT_NUMBER = 1,
};
enum uuid_format {
UUID_FORMAT_CANONICAL = 0,
UUID_FORMAT_HEX = 1,
UUID_FORMAT_BYTES = 2,
};
typedef struct EncoderState {
MsgspecState *mod; /* module reference */
PyObject *enc_hook; /* `enc_hook` callback */
enum decimal_format decimal_format;
enum uuid_format uuid_format;
enum order_mode order;
char* (*resize_buffer)(PyObject**, Py_ssize_t); /* callback for resizing buffer */
char *output_buffer_raw; /* raw pointer to output_buffer internal buffer */
Py_ssize_t output_len; /* Length of output_buffer */
Py_ssize_t max_output_len; /* Allocation size of output_buffer */
PyObject *output_buffer; /* bytes or bytearray storing the output */
} EncoderState;
typedef struct Encoder {
PyObject_HEAD
PyObject *enc_hook;
MsgspecState *mod;
enum decimal_format decimal_format;
enum uuid_format uuid_format;
enum order_mode order;
} Encoder;
static PyTypeObject Encoder_Type;
static char*
ms_resize_bytes(PyObject** output_buffer, Py_ssize_t size)
{
int status = _PyBytes_Resize(output_buffer, size);
if (status < 0) return NULL;
return PyBytes_AS_STRING(*output_buffer);
}
static char*
ms_resize_bytearray(PyObject** output_buffer, Py_ssize_t size)
{
int status = PyByteArray_Resize(*output_buffer, size);
if (status < 0) return NULL;
return PyByteArray_AS_STRING(*output_buffer);
}
static MS_NOINLINE int
ms_resize(EncoderState *self, Py_ssize_t size)
{
self->max_output_len = Py_MAX(8, 1.5 * size);
char *new_buf = self->resize_buffer(&self->output_buffer, self->max_output_len);
if (new_buf == NULL) return -1;
self->output_buffer_raw = new_buf;
return 0;
}
static MS_INLINE int
ms_ensure_space(EncoderState *self, Py_ssize_t size) {
Py_ssize_t required = self->output_len + size;
if (MS_UNLIKELY(required > self->max_output_len)) {
return ms_resize(self, required);
}
return 0;
}
static MS_INLINE int
ms_write(EncoderState *self, const char *s, Py_ssize_t n)
{
Py_ssize_t required = self->output_len + n;
if (MS_UNLIKELY(required > self->max_output_len)) {
if (ms_resize(self, required) < 0) return -1;
}
memcpy(self->output_buffer_raw + self->output_len, s, n);
self->output_len += n;
return 0;
}
static int
Encoder_init(Encoder *self, PyObject *args, PyObject *kwds)
{
char *kwlist[] = {"enc_hook", "decimal_format", "uuid_format", "order", NULL};
PyObject *enc_hook = NULL, *decimal_format = NULL, *uuid_format = NULL, *order = NULL;
if (
!PyArg_ParseTupleAndKeywords(
args, kwds, "|$OOOO", kwlist,
&enc_hook, &decimal_format, &uuid_format, &order
)
) {
return -1;
}
if (enc_hook == Py_None) {
enc_hook = NULL;
}
if (enc_hook != NULL) {
if (!PyCallable_Check(enc_hook)) {
PyErr_SetString(PyExc_TypeError, "enc_hook must be callable");
return -1;
}
Py_INCREF(enc_hook);
}
/* Process decimal format */
if (decimal_format == NULL) {
self->decimal_format = DECIMAL_FORMAT_STRING;
}
else {
bool ok = false;
if (PyUnicode_CheckExact(decimal_format)) {
if (PyUnicode_CompareWithASCIIString(decimal_format, "string") == 0) {
self->decimal_format = DECIMAL_FORMAT_STRING;
ok = true;
}
else if (PyUnicode_CompareWithASCIIString(decimal_format, "number") == 0) {
self->decimal_format = DECIMAL_FORMAT_NUMBER;
ok = true;
}
}
if (!ok) {
PyErr_Format(
PyExc_ValueError,
"`decimal_format` must be 'string' or 'number', got %R",
decimal_format
);
return -1;
}
}
/* Process uuid format */
if (uuid_format == NULL) {
self->uuid_format = UUID_FORMAT_CANONICAL;
}
else {
bool is_msgpack = Py_TYPE(self) == &Encoder_Type;
bool ok = false;
if (PyUnicode_CheckExact(uuid_format)) {
if (PyUnicode_CompareWithASCIIString(uuid_format, "canonical") == 0) {
self->uuid_format = UUID_FORMAT_CANONICAL;
ok = true;
}
else if (PyUnicode_CompareWithASCIIString(uuid_format, "hex") == 0) {
self->uuid_format = UUID_FORMAT_HEX;
ok = true;
}
else if (is_msgpack && PyUnicode_CompareWithASCIIString(uuid_format, "bytes") == 0) {
self->uuid_format = UUID_FORMAT_BYTES;
ok = true;
}
}
if (!ok) {
const char *errmsg = (
is_msgpack ?
"`uuid_format` must be 'canonical', 'hex', or 'bytes', got %R" :
"`uuid_format` must be 'canonical' or 'hex', got %R"
);
PyErr_Format(PyExc_ValueError, errmsg, uuid_format);
return -1;
}
}
/* Process order */
self->order = parse_order_arg(order);
if (self->order == ORDER_INVALID) return -1;
self->mod = msgspec_get_global_state();
self->enc_hook = enc_hook;
return 0;
}
static int
Encoder_traverse(Encoder *self, visitproc visit, void *arg)
{
Py_VISIT(self->enc_hook);
return 0;
}
static int
Encoder_clear(Encoder *self)
{
Py_CLEAR(self->enc_hook);
return 0;
}
static void
Encoder_dealloc(Encoder *self)
{
PyObject_GC_UnTrack(self);
Encoder_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
PyDoc_STRVAR(Encoder_encode_into__doc__,
"encode_into(self, obj, buffer, offset=0, /)\n"
"--\n"
"\n"
"Serialize an object into an existing bytearray buffer.\n"
"\n"
"Upon success, the buffer will be truncated to the end of the serialized\n"
"message. Note that the underlying memory buffer *won't* be truncated,\n"
"allowing for efficiently appending additional bytes later.\n"
"\n"
"Parameters\n"
"----------\n"
"obj : Any\n"
" The object to serialize.\n"
"buffer : bytearray\n"
" The buffer to serialize into.\n"
"offset : int, optional\n"
" The offset into the buffer to start writing at. Defaults to 0. Set to -1\n"
" to start writing at the end of the buffer.\n"
"\n"
"Returns\n"
"-------\n"
"None"
);
static PyObject*
encoder_encode_into_common(
Encoder *self,
PyObject *const *args,
Py_ssize_t nargs,
int(*encode)(EncoderState*, PyObject*)
)
{
if (!check_positional_nargs(nargs, 2, 3)) return NULL;
PyObject *obj = args[0];
PyObject *buf = args[1];
if (!PyByteArray_CheckExact(buf)) {
PyErr_SetString(PyExc_TypeError, "buffer must be a `bytearray`");
return NULL;
}
Py_ssize_t buf_size = PyByteArray_GET_SIZE(buf);
Py_ssize_t offset = 0;
if (nargs == 3) {
offset = PyLong_AsSsize_t(args[2]);
if (offset == -1) {
if (PyErr_Occurred()) return NULL;
offset = buf_size;
}
if (offset < 0) {
PyErr_SetString(PyExc_ValueError, "offset must be >= -1");
return NULL;
}
if (offset < buf_size) {
buf_size = Py_MAX(8, 1.5 * offset);
if (PyByteArray_Resize(buf, buf_size) < 0) return NULL;
}
}
/* Setup buffer */
EncoderState state = {
.mod = self->mod,
.enc_hook = self->enc_hook,
.decimal_format = self->decimal_format,
.uuid_format = self->uuid_format,
.order = self->order,
.output_buffer = buf,
.output_buffer_raw = PyByteArray_AS_STRING(buf),
.output_len = offset,
.max_output_len = buf_size,
.resize_buffer = ms_resize_bytearray
};
if (encode(&state, obj) < 0) {
return NULL;
}
FAST_BYTEARRAY_SHRINK(buf, state.output_len);
Py_RETURN_NONE;
}
PyDoc_STRVAR(Encoder_encode__doc__,
"encode(self, obj)\n"
"--\n"
"\n"
"Serialize an object to bytes.\n"
"\n"
"Parameters\n"
"----------\n"
"obj : Any\n"
" The object to serialize.\n"
"\n"
"Returns\n"
"-------\n"
"data : bytes\n"
" The serialized object.\n"
);
static PyObject*
encoder_encode_common(
Encoder *self,
PyObject *const *args,
Py_ssize_t nargs,
int(*encode)(EncoderState*, PyObject*)
)
{
if (!check_positional_nargs(nargs, 1, 1)) return NULL;
EncoderState state = {
.mod = self->mod,
.enc_hook = self->enc_hook,
.decimal_format = self->decimal_format,
.uuid_format = self->uuid_format,
.order = self->order,
.output_len = 0,
.max_output_len = ENC_INIT_BUFSIZE,
.resize_buffer = &ms_resize_bytes
};
state.output_buffer = PyBytes_FromStringAndSize(NULL, state.max_output_len);
if (state.output_buffer == NULL) return NULL;
state.output_buffer_raw = PyBytes_AS_STRING(state.output_buffer);
if (encode(&state, args[0]) < 0) {
Py_DECREF(state.output_buffer);
return NULL;
}
FAST_BYTES_SHRINK(state.output_buffer, state.output_len);
return state.output_buffer;
}
static PyObject*
encode_common(
PyObject *module,
PyObject *const *args,
Py_ssize_t nargs,
PyObject *kwnames,
int(*encode)(EncoderState*, PyObject*)
)
{
PyObject *enc_hook = NULL, *order = NULL;
MsgspecState *mod = msgspec_get_state(module);
/* Parse arguments */
if (!check_positional_nargs(nargs, 1, 1)) return NULL;
if (kwnames != NULL) {
Py_ssize_t nkwargs = PyTuple_GET_SIZE(kwnames);
if ((enc_hook = find_keyword(kwnames, args + nargs, mod->str_enc_hook)) != NULL) nkwargs--;
if ((order = find_keyword(kwnames, args + nargs, mod->str_order)) != NULL) nkwargs--;
if (nkwargs > 0) {
PyErr_SetString(
PyExc_TypeError,
"Extra keyword arguments provided"
);
return NULL;
}
}
if (enc_hook == Py_None) {
enc_hook = NULL;
}
if (enc_hook != NULL && !PyCallable_Check(enc_hook)) {
PyErr_SetString(PyExc_TypeError, "enc_hook must be callable");
return NULL;
}
EncoderState state = {
.mod = mod,
.enc_hook = enc_hook,
.decimal_format = DECIMAL_FORMAT_STRING,
.uuid_format = UUID_FORMAT_CANONICAL,
.output_len = 0,
.max_output_len = ENC_INIT_BUFSIZE,
.resize_buffer = &ms_resize_bytes
};
state.order = parse_order_arg(order);
if (state.order == ORDER_INVALID) return NULL;
state.output_buffer = PyBytes_FromStringAndSize(NULL, state.max_output_len);
if (state.output_buffer == NULL) return NULL;
state.output_buffer_raw = PyBytes_AS_STRING(state.output_buffer);
if (encode(&state, args[0]) < 0) {
Py_DECREF(state.output_buffer);
return NULL;
}
FAST_BYTES_SHRINK(state.output_buffer, state.output_len);
return state.output_buffer;
}
static PyMemberDef Encoder_members[] = {
{"enc_hook", T_OBJECT, offsetof(Encoder, enc_hook), READONLY, NULL},
{NULL},
};
static PyObject*
Encoder_decimal_format(Encoder *self, void *closure) {
if (self->decimal_format == DECIMAL_FORMAT_STRING) {
return PyUnicode_InternFromString("string");
}
return PyUnicode_InternFromString("number");
}
static PyObject*
Encoder_uuid_format(Encoder *self, void *closure) {
if (self->uuid_format == UUID_FORMAT_CANONICAL) {
return PyUnicode_InternFromString("canonical");
}
else if (self->uuid_format == UUID_FORMAT_HEX) {
return PyUnicode_InternFromString("hex");
}
else {
return PyUnicode_InternFromString("bytes");
}
}
static PyObject*
Encoder_order(Encoder *self, void *closure) {
if (self->order == ORDER_DEFAULT) {
Py_RETURN_NONE;
}
else if (self->order == ORDER_DETERMINISTIC) {
return PyUnicode_InternFromString("deterministic");
}
else {
return PyUnicode_InternFromString("sorted");
}
}
static PyGetSetDef Encoder_getset[] = {
{"decimal_format", (getter) Encoder_decimal_format, NULL, NULL, NULL},
{"uuid_format", (getter) Encoder_uuid_format, NULL, NULL, NULL},
{"order", (getter) Encoder_order, NULL, NULL, NULL},
{NULL},
};
/*************************************************************************
* Shared Decoding Utilities *
*************************************************************************/
static PyObject *
ms_maybe_decode_bool_from_uint64(uint64_t x) {
if (x == 0) {
Py_RETURN_FALSE;
}
else if (x == 1) {
Py_RETURN_TRUE;
}
return NULL;
}
static PyObject *
ms_maybe_decode_bool_from_int64(int64_t x) {
if (x == 0) {
Py_RETURN_FALSE;
}
else if (x == 1) {
Py_RETURN_TRUE;
}
return NULL;
}
static PyObject *
ms_decode_str_enum_or_literal(const char *name, Py_ssize_t size, TypeNode *type, PathNode *path) {
StrLookup *lookup = TypeNode_get_str_enum_or_literal(type);
return StrLookup_GetOrError(lookup, name, size, path);
}
static PyObject *
ms_decode_int_enum_or_literal_int64(int64_t val, TypeNode *type, PathNode *path) {
IntLookup *lookup = TypeNode_get_int_enum_or_literal(type);
return IntLookup_GetInt64OrError(lookup, val, path);
}
static PyObject *
ms_decode_int_enum_or_literal_uint64(uint64_t val, TypeNode *type, PathNode *path) {
IntLookup *lookup = TypeNode_get_int_enum_or_literal(type);
return IntLookup_GetUInt64OrError(lookup, val, path);
}
static PyObject *
ms_decode_int_enum_or_literal_pyint(PyObject *val, TypeNode *type, PathNode *path) {
IntLookup *lookup = TypeNode_get_int_enum_or_literal(type);
return IntLookup_GetPyIntOrError(lookup, val, path);
}
static MS_NOINLINE PyObject *
ms_decode_custom(PyObject *obj, PyObject *dec_hook, TypeNode* type, PathNode *path) {
PyObject *custom_cls = NULL, *custom_obj, *out = NULL;
int status;
bool generic = type->types & MS_TYPE_CUSTOM_GENERIC;
if (obj == NULL) return NULL;
if (obj == Py_None && type->types & MS_TYPE_NONE) return obj;
custom_obj = TypeNode_get_custom(type);
if (dec_hook != NULL) {
out = PyObject_CallFunctionObjArgs(dec_hook, custom_obj, obj, NULL);
Py_DECREF(obj);
if (out == NULL) {
ms_maybe_wrap_validation_error(path);
return NULL;
}
}
else {
out = obj;
}
/* Generic classes must be checked based on __origin__ */
if (generic) {
MsgspecState *st = msgspec_get_global_state();
custom_cls = PyObject_GetAttr(custom_obj, st->str___origin__);
if (custom_cls == NULL) {
Py_DECREF(out);
return NULL;
}
}
else {
custom_cls = custom_obj;
}
/* Check that the decoded value matches the expected type */
status = PyObject_IsInstance(out, custom_cls);
if (status == 0) {
ms_raise_validation_error(
path,
"Expected `%s`, got `%s`%U",
((PyTypeObject *)custom_cls)->tp_name,
Py_TYPE(out)->tp_name
);
Py_CLEAR(out);
}
else if (status == -1) {
Py_CLEAR(out);
}
if (generic) {
Py_DECREF(custom_cls);
}
return out;
}
static MS_NOINLINE PyObject *
_err_int_constraint(const char *msg, int64_t c, PathNode *path) {
ms_raise_validation_error(path, msg, c);
return NULL;
}
static MS_NOINLINE PyObject *
ms_decode_constr_int(int64_t x, TypeNode *type, PathNode *path) {
if (type->types & MS_CONSTR_INT_MIN) {
int64_t c = TypeNode_get_constr_int_min(type);
bool ok = x >= c;
if (MS_UNLIKELY(!ok)) {
return _err_int_constraint("Expected `int` >= %lld%U", c, path);
}
}
if (type->types & MS_CONSTR_INT_MAX) {
int64_t c = TypeNode_get_constr_int_max(type);
bool ok = x <= c;
if (MS_UNLIKELY(!ok)) {
return _err_int_constraint("Expected `int` <= %lld%U", c, path);
}
}
if (MS_UNLIKELY(type->types & MS_CONSTR_INT_MULTIPLE_OF)) {
int64_t c = TypeNode_get_constr_int_multiple_of(type);
bool ok = (x % c) == 0;
if (MS_UNLIKELY(!ok)) {
return _err_int_constraint(
"Expected `int` that's a multiple of %lld%U", c, path
);
}
}
return PyLong_FromLongLong(x);
}
static MS_INLINE PyObject *
ms_decode_int(int64_t x, TypeNode *type, PathNode *path) {
if (MS_UNLIKELY(type->types & MS_INT_CONSTRS)) {
return ms_decode_constr_int(x, type, path);
}
return PyLong_FromLongLong(x);
}
static MS_NOINLINE PyObject *
ms_decode_constr_uint(uint64_t x, TypeNode *type, PathNode *path) {
if (type->types & MS_CONSTR_INT_MAX) {
int64_t c = TypeNode_get_constr_int_max(type);
return _err_int_constraint("Expected `int` <= %lld%U", c, path);
}
if (MS_UNLIKELY(type->types & MS_CONSTR_INT_MULTIPLE_OF)) {
int64_t c = TypeNode_get_constr_int_multiple_of(type);
bool ok = (x % c) == 0;
if (MS_UNLIKELY(!ok)) {
return _err_int_constraint(
"Expected `int` that's a multiple of %lld%U", c, path
);
}
}
return PyLong_FromUnsignedLongLong(x);
}
static MS_INLINE PyObject *
ms_decode_uint(uint64_t x, TypeNode *type, PathNode *path) {
if (MS_UNLIKELY(type->types & MS_INT_CONSTRS)) {
if (MS_LIKELY(x <= LLONG_MAX)) {
return ms_decode_int(x, type, path);
}
return ms_decode_constr_uint(x, type, path);
}
return PyLong_FromUnsignedLongLong(x);
}
static MS_NOINLINE bool
ms_passes_int_constraints(uint64_t ux, bool neg, TypeNode *type, PathNode *path) {
if (type->types & MS_CONSTR_INT_MIN) {
int64_t c = TypeNode_get_constr_int_min(type);
bool ok = (
neg ? ((-(int64_t)ux) >= c) :
((c < 0) || (ux >= (uint64_t)c))
);
if (MS_UNLIKELY(!ok)) {
_err_int_constraint("Expected `int` >= %lld%U", c, path);
return false;
}
}
if (type->types & MS_CONSTR_INT_MAX) {
int64_t c = TypeNode_get_constr_int_max(type);
bool ok = (
neg ? ((-(int64_t)ux) <= c) :
((c >= 0) && (ux <= (uint64_t)c))
);
if (MS_UNLIKELY(!ok)) {
_err_int_constraint("Expected `int` <= %lld%U", c, path);
return false;
}
}
if (MS_UNLIKELY(type->types & MS_CONSTR_INT_MULTIPLE_OF)) {
int64_t c = TypeNode_get_constr_int_multiple_of(type);
bool ok = (ux % c) == 0;
if (MS_UNLIKELY(!ok)) {
_err_int_constraint(
"Expected `int` that's a multiple of %lld%U", c, path
);
return false;
}
}
return true;
}
/* Constraint checks for a PyLong that is known not to fit into a uint64/int64 */
static bool
ms_passes_big_int_constraints(PyObject *obj, TypeNode *type, PathNode *path) {
bool neg = _PyLong_Sign(obj) < 0;
if (type->types & MS_CONSTR_INT_MIN) {
if (neg) {
int64_t c = TypeNode_get_constr_int_min(type);
_err_int_constraint("Expected `int` >= %lld%U", c, path);
return false;
}
}
if (type->types & MS_CONSTR_INT_MAX) {
if (!neg) {
int64_t c = TypeNode_get_constr_int_max(type);
_err_int_constraint("Expected `int` <= %lld%U", c, path);
return false;
}
}
if (MS_UNLIKELY(type->types & MS_CONSTR_INT_MULTIPLE_OF)) {
int64_t c = TypeNode_get_constr_int_multiple_of(type);
PyObject *base = PyLong_FromLongLong(c);
if (base == NULL) return false;
PyObject *remainder = PyNumber_Remainder(obj, base);
Py_DECREF(base);
if (remainder == NULL) return false;
long iremainder = PyLong_AsLong(remainder);
if (iremainder != 0) {
_err_int_constraint(
"Expected `int` that's a multiple of %lld%U", c, path
);
return false;
}
}
return true;
}
static MS_NOINLINE PyObject *
ms_decode_big_pyint(PyObject *obj, TypeNode *type, PathNode *path) {
if (MS_UNLIKELY(type->types & MS_INT_CONSTRS)) {
if (!ms_passes_big_int_constraints(obj, type, path)) return NULL;
}
if (MS_LIKELY(PyLong_CheckExact(obj))) {
Py_INCREF(obj);
return obj;
}
else {
return PyNumber_Long(obj);
}
}
static MS_INLINE PyObject *
ms_decode_pyint(PyObject *obj, TypeNode *type, PathNode *path) {
uint64_t ux;
bool neg, overflow;
overflow = fast_long_extract_parts(obj, &neg, &ux);
if (MS_UNLIKELY(overflow)) {
return ms_decode_big_pyint(obj, type, path);
}
if (MS_UNLIKELY(type->types & MS_INT_CONSTRS)) {
if (!ms_passes_int_constraints(ux, neg, type, path)) return NULL;
}
if (MS_LIKELY(PyLong_CheckExact(obj))) {
Py_INCREF(obj);
return obj;
}
if (!neg) {
return PyLong_FromUnsignedLongLong(ux);
}
return PyLong_FromLongLong(-(int64_t)ux);
}
static MS_NOINLINE PyObject *
ms_decode_bigint(const char *buf, Py_ssize_t size, TypeNode *type, PathNode *path) {
if (size > 4300) goto out_of_range;
/* CPython int parsing routine requires NULL terminated buffer */
char *temp = (char *)PyMem_Malloc(size + 1);
if (temp == NULL) return NULL;
memcpy(temp, buf, size);
temp[size] = '\0';
PyObject *out = PyLong_FromString(temp, NULL, 10);
PyMem_Free(temp);
/* We already know the int is a valid integer string. An error here is
* either a ValueError due to the int being too big (to prevent DDOS
* issues), or some issue in the VM. We convert the former to out-of-range
* errors for uniformity, and raise the latter directly. */
if (MS_UNLIKELY(out == NULL)) {
PyObject *exc_type, *exc, *tb;
/* Fetch the exception state */
PyErr_Fetch(&exc_type, &exc, &tb);
if (exc_type == NULL) {
/* Some other c-extension has borked, just return */
return NULL;
}
else if (exc_type == PyExc_ValueError) {
goto out_of_range;
}
else {
/* Restore the exception state */
PyErr_Restore(exc_type, exc, tb);
}
}
if (MS_UNLIKELY(type->types & MS_INT_CONSTRS)) {
if (!ms_passes_big_int_constraints(out, type, path)) {
Py_CLEAR(out);
}
}
return out;
out_of_range:
return ms_error_with_path("Integer value out of range%U", path);
}
static MS_NOINLINE PyObject *
_err_float_constraint(
const char *msg, int offset, double c, PathNode *path
) {
if (offset == 1) {
c = nextafter(c, DBL_MAX);
}
else if (offset == -1) {
c = nextafter(c, -DBL_MAX);
}
PyObject *py_c = PyFloat_FromDouble(c);
if (py_c != NULL) {
ms_raise_validation_error(path, "Expected `float` %s %R%U", msg, py_c);
Py_DECREF(py_c);
}
return NULL;
}
static MS_INLINE bool
ms_passes_float_constraints_inline(double x, TypeNode *type, PathNode *path) {
if (type->types & (MS_CONSTR_FLOAT_GE | MS_CONSTR_FLOAT_GT)) {
double c = TypeNode_get_constr_float_min(type);
bool ok = x >= c;
if (MS_UNLIKELY(!ok)) {
bool eq = type->types & MS_CONSTR_FLOAT_GE;
_err_float_constraint(
eq ? ">=" : ">",
eq ? 0 : -1,
c,
path
);
return false;
}
}
if (type->types & (MS_CONSTR_FLOAT_LE | MS_CONSTR_FLOAT_LT)) {
double c = TypeNode_get_constr_float_max(type);
bool ok = x <= c;
if (MS_UNLIKELY(!ok)) {
bool eq = type->types & MS_CONSTR_FLOAT_LE;
_err_float_constraint(
eq ? "<=" : "<",
eq ? 0 : 1,
c,
path
);
return false;
}
}
if (MS_UNLIKELY(type->types & MS_CONSTR_FLOAT_MULTIPLE_OF)) {
double c = TypeNode_get_constr_float_multiple_of(type);
bool ok = x == 0 || fmod(x, c) == 0.0;
if (MS_UNLIKELY(!ok)) {
_err_float_constraint(
"that's a multiple of", 0, c, path
);
return false;
}
}
return true;
}
static MS_NOINLINE PyObject *
ms_decode_constr_float(double x, TypeNode *type, PathNode *path) {
if (!ms_passes_float_constraints_inline(x, type, path)) return NULL;
return PyFloat_FromDouble(x);
}
static MS_INLINE PyObject *
ms_decode_float(double x, TypeNode *type, PathNode *path) {
if (MS_UNLIKELY(type->types & MS_FLOAT_CONSTRS)) {
return ms_decode_constr_float(x, type, path);
}
return PyFloat_FromDouble(x);
}
static MS_NOINLINE PyObject *
_ms_check_float_constraints(PyObject *obj, TypeNode *type, PathNode *path) {
double x = PyFloat_AS_DOUBLE(obj);
if (ms_passes_float_constraints_inline(x, type, path)) return obj;
Py_DECREF(obj);
return NULL;
}
static MS_INLINE PyObject *
ms_check_float_constraints(PyObject *obj, TypeNode *type, PathNode *path) {
if (MS_LIKELY(!(type->types & MS_FLOAT_CONSTRS))) return obj;
return _ms_check_float_constraints(obj, type, path);
}
static MS_NOINLINE bool
_err_py_ssize_t_constraint(const char *msg, Py_ssize_t c, PathNode *path) {
ms_raise_validation_error(path, msg, c);
return false;
}
static MS_NOINLINE PyObject *
_ms_check_str_constraints(PyObject *obj, TypeNode *type, PathNode *path) {
if (obj == NULL) return NULL;
Py_ssize_t len = PyUnicode_GET_LENGTH(obj);
if (type->types & MS_CONSTR_STR_MIN_LENGTH) {
Py_ssize_t c = TypeNode_get_constr_str_min_length(type);
if (len < c) {
_err_py_ssize_t_constraint(
"Expected `str` of length >= %zd%U", c, path
);
goto error;
}
}
if (type->types & MS_CONSTR_STR_MAX_LENGTH) {
Py_ssize_t c = TypeNode_get_constr_str_max_length(type);
if (len > c) {
_err_py_ssize_t_constraint(
"Expected `str` of length <= %zd%U", c, path
);
goto error;
}
}
if (type->types & MS_CONSTR_STR_REGEX) {
PyObject *regex = TypeNode_get_constr_str_regex(type);
PyObject *res = PyObject_CallMethod(regex, "search", "O", obj);
if (res == NULL) goto error;
bool ok = (res != Py_None);
Py_DECREF(res);
if (!ok) {
PyObject *pattern = PyObject_GetAttrString(regex, "pattern");
if (pattern == NULL) goto error;
ms_raise_validation_error(
path, "Expected `str` matching regex %R%U", pattern
);
Py_DECREF(pattern);
goto error;
}
}
return obj;
error:
Py_DECREF(obj);
return NULL;
}
static MS_INLINE PyObject *
ms_check_str_constraints(PyObject *obj, TypeNode *type, PathNode *path) {
if (MS_LIKELY(!(type->types & MS_STR_CONSTRS))) return obj;
return _ms_check_str_constraints(obj, type, path);
}
static bool
ms_passes_bytes_constraints(Py_ssize_t size, TypeNode *type, PathNode *path) {
if (MS_UNLIKELY(type->types & MS_CONSTR_BYTES_MIN_LENGTH)) {
Py_ssize_t c = TypeNode_get_constr_bytes_min_length(type);
if (size < c) {
return _err_py_ssize_t_constraint(
"Expected `bytes` of length >= %zd%U", c, path
);
}
}
if (MS_UNLIKELY(type->types & MS_CONSTR_BYTES_MAX_LENGTH)) {
Py_ssize_t c = TypeNode_get_constr_bytes_max_length(type);
if (size > c) {
return _err_py_ssize_t_constraint(
"Expected `bytes` of length <= %zd%U", c, path
);
}
}
return true;
}
static MS_NOINLINE bool
_ms_passes_array_constraints(Py_ssize_t size, TypeNode *type, PathNode *path) {
if (MS_UNLIKELY(type->types & MS_CONSTR_ARRAY_MIN_LENGTH)) {
Py_ssize_t c = TypeNode_get_constr_array_min_length(type);
if (size < c) {
return _err_py_ssize_t_constraint(
"Expected `array` of length >= %zd%U", c, path
);
}
}
if (MS_UNLIKELY(type->types & MS_CONSTR_ARRAY_MAX_LENGTH)) {
Py_ssize_t c = TypeNode_get_constr_array_max_length(type);
if (size > c) {
return _err_py_ssize_t_constraint(
"Expected `array` of length <= %zd%U", c, path
);
}
}
return true;
}
static MS_INLINE bool
ms_passes_array_constraints(Py_ssize_t size, TypeNode *type, PathNode *path) {
if (MS_UNLIKELY(type->types & MS_ARRAY_CONSTRS)) {
return _ms_passes_array_constraints(size, type, path);
}
return true;
}
static MS_NOINLINE bool
_ms_passes_map_constraints(Py_ssize_t size, TypeNode *type, PathNode *path) {
if (MS_UNLIKELY(type->types & MS_CONSTR_MAP_MIN_LENGTH)) {
Py_ssize_t c = TypeNode_get_constr_map_min_length(type);
if (size < c) {
return _err_py_ssize_t_constraint(
"Expected `object` of length >= %zd%U", c, path
);
}
}
if (MS_UNLIKELY(type->types & MS_CONSTR_MAP_MAX_LENGTH)) {
Py_ssize_t c = TypeNode_get_constr_map_max_length(type);
if (size > c) {
return _err_py_ssize_t_constraint(
"Expected `object` of length <= %zd%U", c, path
);
}
}
return true;
}
static MS_INLINE bool
ms_passes_map_constraints(Py_ssize_t size, TypeNode *type, PathNode *path) {
if (MS_UNLIKELY(type->types & MS_MAP_CONSTRS)) {
return _ms_passes_map_constraints(size, type, path);
}
return true;
}
static bool
ms_passes_tz_constraint(
PyObject *tz, TypeNode *type, PathNode *path
) {
char *err, *type_str;
if (tz == Py_None) {
if (type->types & MS_CONSTR_TZ_AWARE) {
err = "Expected `%s` with a timezone component%U";
goto error;
}
}
else if (type->types & MS_CONSTR_TZ_NAIVE) {
err = "Expected `%s` with no timezone component%U";
goto error;
}
return true;
error:
if (type->types & MS_TYPE_TIME) {
type_str = "time";
}
else {
type_str = "datetime";
}
ms_raise_validation_error(path, err, type_str);
return false;
}
static int
ms_encode_err_type_unsupported(PyTypeObject *type) {
PyErr_Format(
PyExc_TypeError,
"Encoding objects of type %.200s is unsupported",
type->tp_name
);
return -1;
}
/*************************************************************************
* Datetime utilities *
*************************************************************************/
#define MS_HAS_TZINFO(o) (((_PyDateTime_BaseTZInfo *)(o))->hastzinfo)
#if PY310_PLUS
#define MS_DATE_GET_TZINFO(o) PyDateTime_DATE_GET_TZINFO(o)
#define MS_TIME_GET_TZINFO(o) PyDateTime_TIME_GET_TZINFO(o)
#else
#define MS_DATE_GET_TZINFO(o) (MS_HAS_TZINFO(o) ? \
((PyDateTime_DateTime *)(o))->tzinfo : Py_None)
#define MS_TIME_GET_TZINFO(o) (MS_HAS_TZINFO(o) ? \
((PyDateTime_Time *)(o))->tzinfo : Py_None)
#endif
#ifndef TIMEZONE_CACHE_SIZE
#define TIMEZONE_CACHE_SIZE 512
#endif
typedef struct {
int32_t offset;
PyObject *tz;
} TimezoneCacheItem;
static TimezoneCacheItem timezone_cache[TIMEZONE_CACHE_SIZE];
static void
timezone_cache_clear(void) {
/* Traverse the timezone cache, deleting any string with a reference count
* of only 1 */
for (Py_ssize_t i = 0; i < TIMEZONE_CACHE_SIZE; i++) {
PyObject *tz = timezone_cache[i].tz;
if (tz != NULL && Py_REFCNT(tz) == 1) {
timezone_cache[i].offset = 0;
timezone_cache[i].tz = NULL;
Py_DECREF(tz);
}
}
}
/* Returns a new reference */
static PyObject*
timezone_from_offset(int32_t offset) {
uint32_t index = ((uint32_t)offset) % TIMEZONE_CACHE_SIZE;
if (timezone_cache[index].offset == offset) {
PyObject *tz = timezone_cache[index].tz;
Py_INCREF(tz);
return tz;
}
PyObject *delta = PyDelta_FromDSU(0, offset * 60, 0);
if (delta == NULL) return NULL;
PyObject *tz = PyTimeZone_FromOffset(delta);
Py_DECREF(delta);
if (tz == NULL) return NULL;
Py_XDECREF(timezone_cache[index].tz);
timezone_cache[index].offset = offset;
Py_INCREF(tz);
timezone_cache[index].tz = tz;
return tz;
}
static bool
is_leap_year(int year)
{
unsigned int y = (unsigned int)year;
return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
}
static int
days_in_month(int year, int month) {
static const uint8_t ndays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && is_leap_year(year))
return 29;
else
return ndays[month - 1];
}
static MS_NOINLINE int
datetime_round_up_micros(
int *year, int *month, int *day, int *hour,
int *minute, int *second, int *microsecond
) {
++*microsecond;
if (*microsecond == 1000000) {
*microsecond = 0;
++*second;
if (*second == 60) {
*second = 0;
++*minute;
if (*minute == 60) {
*minute = 0;
++*hour;
if (*hour == 24) {
*hour = 0;
++*day;
if (*day == days_in_month(*year, *month) + 1) {
++*month;
*day = 1;
if (*month > 12) {
*month = 1;
++*year;
if (*year > 9999) return -1;
}
}
}
}
}
}
return 0;
}
static MS_NOINLINE void
time_round_up_micros(
int *hour, int *minute, int *second, int *microsecond
) {
++*microsecond;
if (*microsecond == 1000000) {
*microsecond = 0;
++*second;
if (*second == 60) {
*second = 0;
++*minute;
if (*minute == 60) {
*minute = 0;
++*hour;
if (*hour == 24) {
*hour = 0;
}
}
}
}
}
/* Days since 0001-01-01, the min value for python's datetime objects */
static int
days_since_min_datetime(int year, int month, int day)
{
int out = day;
static const int _days_before_month[] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
out += _days_before_month[month - 1];
if (month > 2 && is_leap_year(year)) out++;
year--; /* makes math easier */
out += year*365 + year/4 - year/100 + year/400;
return out;
}
static void
datetime_to_epoch(PyObject *obj, int64_t *seconds, int32_t *nanoseconds) {
int64_t d = days_since_min_datetime(
PyDateTime_GET_YEAR(obj),
PyDateTime_GET_MONTH(obj),
PyDateTime_GET_DAY(obj)
) - 719163; /* days_since_min_datetime(1970, 1, 1) */
int64_t s = (
PyDateTime_DATE_GET_HOUR(obj) * 3600
+ PyDateTime_DATE_GET_MINUTE(obj) * 60
+ PyDateTime_DATE_GET_SECOND(obj)
);
int64_t us = PyDateTime_DATE_GET_MICROSECOND(obj);
*seconds = 86400 * d + s;
*nanoseconds = us * 1000;
}
/* Python datetimes bounded between (inclusive)
* [0001-01-01T00:00:00.000000, 9999-12-31T23:59:59.999999] UTC */
#define MS_EPOCH_SECS_MAX 253402300800
#define MS_EPOCH_SECS_MIN -62135596800
#define MS_DAYS_PER_400Y (365*400 + 97)
#define MS_DAYS_PER_100Y (365*100 + 24)
#define MS_DAYS_PER_4Y (365*4 + 1)
/* Epoch -> datetime conversion borrowed and modified from the implementation
* in musl, found at
* http://git.musl-libc.org/cgit/musl/tree/src/time/__secs_to_tm.c. musl is
* copyright Rich Felker et. al, and is licensed under the standard MIT
* license. */
static PyObject *
datetime_from_epoch(
int64_t epoch_secs, uint32_t epoch_nanos, TypeNode *type, PathNode *path
) {
/* Error on out-of-bounds datetimes. This leaves ample space in an int, so
* no need to check for overflow later. */
if (epoch_secs < MS_EPOCH_SECS_MIN || epoch_secs > MS_EPOCH_SECS_MAX) {
return ms_error_with_path("Timestamp is out of range %U", path);
}
int64_t years, days, secs;
int micros, months, remdays, remsecs, remyears;
int qc_cycles, c_cycles, q_cycles;
/* Round nanos to nearest microsecond, adjusting seconds as needed */
micros = DIV_ROUND_CLOSEST(epoch_nanos, 1000);
if (micros == 1000000) {
micros = 0;
epoch_secs++;
}
/* Start in Mar not Jan, so leap day is on end */
static const char days_in_month[] = {31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29};
/* Offset to 2000-03-01, a mod 400 year, immediately after feb 29 */
secs = epoch_secs - (946684800LL + 86400 * (31 + 29));
days = secs / 86400;
remsecs = secs % 86400;
if (remsecs < 0) {
remsecs += 86400;
days--;
}
qc_cycles = days / MS_DAYS_PER_400Y;
remdays = days % MS_DAYS_PER_400Y;
if (remdays < 0) {
remdays += MS_DAYS_PER_400Y;
qc_cycles--;
}
c_cycles = remdays / MS_DAYS_PER_100Y;
if (c_cycles == 4) c_cycles--;
remdays -= c_cycles * MS_DAYS_PER_100Y;
q_cycles = remdays / MS_DAYS_PER_4Y;
if (q_cycles == 25) q_cycles--;
remdays -= q_cycles * MS_DAYS_PER_4Y;
remyears = remdays / 365;
if (remyears == 4) remyears--;
remdays -= remyears * 365;
years = remyears + 4*q_cycles + 100*c_cycles + 400LL*qc_cycles;
for (months = 0; days_in_month[months] <= remdays; months++)
remdays -= days_in_month[months];
if (months >= 10) {
months -= 12;
years++;
}
if (!ms_passes_tz_constraint(PyDateTime_TimeZone_UTC, type, path)) return NULL;
return PyDateTimeAPI->DateTime_FromDateAndTime(
years + 2000,
months + 3,
remdays + 1,
remsecs / 3600,
remsecs / 60 % 60,
remsecs % 60,
micros,
PyDateTime_TimeZone_UTC,
PyDateTimeAPI->DateTimeType
);
}
static inline const char *
ms_read_fixint(const char *buf, int width, int *out) {
int x = 0;
for (int i = 0; i < width; i++) {
char c = *buf++;
if (!is_digit(c)) return NULL;
x = x * 10 + (c - '0');
}
*out = x;
return buf;
}
/* Requires 10 bytes of scratch space */
static void
ms_encode_date(PyObject *obj, char *out)
{
uint32_t year = PyDateTime_GET_YEAR(obj);
uint8_t month = PyDateTime_GET_MONTH(obj);
uint8_t day = PyDateTime_GET_DAY(obj);
write_u32_4_digits(year, out);
*(out + 4) = '-';
write_u32_2_digits(month, out + 5);
*(out + 7) = '-';
write_u32_2_digits(day, out + 8);
}
/* Requires 21 bytes of scratch space */
static int
ms_encode_time_parts(
MsgspecState *mod, PyObject *datetime_or_none,
uint8_t hour, uint8_t minute, uint8_t second, uint32_t microsecond,
PyObject *tzinfo, char *out, int out_offset
) {
char *p = out + out_offset;
write_u32_2_digits(hour, p);
p += 2;
*p++ = ':';
write_u32_2_digits(minute, p);
p += 2;
*p++ = ':';
write_u32_2_digits(second, p);
p += 2;
if (microsecond) {
*p++ = '.';
write_u32_6_digits(microsecond, p);
p += 6;
}
if (tzinfo != Py_None) {
int32_t offset_days = 0, offset_secs = 0;
if (tzinfo != PyDateTime_TimeZone_UTC) {
PyObject *offset = PyObject_CallMethodOneArg(
tzinfo, mod->str_utcoffset, datetime_or_none
);
if (offset == NULL) {
return -1;
}
else if (PyDelta_Check(offset)) {
offset_days = PyDateTime_DELTA_GET_DAYS(offset);
offset_secs = PyDateTime_DELTA_GET_SECONDS(offset);
Py_DECREF(offset);
}
else if (offset == Py_None) {
Py_DECREF(offset);
goto done;
}
else if (offset != Py_None) {
PyErr_SetString(
PyExc_TypeError,
"tzinfo.utcoffset returned a non-timedelta object"
);
Py_DECREF(offset);
return -1;
}
}
if (MS_LIKELY(offset_secs == 0)) {
*p++ = 'Z';
}
else {
char sign = '+';
if (offset_days == -1) {
sign = '-';
offset_secs = 86400 - offset_secs;
}
uint8_t offset_hour = offset_secs / 3600;
uint8_t offset_min = (offset_secs / 60) % 60;
/* If the offset isn't an even number of minutes, RFC 3339
* indicates that the offset should be rounded to the nearest
* possible hour:min pair */
bool round_up = (offset_secs - (offset_hour * 3600 + offset_min * 60)) > 30;
if (MS_UNLIKELY(round_up)) {
offset_min++;
if (offset_min == 60) {
offset_min = 0;
offset_hour++;
if (offset_hour == 24) {
offset_hour = 0;
}
}
}
if (offset_hour == 0 && offset_min == 0) {
*p++ = 'Z';
}
else {
*p++ = sign;
write_u32_2_digits(offset_hour, p);
p += 2;
*p++ = ':';
write_u32_2_digits(offset_min, p);
p += 2;
}
}
}
done:
return p - out;
}
/* Requires 21 bytes of scratch space max.
*
* Returns +nbytes if successful, -1 on failure */
static int
ms_encode_time(MsgspecState *mod, PyObject *obj, char *out)
{
uint8_t hour = PyDateTime_TIME_GET_HOUR(obj);
uint8_t minute = PyDateTime_TIME_GET_MINUTE(obj);
uint8_t second = PyDateTime_TIME_GET_SECOND(obj);
uint32_t microsecond = PyDateTime_TIME_GET_MICROSECOND(obj);
PyObject *tzinfo = MS_TIME_GET_TZINFO(obj);
return ms_encode_time_parts(
mod, Py_None, hour, minute, second, microsecond, tzinfo, out, 0
);
}
/* Requires 32 bytes of scratch space max.
*
* Returns +nbytes if successful, -1 on failure */
static int
ms_encode_datetime(MsgspecState *mod, PyObject *obj, char *out)
{
uint8_t hour = PyDateTime_DATE_GET_HOUR(obj);
uint8_t minute = PyDateTime_DATE_GET_MINUTE(obj);
uint8_t second = PyDateTime_DATE_GET_SECOND(obj);
uint32_t microsecond = PyDateTime_DATE_GET_MICROSECOND(obj);
PyObject *tzinfo = MS_DATE_GET_TZINFO(obj);
ms_encode_date(obj, out);
out[10] = 'T';
return ms_encode_time_parts(
mod, obj, hour, minute, second, microsecond, tzinfo, out, 11
);
}
static PyObject *
ms_decode_date(const char *buf, Py_ssize_t size, PathNode *path) {
int year, month, day;
/* A valid date is 10 characters in length */
if (size != 10) goto invalid;
/* Parse date */
if ((buf = ms_read_fixint(buf, 4, &year)) == NULL) goto invalid;
if (*buf++ != '-') goto invalid;
if ((buf = ms_read_fixint(buf, 2, &month)) == NULL) goto invalid;
if (*buf++ != '-') goto invalid;
if ((buf = ms_read_fixint(buf, 2, &day)) == NULL) goto invalid;
/* Ensure all numbers are valid */
if (year == 0) goto invalid;
if (month == 0 || month > 12) goto invalid;
if (day == 0 || day > days_in_month(year, month)) goto invalid;
return PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType);
invalid:
return ms_error_with_path("Invalid RFC3339 encoded date%U", path);
}
static PyObject *
ms_decode_time(const char *buf, Py_ssize_t size, TypeNode *type, PathNode *path) {
int hour, minute, second, microsecond = 0;
const char *buf_end = buf + size;
bool round_up_micros = false;
PyObject *tz = NULL;
char c;
/* A valid time is at least 8 characters in length */
if (size < 8) goto invalid;
/* Parse time */
if ((buf = ms_read_fixint(buf, 2, &hour)) == NULL) goto invalid;
if (*buf++ != ':') goto invalid;
if ((buf = ms_read_fixint(buf, 2, &minute)) == NULL) goto invalid;
if (*buf++ != ':') goto invalid;
if ((buf = ms_read_fixint(buf, 2, &second)) == NULL) goto invalid;
/* Remaining reads require bounds check */
#define next_or_null() (buf == buf_end) ? '\0' : *buf++
c = next_or_null();
if (c == '.') {
int ndigits = 0;
while (ndigits < 6) {
c = next_or_null();
if (!is_digit(c)) goto end_decimal;
ndigits++;
microsecond = microsecond * 10 + (c - '0');
}
c = next_or_null();
if (is_digit(c)) {
/* This timestamp has higher precision than microseconds; parse
* the next digit to support rounding, then skip all remaining
* digits */
if ((c - '0') >= 5) {
round_up_micros = true;
}
while (true) {
c = next_or_null();
if (!is_digit(c)) break;
}
}
end_decimal:
/* Error if no digits after decimal */
if (ndigits == 0) goto invalid;
int pow10[6] = {100000, 10000, 1000, 100, 10, 1};
/* Scale microseconds appropriately */
microsecond *= pow10[ndigits - 1];
}
#undef next_or_null
if (c != '\0') {
/* Parse timezone */
int offset = 0;
if (c == 'Z' || c == 'z') {
/* Check for trailing characters */
if (buf != buf_end) goto invalid;
}
else {
int offset_hour, offset_min;
if (c == '-') {
offset = -1;
}
else if (c == '+') {
offset = 1;
}
else {
goto invalid;
}
if (buf_end - buf < 3) goto invalid;
if ((buf = ms_read_fixint(buf, 2, &offset_hour)) == NULL) goto invalid;
/* RFC3339 requires a ':' separator, ISO8601 doesn't. We support
* either */
if (*buf == ':') buf++;
if (buf_end - buf != 2) goto invalid;
if ((buf = ms_read_fixint(buf, 2, &offset_min)) == NULL) goto invalid;
if (offset_hour > 23 || offset_min > 59) goto invalid;
offset *= (offset_hour * 60 + offset_min);
}
if (offset == 0) {
tz = PyDateTime_TimeZone_UTC;
Py_INCREF(tz);
}
else {
tz = timezone_from_offset(offset);
if (tz == NULL) goto error;
}
}
else {
tz = Py_None;
Py_INCREF(tz);
}
/* Ensure all numbers are valid */
if (hour > 23) goto invalid;
if (minute > 59) goto invalid;
if (second > 59) goto invalid;
if (MS_UNLIKELY(round_up_micros)) {
time_round_up_micros(&hour, &minute, &second, µsecond);
}
if (!ms_passes_tz_constraint(tz, type, path)) goto error;
PyObject *out = PyDateTimeAPI->Time_FromTime(
hour, minute, second, microsecond, tz, PyDateTimeAPI->TimeType
);
Py_XDECREF(tz);
return out;
invalid:
ms_error_with_path("Invalid RFC3339 encoded time%U", path);
error:
Py_XDECREF(tz);
return NULL;
}
static PyObject *
ms_decode_datetime_from_int64(
int64_t timestamp, TypeNode *type, PathNode *path
) {
return datetime_from_epoch(timestamp, 0, type, path);
}
static PyObject *
ms_decode_datetime_from_uint64(
uint64_t timestamp, TypeNode *type, PathNode *path
) {
if (timestamp > LLONG_MAX) {
timestamp = LLONG_MAX; /* will raise out of range error later */
}
return datetime_from_epoch((int64_t)timestamp, 0, type, path);
}
static PyObject *
ms_decode_datetime_from_float(
double timestamp, TypeNode *type, PathNode *path
) {
if (MS_UNLIKELY(!isfinite(timestamp))) {
return ms_error_with_path("Invalid epoch timestamp%U", path);
}
int64_t secs = trunc(timestamp);
int32_t nanos = 1000000000 * (timestamp - secs);
if (nanos && timestamp < 0) {
secs--;
nanos += 1000000000;
}
return datetime_from_epoch(secs, nanos, type, path);
}
static PyObject *
ms_decode_datetime_from_str(
const char *buf, Py_ssize_t size,
TypeNode *type, PathNode *path
) {
int year, month, day, hour, minute, second, microsecond = 0;
const char *buf_end = buf + size;
bool round_up_micros = false;
PyObject *tz = NULL;
char c;
/* A valid datetime is at least 19 characters in length */
if (size < 19) goto invalid;
/* Parse date */
if ((buf = ms_read_fixint(buf, 4, &year)) == NULL) goto invalid;
if (*buf++ != '-') goto invalid;
if ((buf = ms_read_fixint(buf, 2, &month)) == NULL) goto invalid;
if (*buf++ != '-') goto invalid;
if ((buf = ms_read_fixint(buf, 2, &day)) == NULL) goto invalid;
/* RFC3339 date/time separator can be T or t. We also support ' ', which is
* ISO8601 compatible. */
c = *buf++;
if (!(c == 'T' || c == 't' || c == ' ')) goto invalid;
/* Parse time */
if ((buf = ms_read_fixint(buf, 2, &hour)) == NULL) goto invalid;
if (*buf++ != ':') goto invalid;
if ((buf = ms_read_fixint(buf, 2, &minute)) == NULL) goto invalid;
if (*buf++ != ':') goto invalid;
if ((buf = ms_read_fixint(buf, 2, &second)) == NULL) goto invalid;
/* Remaining reads require bounds check */
#define next_or_null() (buf == buf_end) ? '\0' : *buf++
c = next_or_null();
/* Parse decimal if present.
*
* Python datetime's only supports microsecond precision, but RFC3339
* doesn't specify a decimal precision limit. To work around this we
* support infinite decimal digits, but round to the closest microsecond.
* This means that nanosecond timestamps won't properly roundtrip through
* datetime objects, but there's not much we can do about that. Other
* systems commonly accept 3 or 6 digits, support for/usage of nanosecond
* precision is rare. */
if (c == '.') {
int ndigits = 0;
while (ndigits < 6) {
c = next_or_null();
if (!is_digit(c)) goto end_decimal;
ndigits++;
microsecond = microsecond * 10 + (c - '0');
}
c = next_or_null();
if (is_digit(c)) {
/* This timestamp has higher precision than microseconds; parse
* the next digit to support rounding, then skip all remaining
* digits */
if ((c - '0') >= 5) {
round_up_micros = true;
}
while (true) {
c = next_or_null();
if (!is_digit(c)) break;
}
}
end_decimal:
/* Error if no digits after decimal */
if (ndigits == 0) goto invalid;
int pow10[6] = {100000, 10000, 1000, 100, 10, 1};
/* Scale microseconds appropriately */
microsecond *= pow10[ndigits - 1];
}
#undef next_or_null
if (c != '\0') {
/* Parse timezone */
int offset = 0;
if (c == 'Z' || c == 'z') {
/* Check for trailing characters */
if (buf != buf_end) goto invalid;
}
else {
int offset_hour, offset_min;
if (c == '-') {
offset = -1;
}
else if (c == '+') {
offset = 1;
}
else {
goto invalid;
}
if (buf_end - buf < 3) goto invalid;
if ((buf = ms_read_fixint(buf, 2, &offset_hour)) == NULL) goto invalid;
/* RFC3339 requires a ':' separator, ISO8601 doesn't. We support
* either */
if (*buf == ':') buf++;
if (buf_end - buf != 2) goto invalid;
if ((buf = ms_read_fixint(buf, 2, &offset_min)) == NULL) goto invalid;
if (offset_hour > 23 || offset_min > 59) goto invalid;
offset *= (offset_hour * 60 + offset_min);
}
if (offset == 0) {
tz = PyDateTime_TimeZone_UTC;
Py_INCREF(tz);
}
else {
tz = timezone_from_offset(offset);
if (tz == NULL) goto error;
}
}
else {
tz = Py_None;
Py_INCREF(tz);
}
/* Ensure all numbers are valid */
if (year == 0) goto invalid;
if (month == 0 || month > 12) goto invalid;
if (day == 0 || day > days_in_month(year, month)) goto invalid;
if (hour > 23) goto invalid;
if (minute > 59) goto invalid;
if (second > 59) goto invalid;
if (MS_UNLIKELY(round_up_micros)) {
if (
datetime_round_up_micros(
&year, &month, &day, &hour, &minute, &second, µsecond
) < 0
) goto invalid;
}
if (!ms_passes_tz_constraint(tz, type, path)) goto error;
PyObject *out = PyDateTimeAPI->DateTime_FromDateAndTime(
year, month, day, hour, minute, second, microsecond, tz,
PyDateTimeAPI->DateTimeType
);
Py_XDECREF(tz);
return out;
invalid:
ms_error_with_path("Invalid RFC3339 encoded datetime%U", path);
error:
Py_XDECREF(tz);
return NULL;
}
/* Requires 26 bytes of scratch space */
static int
ms_encode_timedelta(PyObject *obj, char *out) {
const char *start = out;
int days = PyDateTime_DELTA_GET_DAYS(obj);
int secs = PyDateTime_DELTA_GET_SECONDS(obj);
int micros = PyDateTime_DELTA_GET_MICROSECONDS(obj);
if (days < 0) {
*out++ = '-';
days = -days;
if (secs != 0 || micros != 0) {
days--;
if (micros != 0) {
micros = 1000000 - micros;
secs += 1;
}
secs = 86400 - secs;
}
}
*out++ = 'P';
if (days != 0) {
out = write_u64(days, out);
*out++ = 'D';
}
if (secs != 0 || micros != 0) {
*out++ = 'T';
out = write_u64(secs, out);
if (micros != 0) {
*out++ = '.';
write_u32_6_digits(micros, out);
out += 6;
while (*(out - 1) == '0') {
out--;
}
}
*out++ = 'S';
}
else if (days == 0) {
*out++ = '0';
*out++ = 'D';
}
return out - start;
}
#define MS_TIMEDELTA_MAX_SECONDS (86399999999999LL)
#define MS_TIMEDELTA_MIN_SECONDS (-86399999913600LL)
static PyObject *
ms_timedelta_from_parts(int64_t secs, int micros) {
int64_t days = secs / (24 * 60 * 60);
secs -= days * (24 * 60 * 60);
return PyDelta_FromDSU(days, secs, micros);
}
static PyObject *
ms_decode_timedelta_from_uint64(uint64_t x, PathNode *path) {
if (x > (uint64_t)MS_TIMEDELTA_MAX_SECONDS) {
return ms_error_with_path("Duration is out of range%U", path);
}
return ms_timedelta_from_parts((int64_t)x, 0);
}
static PyObject *
ms_decode_timedelta_from_int64(int64_t x, PathNode *path) {
if ((x > MS_TIMEDELTA_MAX_SECONDS) || (x < MS_TIMEDELTA_MIN_SECONDS)) {
return ms_error_with_path("Duration is out of range%U", path);
}
return ms_timedelta_from_parts(x, 0);
}
static PyObject *
ms_decode_timedelta_from_float(double x, PathNode *path) {
if (
(!isfinite(x)) ||
(x > (double)MS_TIMEDELTA_MAX_SECONDS) ||
(x < (double)MS_TIMEDELTA_MIN_SECONDS)
) {
return ms_error_with_path("Duration is out of range%U", path);
}
int64_t secs = trunc(x);
long micros = lround(1000000 * (x - secs));
return ms_timedelta_from_parts(secs, micros);
}
enum timedelta_parse_state {
TIMEDELTA_START = 0,
TIMEDELTA_D = 1,
TIMEDELTA_T = 2,
TIMEDELTA_H = 3,
TIMEDELTA_M = 4,
TIMEDELTA_S = 5,
};
/* Parses a timedelta from an extended ISO8601 Duration. We try to follow the
* ISO8601-2 spec as closely as possible, extrapolating as needed when the spec
* is vague. We've also limited support for some units/ranges as needed to fit
* python's timedelta model.
*
* Values parsed here are compatible with Java's `Time.Duration.parse`, as well
* as the proposed javascript `Temporal.Duration.from` API.
*
* We accept the following format: [-/+]P#DT#H#M#S
*
* where # is a number with optional decimal component. Characters are case
* insensitive.
*
* Additional restrictions, mostly taken from the ISO spec. Extrapolations or
* self-imposed restrictions are noted.
*
* - The units D (days), H (hours), M (minutes) and S (seconds) may be omitted
* if their value is 0.
*
* - At least one value must be present (`P0D` is a valid 0 duration, but `P`
* is not).
*
* - If present, the values must be in the proper unit order (D, H, M, S).
*
* - If a unit value contains a fractional number, it must be the last unit.
* `PT1H1.5S` and `PT1.5H` are valid but `PT1.5H1S` is not.
*
* - Unlike JSON numbers, leading 0s are fine. `P001D` and `P1D` are
* equivalent.
*
* - If `T` is present, there must be at least one time component after it.
* This isn't explicitly said in the spec, but is enforced by both Java and
* Temporal APIs.
*
* - A leading `-` or `+` may be used to indicate a negative or positive
* duration. This is part of the extended spec in ISO8601-2, and is supported
* by both Java and Temporal apis.
*
* - We don't support relative duration units (Y (year), M (month), W (week)).
* Python's timedeltas are absolute deltas composed of fixed-length days,
* seconds, and microseconds. There's no way to accurately store a relative
* quantity like "months". Java's Duration implementation has the same
* restriction.
*
* - This implementation will error for durations that exceed python's
* timedelta range limits. The ISO spec provides no restrictions on duration
* range.
*/
static PyObject *
ms_decode_timedelta(
const char *p, Py_ssize_t size,
TypeNode *type, PathNode *path
) {
bool neg = false;
const char *end = p + size;
if (p == end) goto invalid;
if (*p == '-') {
neg = true;
p++;
if (p == end) goto invalid;
}
else if (*p == '+') {
p++;
if (p == end) goto invalid;
}
if (*p != 'P' && *p != 'p') goto invalid;
p++;
if (p == end) goto invalid;
int64_t seconds = 0;
int micros = 0;
enum timedelta_parse_state parse_state = TIMEDELTA_START;
while (true) {
if (p == end) goto invalid; /* Missing segment */
if (*p == 'T' || *p == 't') {
if (parse_state >= TIMEDELTA_T) goto invalid;
parse_state = TIMEDELTA_T;
p++;
continue;
}
uint32_t scale;
bool has_frac = false;
uint64_t x = 0, frac_num = 0, frac_den = 10;
/* Read integral part */
if (!is_digit(*p)) goto invalid;
x = *p - '0';
p++;
while (true) {
if (p == end) goto invalid; /* missing unit */
if (!is_digit(*p)) break;
x = x * 10 + (uint64_t)(*p - '0');
if (x > (1ULL << 47)) goto out_of_range;
p++;
}
if (*p == '.') {
/* Read fractional part */
has_frac = true;
p++;
if (p == end) goto invalid;
if (!is_digit(*p)) goto invalid;
frac_num = *p - '0';
p++;
/* Parse up to 10 more decimal digits.
*
* Since the largest unit we support is days, and python's
* timedelta has microsecond precision, only 11 decimal digits need
* to be read. Any further precision will have no effect on the
* output. */
for (int i = 0; i < 10; i++) {
if (p == end) goto invalid; /* missing unit */
if (!is_digit(*p)) goto parse_unit;
frac_num = frac_num * 10 + (uint64_t)(*p - '0');
frac_den *= 10;
p++;
}
/* Remaining digits won't have any effect on output, skip them */
while (true) {
if (p == end) goto invalid; /* missing unit */
if (!is_digit(*p)) goto parse_unit;
p++;
}
}
parse_unit:
switch (*p++) {
case 'D':
case 'd': {
if (parse_state >= TIMEDELTA_D) goto invalid;
parse_state = TIMEDELTA_D;
scale = 24 * 60 * 60;
break;
};
case 'H':
case 'h': {
if (parse_state < TIMEDELTA_T || parse_state >= TIMEDELTA_H) goto invalid;
parse_state = TIMEDELTA_H;
scale = 60 * 60;
break;
}
case 'M':
case 'm': {
if (parse_state < TIMEDELTA_T) goto unsupported;
if (parse_state >= TIMEDELTA_M) goto invalid;
parse_state = TIMEDELTA_M;
scale = 60;
break;
};
case 'S':
case 's': {
if (parse_state < TIMEDELTA_T || parse_state >= TIMEDELTA_S) goto invalid;
parse_state = TIMEDELTA_S;
scale = 1;
break;
};
case 'W':
case 'w':
case 'Y':
case 'y':
goto unsupported;
default:
goto invalid;
}
/* Apply integral part */
seconds += scale * x;
if (has_frac) {
/* Apply fractional part */
frac_num *= scale;
int64_t extra_secs = frac_num / frac_den;
int extra_micros = DIV_ROUND_CLOSEST(1000000 * (frac_num - (extra_secs * frac_den)), frac_den);
micros += extra_micros;
if (micros >= 1000000) {
extra_secs++;
micros -= 1000000;
}
seconds += extra_secs;
}
/* Ensure seconds are still in-bounds */
if (seconds > MS_TIMEDELTA_MAX_SECONDS) goto out_of_range;
if (p == end) {
break;
}
else if (has_frac) {
goto invalid; /* decimal segment must be last */
}
}
if (neg) {
seconds = -seconds;
if (micros) {
micros = 1000000 - micros;
seconds -= 1;
}
/* abs(lower_limit) < upper_limit, so we need to recheck it here */
if (seconds < MS_TIMEDELTA_MIN_SECONDS) goto out_of_range;
}
int64_t days = seconds / (24 * 60 * 60);
seconds -= days * (24 * 60 * 60);
return PyDelta_FromDSU(days, seconds, micros);
invalid:
return ms_error_with_path("Invalid ISO8601 duration%U", path);
out_of_range:
return ms_error_with_path("Duration is out of range%U", path);
unsupported:
return ms_error_with_path(
"Only units 'D', 'H', 'M', and 'S' are supported when parsing ISO8601 durations%U",
path
);
}
/*************************************************************************
* Base64 Encoder *
*************************************************************************/
static Py_ssize_t
ms_encode_base64_size(MsgspecState *mod, Py_ssize_t input_size) {
if (input_size >= (1LL << 32)) {
PyErr_SetString(
mod->EncodeError,
"Can't encode bytes-like objects longer than 2**32 - 1"
);
return -1;
}
/* ceil(4/3 * input_size) */
return 4 * ((input_size + 2) / 3);
}
static void
ms_encode_base64(const char *input, Py_ssize_t input_size, char *out) {
int nbits = 0;
unsigned int charbuf = 0;
for (; input_size > 0; input_size--, input++) {
charbuf = (charbuf << 8) | (unsigned char)(*input);
nbits += 8;
while (nbits >= 6) {
unsigned char ind = (charbuf >> (nbits - 6)) & 0x3f;
nbits -= 6;
*out++ = base64_encode_table[ind];
}
}
if (nbits == 2) {
*out++ = base64_encode_table[(charbuf & 3) << 4];
*out++ = '=';
*out++ = '=';
}
else if (nbits == 4) {
*out++ = base64_encode_table[(charbuf & 0xf) << 2];
*out++ = '=';
}
}
/*************************************************************************
* UUID Utilities *
*************************************************************************/
static int
ms_uuid_to_16_bytes(MsgspecState *mod, PyObject *obj, unsigned char *buf) {
PyObject *int128 = PyObject_GetAttr(obj, mod->str_int);
if (int128 == NULL) return -1;
if (MS_UNLIKELY(!PyLong_CheckExact(int128))) {
PyErr_SetString(PyExc_TypeError, "uuid.int must be an int");
return -1;
}
#if PY313_PLUS
int out = (int)PyLong_AsNativeBytes(
int128,
buf,
16,
Py_ASNATIVEBYTES_BIG_ENDIAN | Py_ASNATIVEBYTES_UNSIGNED_BUFFER
);
#else
int out = _PyLong_AsByteArray((PyLongObject *)int128, buf, 16, 0, 0);
#endif
Py_DECREF(int128);
return out;
}
static PyObject *
ms_uuid_from_16_bytes(const unsigned char *buf) {
PyObject *int128 = _PyLong_FromByteArray(buf, 16, 0, 0);
if (int128 == NULL) return NULL;
MsgspecState *mod = msgspec_get_global_state();
PyTypeObject *uuid_type = (PyTypeObject *)(mod->UUIDType);
PyObject *out = uuid_type->tp_alloc(uuid_type, 0);
if (out == NULL) goto error;
/* UUID objects are immutable, use GenericSetAttr instead of SetAttr */
if (PyObject_GenericSetAttr(out, mod->str_int, int128) < 0) goto error;
if (PyObject_GenericSetAttr(out, mod->str_is_safe, mod->uuid_safeuuid_unknown) < 0) goto error;
Py_DECREF(int128);
return out;
error:
Py_DECREF(int128);
Py_XDECREF(out);
return NULL;
}
/* Requires up to 36 bytes of space */
static int
ms_encode_uuid(MsgspecState *mod, PyObject *obj, char *out, bool canonical) {
unsigned char scratch[16];
unsigned char *buf = scratch;
if (ms_uuid_to_16_bytes(mod, obj, scratch) < 0) return -1;
for (int i = 0; i < 4; i++) {
unsigned char c = *buf++;
*out++ = hex_encode_table[c >> 4];
*out++ = hex_encode_table[c & 0xF];
}
if (canonical) *out++ = '-';
for (int j = 0; j < 3; j++) {
for (int i = 0; i < 2; i++) {
unsigned char c = *buf++;
*out++ = hex_encode_table[c >> 4];
*out++ = hex_encode_table[c & 0xF];
}
if (canonical) *out++ = '-';
}
for (int i = 0; i < 6; i++) {
unsigned char c = *buf++;
*out++ = hex_encode_table[c >> 4];
*out++ = hex_encode_table[c & 0xF];
}
return 0;
}
static PyObject *
ms_decode_uuid_from_str(const char *buf, Py_ssize_t size, PathNode *path) {
unsigned char scratch[16];
unsigned char *decoded = scratch;
int segments[] = {4, 2, 2, 2, 6};
/* A valid uuid is 32 or 36 characters in length */
if (size != 32 && size != 36) goto invalid;
bool has_hyphens = size == 36;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < segments[i]; j++) {
char hi = *buf++;
if (hi >= '0' && hi <= '9') { hi -= '0'; }
else if (hi >= 'a' && hi <= 'f') { hi = hi - 'a' + 10; }
else if (hi >= 'A' && hi <= 'F') { hi = hi - 'A' + 10; }
else { goto invalid; }
char lo = *buf++;
if (lo >= '0' && lo <= '9') { lo -= '0'; }
else if (lo >= 'a' && lo <= 'f') { lo = lo - 'a' + 10; }
else if (lo >= 'A' && lo <= 'F') { lo = lo - 'A' + 10; }
else { goto invalid; }
*decoded++ = ((unsigned char)hi << 4) + (unsigned char)lo;
}
if (has_hyphens && i < 4 && *buf++ != '-') goto invalid;
}
return ms_uuid_from_16_bytes(scratch);
invalid:
return ms_error_with_path("Invalid UUID%U", path);
}
static PyObject *
ms_decode_uuid_from_bytes(const char *buf, Py_ssize_t size, PathNode *path) {
if (size == 16) {
return ms_uuid_from_16_bytes((unsigned char *)buf);
}
return ms_error_with_path("Invalid UUID bytes%U", path);
}
/*************************************************************************
* Decimal Utilities *
*************************************************************************/
static PyObject *
ms_decode_decimal_from_pyobj(PyObject *str, PathNode *path, MsgspecState *mod) {
if (mod == NULL) {
mod = msgspec_get_global_state();
}
return PyObject_CallOneArg(mod->DecimalType, str);
}
static PyObject *
ms_decode_decimal_from_pystr(PyObject *str, PathNode *path, MsgspecState *mod) {
PyObject *out = ms_decode_decimal_from_pyobj(str, path, mod);
if (out == NULL) {
ms_error_with_path("Invalid decimal string%U", path);
}
return out;
}
static PyObject *
ms_decode_decimal(
const char *view, Py_ssize_t size, bool is_ascii, PathNode *path, MsgspecState *mod
) {
PyObject *str;
if (MS_LIKELY(is_ascii)) {
str = PyUnicode_New(size, 127);
if (str == NULL) return NULL;
memcpy(ascii_get_buffer(str), view, size);
}
else {
str = PyUnicode_DecodeUTF8(view, size, NULL);
if (str == NULL) return NULL;
}
PyObject *out = ms_decode_decimal_from_pystr(str, path, mod);
Py_DECREF(str);
return out;
}
static PyObject *
ms_decode_decimal_from_int64(int64_t x, PathNode *path) {
PyObject *temp = PyLong_FromLongLong(x);
if (temp == NULL) return NULL;
PyObject *out = ms_decode_decimal_from_pyobj(temp, path, NULL);
Py_DECREF(temp);
return out;
}
static PyObject *
ms_decode_decimal_from_uint64(uint64_t x, PathNode *path) {
PyObject *temp = PyLong_FromUnsignedLongLong(x);
if (temp == NULL) return NULL;
PyObject *out = ms_decode_decimal_from_pyobj(temp, path, NULL);
Py_DECREF(temp);
return out;
}
static PyObject *
ms_decode_decimal_from_float(double val, PathNode *path, MsgspecState *mod) {
if (MS_LIKELY(isfinite(val))) {
/* For finite values, render as the nearest IEEE754 double in string
* form, then call decimal.Decimal to parse */
char buf[24];
int n = write_f64(val, buf, false);
return ms_decode_decimal(buf, n, true, path, mod);
}
else {
/* For nonfinite values, convert to float obj and go through python */
PyObject *temp = PyFloat_FromDouble(val);
if (temp == NULL) return NULL;
PyObject *out = ms_decode_decimal_from_pyobj(temp, path, mod);
Py_DECREF(temp);
return out;
}
}
/*************************************************************************
* strict=False Utilities *
*************************************************************************/
static bool
maybe_parse_number(
const char *, Py_ssize_t, TypeNode *, PathNode *, bool, PyObject **
);
static PyObject *
ms_decode_str_lax(
const char *view,
Py_ssize_t size,
TypeNode *type,
PathNode *path,
bool *invalid
) {
if (type->types & (
MS_TYPE_INT | MS_TYPE_INTENUM | MS_TYPE_INTLITERAL |
MS_TYPE_BOOL |
MS_TYPE_FLOAT | MS_TYPE_DECIMAL |
MS_TYPE_DATETIME | MS_TYPE_TIMEDELTA
)
) {
PyObject *out;
if (maybe_parse_number(view, size, type, path, false, &out)) {
return out;
}
}
if (type->types & MS_TYPE_BOOL) {
if (size == 4) {
if (
(view[0] == 't' || view[0] == 'T') &&
(view[1] == 'r' || view[1] == 'R') &&
(view[2] == 'u' || view[2] == 'U') &&
(view[3] == 'e' || view[3] == 'E')
) {
Py_RETURN_TRUE;
}
}
else if (size == 5) {
if (
(view[0] == 'f' || view[0] == 'F') &&
(view[1] == 'a' || view[1] == 'A') &&
(view[2] == 'l' || view[2] == 'L') &&
(view[3] == 's' || view[3] == 'S') &&
(view[4] == 'e' || view[4] == 'E')
) {
Py_RETURN_FALSE;
}
}
}
if (type->types & MS_TYPE_NONE) {
if (size == 4 &&
(view[0] == 'n' || view[0] == 'N') &&
(view[1] == 'u' || view[1] == 'U') &&
(view[2] == 'l' || view[2] == 'L') &&
(view[3] == 'l' || view[3] == 'L')
) {
Py_RETURN_NONE;
}
}
*invalid = true;
return NULL;
}
/*************************************************************************
* Shared Post-Decode Handlers *
*************************************************************************/
static PyObject *
ms_post_decode_int64(
int64_t x, TypeNode *type, PathNode *path, bool strict, bool from_str
) {
if (MS_LIKELY(type->types & (MS_TYPE_ANY | MS_TYPE_INT))) {
return ms_decode_int(x, type, path);
}
else if (type->types & (MS_TYPE_INTENUM | MS_TYPE_INTLITERAL)) {
return ms_decode_int_enum_or_literal_int64(x, type, path);
}
else if (type->types & MS_TYPE_FLOAT) {
return ms_decode_float(x, type, path);
}
else if (type->types & MS_TYPE_DECIMAL) {
return ms_decode_decimal_from_int64(x, path);
}
else if (!strict) {
if (type->types & MS_TYPE_BOOL) {
PyObject *out = ms_maybe_decode_bool_from_int64(x);
if (out != NULL) return out;
}
if (type->types & MS_TYPE_DATETIME) {
return ms_decode_datetime_from_int64(x, type, path);
}
if (type->types & MS_TYPE_TIMEDELTA) {
return ms_decode_timedelta_from_int64(x, path);
}
}
return ms_validation_error(from_str ? "str" : "int", type, path);
}
static PyObject *
ms_post_decode_uint64(
uint64_t x, TypeNode *type, PathNode *path, bool strict, bool from_str
) {
if (MS_LIKELY(type->types & (MS_TYPE_ANY | MS_TYPE_INT))) {
return ms_decode_uint(x, type, path);
}
else if (type->types & (MS_TYPE_INTENUM | MS_TYPE_INTLITERAL)) {
return ms_decode_int_enum_or_literal_uint64(x, type, path);
}
else if (type->types & MS_TYPE_FLOAT) {
return ms_decode_float(x, type, path);
}
else if (type->types & MS_TYPE_DECIMAL) {
return ms_decode_decimal_from_uint64(x, path);
}
else if (!strict) {
if (type->types & MS_TYPE_BOOL) {
PyObject *out = ms_maybe_decode_bool_from_uint64(x);
if (out != NULL) return out;
}
if (type->types & MS_TYPE_DATETIME) {
return ms_decode_datetime_from_uint64(x, type, path);
}
if (type->types & MS_TYPE_TIMEDELTA) {
return ms_decode_timedelta_from_uint64(x, path);
}
}
return ms_validation_error(from_str ? "str" : "int", type, path);
}
static bool
double_as_int64(double x, int64_t *out) {
if (fmod(x, 1.0) != 0.0) return false;
if (x > (1LL << 53)) return false;
if (x < (-1LL << 53)) return false;
*out = (int64_t)x;
return true;
}
static PyObject *
ms_post_decode_float(
double x, TypeNode *type, PathNode *path, bool strict, bool from_str
) {
if (type->types & (MS_TYPE_ANY | MS_TYPE_FLOAT)) {
return ms_decode_float(x, type, path);
}
else if (!strict) {
if (type->types & MS_TYPE_INT) {
int64_t out;
if (double_as_int64(x, &out)) {
return ms_post_decode_int64(out, type, path, strict, from_str);
}
}
if (type->types & MS_TYPE_DATETIME) {
return ms_decode_datetime_from_float(x, type, path);
}
if (type->types & MS_TYPE_TIMEDELTA) {
return ms_decode_timedelta_from_float(x, path);
}
}
return ms_validation_error(from_str ? "str" : "float", type, path);
}
/*************************************************************************
* Number Parser *
*************************************************************************/
#define ONE_E18 1000000000000000000ULL
#define ONE_E19_MINUS_ONE 9999999999999999999ULL
static MS_NOINLINE PyObject *
parse_number_fallback(
const unsigned char* integer_start,
const unsigned char* integer_end,
const unsigned char* fraction_start,
const unsigned char* fraction_end,
int32_t exp_part,
bool is_negative,
TypeNode *type,
PathNode *path,
bool strict,
bool from_str
) {
uint32_t nd = 0;
int32_t dp = 0;
ms_hpd dec;
dec.num_digits = 0;
dec.decimal_point = 0;
dec.negative = is_negative;
dec.truncated = false;
/* Parse integer */
const unsigned char *p = integer_start;
if (*p != '0') {
while (p < integer_end) {
if (MS_LIKELY(nd < MS_HPD_MAX_DIGITS)) {
dec.digits[nd++] = (uint8_t)(*p - '0');
}
else if (*p != '0') {
dec.truncated = true;
}
dp++;
p++;
}
}
p = fraction_start;
while (p < fraction_end) {
if (*p == '0') {
if (nd == 0) {
/* Track leading zeros implicitly */
dp--;
}
else if (nd < MS_HPD_MAX_DIGITS) {
dec.digits[nd++] = (uint8_t)(*p - '0');
}
}
else if ('1' <= *p && *p <= '9') {
if (nd < MS_HPD_MAX_DIGITS) {
dec.digits[nd++] = (uint8_t)(*p - '0');
}
else {
dec.truncated = true;
}
}
p++;
}
dp += exp_part;
dec.num_digits = nd;
if (dp < -MS_HPD_DP_RANGE) {
dec.decimal_point = -(MS_HPD_DP_RANGE + 1);
}
else if (dp > MS_HPD_DP_RANGE) {
dec.decimal_point = (MS_HPD_DP_RANGE + 1);
}
else {
dec.decimal_point = dp;
}
ms_hpd_trim(&dec);
double res = ms_hpd_to_double(&dec);
if (Py_IS_INFINITY(res)) {
return ms_error_with_path("Number out of range%U", path);
}
return ms_post_decode_float(res, type, path, strict, from_str);
}
static MS_NOINLINE PyObject *
parse_number_nonfinite(
const unsigned char *start,
bool is_negative,
const unsigned char *p,
const unsigned char *pend,
const char **errmsg,
TypeNode *type,
PathNode *path,
bool strict
) {
size_t size = pend - p;
double val;
if (size == 3) {
if (
(p[0] == 'n' || p[0] == 'N') &&
(p[1] == 'a' || p[1] == 'A') &&
(p[2] == 'n' || p[2] == 'N')
) {
val = NAN;
goto done;
}
else if (
(p[0] == 'i' || p[0] == 'I') &&
(p[1] == 'n' || p[1] == 'N') &&
(p[2] == 'f' || p[2] == 'F')
) {
val = INFINITY;
goto done;
}
}
else if (size == 8) {
if (
(p[0] == 'i' || p[0] == 'I') &&
(p[1] == 'n' || p[1] == 'N') &&
(p[2] == 'f' || p[2] == 'F') &&
(p[3] == 'i' || p[3] == 'I') &&
(p[4] == 'n' || p[4] == 'N') &&
(p[5] == 'i' || p[5] == 'I') &&
(p[6] == 't' || p[6] == 'T') &&
(p[7] == 'y' || p[7] == 'Y')
) {
val = INFINITY;
goto done;
}
}
*errmsg = "invalid number";
return NULL;
done:
if (
MS_UNLIKELY(
!(type->types & (MS_TYPE_ANY | MS_TYPE_FLOAT))
&& type->types & MS_TYPE_DECIMAL
)
) {
return ms_decode_decimal(
(char *)start, pend - start, true, path, NULL
);
}
if (is_negative) {
val = -val;
}
return ms_post_decode_float(val, type, path, strict, true);
}
static MS_NOINLINE PyObject *
json_float_hook(
const char *buf, Py_ssize_t size, PathNode *path, PyObject *float_hook
) {
PyObject *str = PyUnicode_New(size, 127);
if (str == NULL) return NULL;
memcpy(ascii_get_buffer(str), buf, size);
PyObject *out = PyObject_CallOneArg(float_hook, str);
Py_DECREF(str);
if (out == NULL) {
ms_maybe_wrap_validation_error(path);
return NULL;
}
return out;
}
static MS_INLINE PyObject *
parse_number_inline(
const unsigned char *p,
const unsigned char *pend,
const unsigned char **pout,
const char **errmsg,
TypeNode *type,
PathNode *path,
bool strict,
PyObject *float_hook,
bool from_str
) {
uint64_t mantissa = 0;
int64_t exponent = 0;
int32_t exp_part = 0;
bool is_negative = false;
bool is_float = false;
bool is_truncated = false;
const unsigned char *start = p;
/* We know there is at least one byte available when this function is
* called */
if (*p == '-') {
/* Parse minus sign */
p++;
if (p == pend) goto invalid_number;
is_negative = true;
}
const unsigned char *integer_start = p;
/* Parse integer */
if (MS_UNLIKELY(*p == '0')) {
p++;
if (MS_UNLIKELY(p != pend && is_digit(*p))) goto invalid_number;
}
else {
unsigned char c = *p;
while (MS_LIKELY(is_digit(c))) {
mantissa = mantissa * 10 + (uint8_t)(c - '0');
p++;
if (MS_UNLIKELY(p == pend)) break;
c = *p;
}
/* There must be at least one digit */
if (MS_UNLIKELY(integer_start == p)) {
if (MS_UNLIKELY(from_str)) {
return parse_number_nonfinite(
start, is_negative, p, pend, errmsg, type, path, strict
);
}
else {
goto invalid_character;
}
}
}
const unsigned char *integer_end = p;
int64_t digit_count = integer_end - integer_start;
const unsigned char *fraction_start = NULL;
const unsigned char *fraction_end = NULL;
if (MS_UNLIKELY(p == pend)) goto end_parsing;
if (*p == '.') {
is_float = true;
p++;
/* Parse fraction */
fraction_start = p;
while (MS_LIKELY(p != pend && is_digit(*p))) {
mantissa = mantissa * 10 + (uint8_t)(*p - '0');
p++;
}
/* Error if no digits after decimal */
if (MS_UNLIKELY(fraction_start == p)) goto invalid_number;
fraction_end = p;
exponent = fraction_start - p;
digit_count -= exponent;
if (MS_UNLIKELY(p == pend)) goto end_parsing;
}
if (*p == 'e' || *p == 'E') {
is_float = true;
int32_t exp_sign = 1;
p++;
if (p == pend) goto invalid_number;
/* Parse exponent sign (if any) */
if (*p == '+') {
p++;
}
else if (*p == '-') {
p++;
exp_sign = -1;
}
/* Parse exponent digits */
const unsigned char *start_exponent = p;
while (p != pend && is_digit(*p)) {
if (MS_LIKELY(exp_part < 10000)) {
exp_part = exp_part * 10 + (uint8_t)(*p - '0');
}
p++;
}
/* Error if no digits in exponent */
if (MS_UNLIKELY(start_exponent == p)) goto invalid_number;
exp_part *= exp_sign;
exponent += exp_part;
}
if (MS_UNLIKELY(from_str)) {
if (MS_UNLIKELY(p != pend)) goto invalid_number;
}
end_parsing:
/* Check for overflow and maybe reparse if needed */
if (MS_UNLIKELY(digit_count > 19)) {
const unsigned char *cur = integer_start;
while ((cur != pend) && (*cur == '0' || *cur == '.')) {
if (*cur == '0') {
digit_count--;
}
cur++;
}
if (
(digit_count > 19) &&
(
(is_float) ||
((integer_end - integer_start) != 20) ||
(*integer_start != '1') ||
(mantissa <= ONE_E19_MINUS_ONE)
)
) {
/* We overflowed. Redo parsing, truncating at 19 digits */
is_truncated = true;
const unsigned char *cur = integer_start;
mantissa = 0;
while ((mantissa < ONE_E18) && (cur != integer_end)) {
mantissa = mantissa * 10 + (uint64_t)(*cur - '0');
cur++;
}
if (mantissa >= ONE_E18) {
exponent = integer_end - cur + exp_part;
}
else {
cur = fraction_start;
while ((mantissa < ONE_E18) && (cur != fraction_end)) {
mantissa = mantissa * 10 + (uint64_t)(*cur - '0');
cur++;
}
exponent = fraction_start - cur + exp_part;
}
}
}
/* Forward output position */
*pout = p;
if (!is_float) {
if (is_negative) {
is_truncated |= (mantissa > (1ull << 63));
}
if (MS_UNLIKELY(is_truncated)) {
if (type->types & (MS_TYPE_ANY | MS_TYPE_INT)) {
return ms_decode_bigint((char *)start, p - start, type, path);
}
}
else {
if (is_negative) {
return ms_post_decode_int64(
-1 * (int64_t)(mantissa), type, path, strict, from_str
);
}
else {
return ms_post_decode_uint64(mantissa, type, path, strict, from_str);
}
}
}
if (
MS_UNLIKELY(
!(type->types & (MS_TYPE_ANY | MS_TYPE_FLOAT))
&& type->types & MS_TYPE_DECIMAL
)
) {
return ms_decode_decimal(
(char *)start, p - start, true, path, NULL
);
}
else if (MS_UNLIKELY(float_hook != NULL && type->types & MS_TYPE_ANY)) {
return json_float_hook((char *)start, p - start, path, float_hook);
}
else {
if (MS_UNLIKELY(exponent > 288 || exponent < -307)) {
/* Exponent is out of bounds */
goto fallback;
}
double val;
if (MS_LIKELY((-22 <= exponent) && (exponent <= 22) && ((mantissa >> 53) == 0))) {
/* If both `mantissa` and `10 ** exponent` can be exactly
* represented as a double, we can take a fast path */
val = (double)(mantissa);
if (exponent >= 0) {
val *= ms_atof_f64_powers_of_10[exponent];
} else {
val /= ms_atof_f64_powers_of_10[-exponent];
}
}
else if (MS_UNLIKELY(mantissa == 0)) {
/* Special case 0 handling. This is only hit if the mantissa is 0
* and the exponent is out of bounds above (i.e. rarely) */
val = 0.0;
}
else {
int64_t r1 = eisel_lemire(mantissa, exponent);
if (MS_UNLIKELY(r1 < 0)) goto fallback;
if (MS_UNLIKELY(is_truncated)) {
int64_t r2 = eisel_lemire(mantissa + 1, exponent);
if (r1 != r2) goto fallback;
}
uint64_t bits = ((uint64_t)r1);
memcpy(&val, &bits, sizeof(double));
}
if (is_negative) {
val = -val;
}
return ms_post_decode_float(val, type, path, strict, from_str);
}
fallback:
return parse_number_fallback(
integer_start, integer_end,
fraction_start, fraction_end,
exp_part,
is_negative,
type, path, strict, from_str
);
invalid_number:
if (pout != NULL) *pout = p;
*errmsg = "invalid number";
return NULL;
invalid_character:
if (pout != NULL) *pout = p;
*errmsg = "invalid character";
return NULL;
}
static MS_NOINLINE bool
maybe_parse_number(
const char *view,
Py_ssize_t size,
TypeNode *type,
PathNode *path,
bool strict,
PyObject **out
) {
const char *errmsg = NULL;
const unsigned char *pout;
*out = parse_number_inline(
(const unsigned char *)view,
(const unsigned char *)(view + size),
&pout,
&errmsg,
type,
path,
strict,
NULL,
true
);
return (*out != NULL || errmsg == NULL);
}
/*************************************************************************
* MessagePack Encoder *
*************************************************************************/
PyDoc_STRVAR(Encoder__doc__,
"Encoder(*, enc_hook=None, decimal_format='string', uuid_format='canonical', order=None)\n"
"--\n"
"\n"
"A MessagePack encoder.\n"
"\n"
"Parameters\n"
"----------\n"
"enc_hook : callable, optional\n"
" A callable to call for objects that aren't supported msgspec types. Takes\n"
" the unsupported object and should return a supported object, or raise a\n"
" ``NotImplementedError`` if unsupported.\n"
"decimal_format : {'string', 'number'}, optional\n"
" The format to use for encoding `decimal.Decimal` objects. If 'string'\n"
" they're encoded as strings, if 'number', they're encoded as floats.\n"
" Defaults to 'string', which is the recommended value since 'number'\n"
" may result in precision loss when decoding.\n"
"uuid_format : {'canonical', 'hex', 'bytes'}, optional\n"
" The format to use for encoding `uuid.UUID` objects. The 'canonical'\n"
" and 'hex' formats encode them as strings with and without hyphens\n"
" respectively. The 'bytes' format encodes them as big-endian binary\n"
" representations of the corresponding 128-bit integers. Defaults to\n"
" 'canonical'.\n"
"order : {None, 'deterministic', 'sorted'}, optional\n"
" The ordering to use when encoding unordered compound types.\n"
"\n"
" - ``None``: All objects are encoded in the most efficient manner matching\n"
" their in-memory representations. The default.\n"
" - `'deterministic'`: Unordered collections (sets, dicts) are sorted to\n"
" ensure a consistent output between runs. Useful when comparison/hashing\n"
" of the encoded binary output is necessary.\n"
" - `'sorted'`: Like `'deterministic'`, but *all* object-like types (structs,\n"
" dataclasses, ...) are also sorted by field name before encoding. This is\n"
" slower than `'deterministic'`, but may produce more human-readable output."
);
enum mpack_code {
MP_NIL = '\xc0',
MP_FALSE = '\xc2',
MP_TRUE = '\xc3',
MP_FLOAT32 = '\xca',
MP_FLOAT64 = '\xcb',
MP_UINT8 = '\xcc',
MP_UINT16 = '\xcd',
MP_UINT32 = '\xce',
MP_UINT64 = '\xcf',
MP_INT8 = '\xd0',
MP_INT16 = '\xd1',
MP_INT32 = '\xd2',
MP_INT64 = '\xd3',
MP_FIXSTR = '\xa0',
MP_STR8 = '\xd9',
MP_STR16 = '\xda',
MP_STR32 = '\xdb',
MP_BIN8 = '\xc4',
MP_BIN16 = '\xc5',
MP_BIN32 = '\xc6',
MP_FIXARRAY = '\x90',
MP_ARRAY16 = '\xdc',
MP_ARRAY32 = '\xdd',
MP_FIXMAP = '\x80',
MP_MAP16 = '\xde',
MP_MAP32 = '\xdf',
MP_FIXEXT1 = '\xd4',
MP_FIXEXT2 = '\xd5',
MP_FIXEXT4 = '\xd6',
MP_FIXEXT8 = '\xd7',
MP_FIXEXT16 = '\xd8',
MP_EXT8 = '\xc7',
MP_EXT16 = '\xc8',
MP_EXT32 = '\xc9',
};
static int mpack_encode_inline(EncoderState *self, PyObject *obj);
static int mpack_encode_dict_key_inline(EncoderState *self, PyObject *obj);
static int mpack_encode(EncoderState *self, PyObject *obj);
static int
mpack_encode_none(EncoderState *self)
{
const char op = MP_NIL;
return ms_write(self, &op, 1);
}
static int
mpack_encode_bool(EncoderState *self, PyObject *obj)
{
const char op = (obj == Py_True) ? MP_TRUE : MP_FALSE;
return ms_write(self, &op, 1);
}
static MS_NOINLINE int
mpack_encode_long(EncoderState *self, PyObject *obj)
{
bool overflow, neg;
uint64_t ux;
overflow = fast_long_extract_parts(obj, &neg, &ux);
if (MS_UNLIKELY(overflow)) {
PyErr_SetString(
PyExc_OverflowError,
"can't serialize ints < -2**63 or > 2**64 - 1"
);
return -1;
}
if (MS_UNLIKELY(neg)) {
int64_t x = -ux;
if(x < -(1LL<<5)) {
if(x < -(1LL<<15)) {
if(x < -(1LL<<31)) {
char buf[9];
buf[0] = MP_INT64;
_msgspec_store64(&buf[1], x);
return ms_write(self, buf, 9);
} else {
char buf[5];
buf[0] = MP_INT32;
_msgspec_store32(&buf[1], (int32_t)x);
return ms_write(self, buf, 5);
}
} else {
if(x < -(1<<7)) {
char buf[3];
buf[0] = MP_INT16;
_msgspec_store16(&buf[1], (int16_t)x);
return ms_write(self, buf, 3);
} else {
char buf[2] = {MP_INT8, (x & 0xff)};
return ms_write(self, buf, 2);
}
}
}
else {
char buf[1] = {(x & 0xff)};
return ms_write(self, buf, 1);
}
}
else {
if (ux < (1<<7)) {
char buf[1] = {(ux & 0xff)};
return ms_write(self, buf, 1);
} else {
if(ux < (1<<16)) {
if(ux < (1<<8)) {
char buf[2] = {MP_UINT8, (ux & 0xff)};
return ms_write(self, buf, 2);
} else {
char buf[3];
buf[0] = MP_UINT16;
_msgspec_store16(&buf[1], (uint16_t)ux);
return ms_write(self, buf, 3);
}
} else {
if(ux < (1LL<<32)) {
char buf[5];
buf[0] = MP_UINT32;
_msgspec_store32(&buf[1], (uint32_t)ux);
return ms_write(self, buf, 5);
} else {
char buf[9];
buf[0] = MP_UINT64;
_msgspec_store64(&buf[1], ux);
return ms_write(self, buf, 9);
}
}
}
}
}
static MS_NOINLINE int
mpack_encode_float(EncoderState *self, PyObject *obj)
{
char buf[9];
double x = PyFloat_AS_DOUBLE(obj);
uint64_t ux = 0;
memcpy(&ux, &x, sizeof(double));
buf[0] = MP_FLOAT64;
_msgspec_store64(&buf[1], ux);
return ms_write(self, buf, 9);
}
static MS_NOINLINE int
mpack_encode_cstr(EncoderState *self, const char *buf, Py_ssize_t len)
{
if (buf == NULL) {
return -1;
}
if (len < 32) {
char header[1] = {MP_FIXSTR | (uint8_t)len};
if (ms_write(self, header, 1) < 0)
return -1;
} else if (len < (1 << 8)) {
char header[2] = {MP_STR8, (uint8_t)len};
if (ms_write(self, header, 2) < 0)
return -1;
} else if (len < (1 << 16)) {
char header[3];
header[0] = MP_STR16;
_msgspec_store16(&header[1], (uint16_t)len);
if (ms_write(self, header, 3) < 0)
return -1;
} else if (len < (1LL << 32)) {
char header[5];
header[0] = MP_STR32;
_msgspec_store32(&header[1], (uint32_t)len);
if (ms_write(self, header, 5) < 0)
return -1;
} else {
PyErr_SetString(
self->mod->EncodeError,
"Can't encode strings longer than 2**32 - 1"
);
return -1;
}
return len > 0 ? ms_write(self, buf, len) : 0;
}
static MS_INLINE int
mpack_encode_str(EncoderState *self, PyObject *obj)
{
Py_ssize_t len;
const char* buf = unicode_str_and_size(obj, &len);
if (buf == NULL) return -1;
return mpack_encode_cstr(self, buf, len);
}
static int
mpack_encode_bin(EncoderState *self, const char* buf, Py_ssize_t len) {
if (buf == NULL) {
return -1;
}
if (len < (1 << 8)) {
char header[2] = {MP_BIN8, (uint8_t)len};
if (ms_write(self, header, 2) < 0)
return -1;
} else if (len < (1 << 16)) {
char header[3];
header[0] = MP_BIN16;
_msgspec_store16(&header[1], (uint16_t)len);
if (ms_write(self, header, 3) < 0)
return -1;
} else if (len < (1LL << 32)) {
char header[5];
header[0] = MP_BIN32;
_msgspec_store32(&header[1], (uint32_t)len);
if (ms_write(self, header, 5) < 0)
return -1;
} else {
PyErr_SetString(
self->mod->EncodeError,
"Can't encode bytes-like objects longer than 2**32 - 1"
);
return -1;
}
return len > 0 ? ms_write(self, buf, len) : 0;
}
static int
mpack_encode_bytes(EncoderState *self, PyObject *obj)
{
Py_ssize_t len = PyBytes_GET_SIZE(obj);
const char* buf = PyBytes_AS_STRING(obj);
return mpack_encode_bin(self, buf, len);
}
static int
mpack_encode_bytearray(EncoderState *self, PyObject *obj)
{
Py_ssize_t len = PyByteArray_GET_SIZE(obj);
const char* buf = PyByteArray_AS_STRING(obj);
return mpack_encode_bin(self, buf, len);
}
static int
mpack_encode_memoryview(EncoderState *self, PyObject *obj)
{
int out;
Py_buffer buffer;
if (PyObject_GetBuffer(obj, &buffer, PyBUF_CONTIG_RO) < 0) return -1;
out = mpack_encode_bin(self, buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
return out;
}
static int
mpack_encode_raw(EncoderState *self, PyObject *obj)
{
Raw *raw = (Raw *)obj;
return ms_write(self, raw->buf, raw->len);
}
static int
mpack_encode_array_header(EncoderState *self, Py_ssize_t len, const char* typname)
{
if (len < 16) {
char header[1] = {MP_FIXARRAY | len};
if (ms_write(self, header, 1) < 0)
return -1;
} else if (len < (1 << 16)) {
char header[3];
header[0] = MP_ARRAY16;
_msgspec_store16(&header[1], (uint16_t)len);
if (ms_write(self, header, 3) < 0)
return -1;
} else if (len < (1LL << 32)) {
char header[5];
header[0] = MP_ARRAY32;
_msgspec_store32(&header[1], (uint32_t)len);
if (ms_write(self, header, 5) < 0)
return -1;
} else {
PyErr_Format(
self->mod->EncodeError,
"Can't encode %s longer than 2**32 - 1",
typname
);
return -1;
}
return 0;
}
static MS_INLINE int
mpack_encode_empty_array(EncoderState *self) {
char header[1] = {MP_FIXARRAY};
return ms_write(self, header, 1);
}
static MS_NOINLINE int
mpack_encode_list(EncoderState *self, PyObject *obj)
{
Py_ssize_t i, len;
int status = 0;
len = PyList_GET_SIZE(obj);
if (len == 0) return mpack_encode_empty_array(self);
if (mpack_encode_array_header(self, len, "list") < 0) return -1;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
for (i = 0; i < len; i++) {
if (mpack_encode_inline(self, PyList_GET_ITEM(obj, i)) < 0) {
status = -1;
break;
}
}
Py_LeaveRecursiveCall();
return status;
}
static int
mpack_encode_set(EncoderState *self, PyObject *obj)
{
Py_ssize_t len = 0;
PyObject *item;
int status = -1;
len = PySet_GET_SIZE(obj);
if (len == 0) return mpack_encode_empty_array(self);
if (MS_UNLIKELY(self->order != ORDER_DEFAULT)) {
PyObject *temp = PySequence_List(obj);
if (temp == NULL) return -1;
if (PyList_Sort(temp) == 0) {
status = mpack_encode_list(self, temp);
}
Py_DECREF(temp);
return status;
}
if (mpack_encode_array_header(self, len, "set") < 0) return -1;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
PyObject *iter = PyObject_GetIter(obj);
if (iter == NULL) goto cleanup;
while ((item = PyIter_Next(iter))) {
if (mpack_encode_inline(self, item) < 0) goto cleanup;
}
status = 0;
cleanup:
Py_LeaveRecursiveCall();
Py_XDECREF(iter);
return status;
}
static int
mpack_encode_tuple(EncoderState *self, PyObject *obj)
{
Py_ssize_t i, len;
int status = 0;
len = PyTuple_GET_SIZE(obj);
if (len == 0) return mpack_encode_empty_array(self);
if (mpack_encode_array_header(self, len, "tuples") < 0) return -1;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
for (i = 0; i < len; i++) {
if (mpack_encode_inline(self, PyTuple_GET_ITEM(obj, i)) < 0) {
status = -1;
break;
}
}
Py_LeaveRecursiveCall();
return status;
}
static int
mpack_encode_map_header(EncoderState *self, Py_ssize_t len, const char* typname)
{
if (len < 16) {
char header[1] = {MP_FIXMAP | len};
if (ms_write(self, header, 1) < 0)
return -1;
} else if (len < (1 << 16)) {
char header[3];
header[0] = MP_MAP16;
_msgspec_store16(&header[1], (uint16_t)len);
if (ms_write(self, header, 3) < 0)
return -1;
} else if (len < (1LL << 32)) {
char header[5];
header[0] = MP_MAP32;
_msgspec_store32(&header[1], (uint32_t)len);
if (ms_write(self, header, 5) < 0)
return -1;
} else {
PyErr_Format(
self->mod->EncodeError,
"Can't encode %s longer than 2**32 - 1",
typname
);
return -1;
}
return 0;
}
static int
mpack_encode_and_free_assoclist(EncoderState *self, AssocList *list) {
if (list == NULL) return -1;
int status = -1;
AssocList_Sort(list);
if (mpack_encode_map_header(self, list->size, "dicts") < 0) goto cleanup2;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
for (Py_ssize_t i = 0; i < list->size; i++) {
AssocItem *item = &(list->items[i]);
if (mpack_encode_cstr(self, item->key, item->key_size) < 0) goto cleanup;
if (mpack_encode_inline(self, item->val) < 0) goto cleanup;
}
status = 0;
cleanup:
Py_LeaveRecursiveCall();
cleanup2:
AssocList_Free(list);
return status;
}
static MS_NOINLINE int
mpack_encode_dict(EncoderState *self, PyObject *obj)
{
PyObject *key, *val;
Py_ssize_t pos = 0;
int status = -1;
Py_ssize_t len = PyDict_GET_SIZE(obj);
if (MS_UNLIKELY(len == 0)) {
char header[1] = {MP_FIXMAP};
return ms_write(self, header, 1);
}
if (MS_UNLIKELY(self->order != ORDER_DEFAULT)) {
return mpack_encode_and_free_assoclist(self, AssocList_FromDict(obj));
}
if (mpack_encode_map_header(self, len, "dicts") < 0) return -1;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
while (PyDict_Next(obj, &pos, &key, &val)) {
if (mpack_encode_dict_key_inline(self, key) < 0) goto cleanup;
if (mpack_encode_inline(self, val) < 0) goto cleanup;
}
status = 0;
cleanup:
Py_LeaveRecursiveCall();
return status;
}
static int
mpack_encode_dataclass(EncoderState *self, PyObject *obj, PyObject *fields)
{
if (MS_UNLIKELY(self->order == ORDER_SORTED)) {
return mpack_encode_and_free_assoclist(self, AssocList_FromDataclass(obj, fields));
}
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
int status = -1;
DataclassIter iter;
if (!dataclass_iter_setup(&iter, obj, fields)) goto cleanup;
/* Cache header offset in case we need to adjust the header after writing */
Py_ssize_t header_offset = self->output_len;
Py_ssize_t max_size = PyDict_GET_SIZE(fields);
if (mpack_encode_map_header(self, max_size, "objects") < 0) goto cleanup;
Py_ssize_t size = 0;
PyObject *field, *val;
while (dataclass_iter_next(&iter, &field, &val)) {
size++;
Py_ssize_t field_len;
const char* field_buf = unicode_str_and_size(field, &field_len);
bool errored = (
(field_buf == NULL) ||
(mpack_encode_cstr(self, field_buf, field_len) < 0) ||
(mpack_encode(self, val) < 0)
);
Py_DECREF(val);
if (errored) goto cleanup;
}
if (MS_UNLIKELY(size != max_size)) {
/* Some fields were skipped, need to adjust header. We write the header
* using the width type of `max_size`, but the value of `size`. */
char *header_loc = self->output_buffer_raw + header_offset;
if (max_size < 16) {
*header_loc = MP_FIXMAP | size;
} else if (max_size < (1 << 16)) {
*header_loc++ = MP_MAP16;
_msgspec_store16(header_loc, (uint16_t)size);
} else {
*header_loc++ = MP_MAP32;
_msgspec_store32(header_loc, (uint32_t)size);
}
}
status = 0;
cleanup:
Py_LeaveRecursiveCall();
dataclass_iter_cleanup(&iter);
return status;
}
/* This method encodes an object as a map, with fields taken from `__dict__`,
* followed by all `__slots__` in the class hierarchy. Any unset slots are
* ignored, and `__weakref__` is not included. */
static int
mpack_encode_object(EncoderState *self, PyObject *obj)
{
if (MS_UNLIKELY(self->order == ORDER_SORTED)) {
return mpack_encode_and_free_assoclist(self, AssocList_FromObject(obj));
}
int status = -1;
Py_ssize_t size = 0, max_size;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
/* Calculate the maximum number of fields that could be part of this object.
* This is roughly equal to:
* max_size = size = len(getattr(obj, '__dict__', {}))
* max_size += sum(len(getattr(c, '__slots__', ())) for c in type(obj).mro())
*/
PyObject *dict = PyObject_GenericGetDict(obj, NULL);
if (MS_UNLIKELY(dict == NULL)) {
PyErr_Clear();
max_size = 0;
}
else {
max_size = PyDict_GET_SIZE(dict);
}
PyTypeObject *type = Py_TYPE(obj);
while (type != NULL) {
max_size += Py_SIZE(type);
type = type->tp_base;
}
/* Cache header offset in case we need to adjust the header after writing */
Py_ssize_t header_offset = self->output_len;
if (mpack_encode_map_header(self, max_size, "objects") < 0) goto cleanup;
/* First encode everything in `__dict__` */
if (dict != NULL) {
PyObject *key, *val;
Py_ssize_t pos = 0;
while (PyDict_Next(dict, &pos, &key, &val)) {
if (MS_LIKELY(PyUnicode_CheckExact(key))) {
Py_ssize_t key_len;
if (MS_UNLIKELY(val == UNSET)) continue;
const char* key_buf = unicode_str_and_size(key, &key_len);
if (MS_UNLIKELY(key_buf == NULL)) goto cleanup;
if (MS_UNLIKELY(*key_buf == '_')) continue;
if (MS_UNLIKELY(mpack_encode_cstr(self, key_buf, key_len) < 0)) goto cleanup;
if (MS_UNLIKELY(mpack_encode(self, val) < 0)) goto cleanup;
size++;
}
}
}
/* Then encode everything in slots */
type = Py_TYPE(obj);
while (type != NULL) {
Py_ssize_t n = Py_SIZE(type);
if (n) {
PyMemberDef *mp = MS_PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
for (Py_ssize_t i = 0; i < n; i++, mp++) {
if (MS_LIKELY(mp->type == T_OBJECT_EX && !(mp->flags & READONLY))) {
char *addr = (char *)obj + mp->offset;
PyObject *val = *(PyObject **)addr;
if (MS_UNLIKELY(val == UNSET)) continue;
if (MS_UNLIKELY(val == NULL)) continue;
if (MS_UNLIKELY(*mp->name == '_')) continue;
if (MS_UNLIKELY(mpack_encode_cstr(self, mp->name, strlen(mp->name)) < 0)) goto cleanup;
if (MS_UNLIKELY(mpack_encode(self, val) < 0)) goto cleanup;
size++;
}
}
}
type = type->tp_base;
}
if (MS_UNLIKELY(size != max_size)) {
/* Some fields were NULL, need to adjust header. We write the header
* using the width type of `max_size`, but the value of `size`. */
char *header_loc = self->output_buffer_raw + header_offset;
if (max_size < 16) {
*header_loc = MP_FIXMAP | size;
} else if (max_size < (1 << 16)) {
*header_loc++ = MP_MAP16;
_msgspec_store16(header_loc, (uint16_t)size);
} else {
*header_loc++ = MP_MAP32;
_msgspec_store32(header_loc, (uint32_t)size);
}
}
status = 0;
cleanup:
Py_XDECREF(dict);
Py_LeaveRecursiveCall();
return status;
}
static int
mpack_encode_struct_array(
EncoderState *self, StructMetaObject *struct_type, PyObject *obj
) {
int status = -1;
PyObject *tag_value = struct_type->struct_tag_value;
int tagged = tag_value != NULL;
PyObject *fields = struct_type->struct_encode_fields;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
Py_ssize_t len = nfields + tagged;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
if (mpack_encode_array_header(self, len, "structs") < 0) goto cleanup;
if (tagged) {
if (mpack_encode(self, tag_value) < 0) goto cleanup;
}
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *val = Struct_get_index(obj, i);
if (val == NULL || mpack_encode(self, val) < 0) goto cleanup;
}
status = 0;
cleanup:
Py_LeaveRecursiveCall();
return status;
}
static int
mpack_encode_struct_object(
EncoderState *self, StructMetaObject *struct_type, PyObject *obj
) {
if (MS_UNLIKELY(self->order == ORDER_SORTED)) {
return mpack_encode_and_free_assoclist(self, AssocList_FromStruct(obj));
}
int status = -1;
PyObject *tag_field = struct_type->struct_tag_field;
PyObject *tag_value = struct_type->struct_tag_value;
int tagged = tag_value != NULL;
PyObject *fields = struct_type->struct_encode_fields;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
Py_ssize_t len = nfields + tagged;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
Py_ssize_t header_offset = self->output_len;
if (mpack_encode_map_header(self, len, "structs") < 0) goto cleanup;
if (tagged) {
if (mpack_encode_str(self, tag_field) < 0) goto cleanup;
if (mpack_encode(self, tag_value) < 0) goto cleanup;
}
Py_ssize_t nunchecked = nfields, actual_len = len;
if (struct_type->omit_defaults == OPT_TRUE) {
nunchecked -= PyTuple_GET_SIZE(struct_type->struct_defaults);
}
for (Py_ssize_t i = 0; i < nunchecked; i++) {
PyObject *key = PyTuple_GET_ITEM(fields, i);
PyObject *val = Struct_get_index(obj, i);
if (MS_UNLIKELY(val == NULL)) goto cleanup;
if (MS_UNLIKELY(val == UNSET)) {
actual_len--;
}
else {
if (mpack_encode_str(self, key) < 0) goto cleanup;
if (mpack_encode(self, val) < 0) goto cleanup;
}
}
for (Py_ssize_t i = nunchecked; i < nfields; i++) {
PyObject *key = PyTuple_GET_ITEM(fields, i);
PyObject *val = Struct_get_index(obj, i);
if (val == NULL) goto cleanup;
PyObject *default_val = PyTuple_GET_ITEM(
struct_type->struct_defaults, i - nunchecked
);
if (val == UNSET || is_default(val, default_val)) {
actual_len--;
}
else {
if (mpack_encode_str(self, key) < 0) goto cleanup;
if (mpack_encode(self, val) < 0) goto cleanup;
}
}
if (MS_UNLIKELY(actual_len != len)) {
/* Fixup the header length after we know how many fields were
* actually written */
char *header_loc = self->output_buffer_raw + header_offset;
if (len < 16) {
*header_loc = MP_FIXMAP | actual_len;
} else if (len < (1 << 16)) {
*header_loc++ = MP_MAP16;
_msgspec_store16(header_loc, (uint16_t)actual_len);
} else {
*header_loc++ = MP_MAP32;
_msgspec_store32(header_loc, (uint32_t)actual_len);
}
}
status = 0;
cleanup:
Py_LeaveRecursiveCall();
return status;
}
static int
mpack_encode_struct(EncoderState *self, PyObject *obj)
{
StructMetaObject *struct_type = (StructMetaObject *)Py_TYPE(obj);
if (struct_type->array_like == OPT_TRUE) {
return mpack_encode_struct_array(self, struct_type, obj);
}
return mpack_encode_struct_object(self, struct_type, obj);
}
static int
mpack_encode_ext(EncoderState *self, PyObject *obj)
{
Ext *ex = (Ext *)obj;
Py_ssize_t len;
int status = -1, header_len = 2;
char header[6];
const char* data;
Py_buffer buffer;
buffer.buf = NULL;
if (PyBytes_CheckExact(ex->data)) {
len = PyBytes_GET_SIZE(ex->data);
data = PyBytes_AS_STRING(ex->data);
}
else if (PyByteArray_CheckExact(ex->data)) {
len = PyByteArray_GET_SIZE(ex->data);
data = PyByteArray_AS_STRING(ex->data);
}
else {
if (PyObject_GetBuffer(ex->data, &buffer, PyBUF_CONTIG_RO) < 0)
return -1;
len = buffer.len;
data = buffer.buf;
}
if (len == 1) {
header[0] = MP_FIXEXT1;
header[1] = ex->code;
}
else if (len == 2) {
header[0] = MP_FIXEXT2;
header[1] = ex->code;
}
else if (len == 4) {
header[0] = MP_FIXEXT4;
header[1] = ex->code;
}
else if (len == 8) {
header[0] = MP_FIXEXT8;
header[1] = ex->code;
}
else if (len == 16) {
header[0] = MP_FIXEXT16;
header[1] = ex->code;
}
else if (len < (1<<8)) {
header[0] = MP_EXT8;
header[1] = len;
header[2] = ex->code;
header_len = 3;
}
else if (len < (1<<16)) {
header[0] = MP_EXT16;
_msgspec_store16(&header[1], (uint16_t)len);
header[3] = ex->code;
header_len = 4;
}
else if (len < (1LL<<32)) {
header[0] = MP_EXT32;
_msgspec_store32(&header[1], (uint32_t)len);
header[5] = ex->code;
header_len = 6;
}
else {
PyErr_SetString(
self->mod->EncodeError,
"Can't encode Ext objects with data longer than 2**32 - 1"
);
goto done;
}
if (ms_write(self, header, header_len) < 0)
goto done;
status = len > 0 ? ms_write(self, data, len) : 0;
done:
if (buffer.buf != NULL)
PyBuffer_Release(&buffer);
return status;
}
static int
mpack_encode_enum(EncoderState *self, PyObject *obj)
{
if (PyLong_Check(obj))
return mpack_encode_long(self, obj);
if (PyUnicode_Check(obj))
return mpack_encode_str(self, obj);
PyObject *value = PyObject_GetAttr(obj, self->mod->str__value_);
if (value == NULL) return -1;
int status = mpack_encode(self, value);
Py_DECREF(value);
return status;
}
static int
mpack_encode_uuid(EncoderState *self, PyObject *obj)
{
char buf[36];
if (MS_UNLIKELY(self->uuid_format == UUID_FORMAT_BYTES)) {
if (ms_uuid_to_16_bytes(self->mod, obj, (unsigned char *)buf) < 0) return -1;
return mpack_encode_bin(self, buf, 16);
}
bool canonical = self->uuid_format == UUID_FORMAT_CANONICAL;
if (ms_encode_uuid(self->mod, obj, buf, canonical) < 0) return -1;
return mpack_encode_cstr(self, buf, canonical ? 36 : 32);
}
static int
mpack_encode_decimal(EncoderState *self, PyObject *obj)
{
PyObject *temp;
int out;
if (MS_LIKELY(self->decimal_format == DECIMAL_FORMAT_STRING)) {
temp = PyObject_Str(obj);
if (temp == NULL) return -1;
out = mpack_encode_str(self, temp);
}
else {
temp = PyNumber_Float(obj);
if (temp == NULL) return -1;
out = mpack_encode_float(self, temp);
}
Py_DECREF(temp);
return out;
}
static int
mpack_encode_date(EncoderState *self, PyObject *obj)
{
char buf[10];
ms_encode_date(obj, buf);
return mpack_encode_cstr(self, buf, 10);
}
static int
mpack_encode_time(EncoderState *self, PyObject *obj)
{
char buf[21];
int size = ms_encode_time(self->mod, obj, buf);
if (size < 0) return -1;
return mpack_encode_cstr(self, buf, size);
}
static int
mpack_encode_timedelta(EncoderState *self, PyObject *obj)
{
char buf[26];
int size = ms_encode_timedelta(obj, buf);
return mpack_encode_cstr(self, buf, size);
}
static int
mpack_encode_datetime(EncoderState *self, PyObject *obj)
{
int64_t seconds;
int32_t nanoseconds;
PyObject *tzinfo = MS_DATE_GET_TZINFO(obj);
if (tzinfo == Py_None) {
char buf[32];
int size = ms_encode_datetime(self->mod, obj, buf);
if (size < 0) return -1;
return mpack_encode_cstr(self, buf, size);
}
if (tzinfo == PyDateTime_TimeZone_UTC) {
datetime_to_epoch(obj, &seconds, &nanoseconds);
}
else {
PyObject *temp = PyObject_CallFunctionObjArgs(
self->mod->astimezone,
obj, PyDateTime_TimeZone_UTC, NULL
);
if (temp == NULL) return -1;
datetime_to_epoch(temp, &seconds, &nanoseconds);
Py_DECREF(temp);
}
if ((seconds >> 34) == 0) {
uint64_t data64 = ((uint64_t)nanoseconds << 34) | (uint64_t)seconds;
if ((data64 & 0xffffffff00000000L) == 0) {
/* timestamp 32 */
char buf[6];
buf[0] = MP_FIXEXT4;
buf[1] = -1;
uint32_t data32 = (uint32_t)data64;
_msgspec_store32(&buf[2], data32);
if (ms_write(self, buf, 6) < 0) return -1;
} else {
/* timestamp 64 */
char buf[10];
buf[0] = MP_FIXEXT8;
buf[1] = -1;
_msgspec_store64(&buf[2], data64);
if (ms_write(self, buf, 10) < 0) return -1;
}
} else {
/* timestamp 96 */
char buf[15];
buf[0] = MP_EXT8;
buf[1] = 12;
buf[2] = -1;
_msgspec_store32(&buf[3], nanoseconds);
_msgspec_store64(&buf[7], seconds);
if (ms_write(self, buf, 15) < 0) return -1;
}
return 0;
}
static MS_NOINLINE int
mpack_encode_uncommon(EncoderState *self, PyTypeObject *type, PyObject *obj)
{
if (obj == Py_None) {
return mpack_encode_none(self);
}
else if (type == &PyBool_Type) {
return mpack_encode_bool(self, obj);
}
else if (Py_TYPE(type) == &StructMetaType) {
return mpack_encode_struct(self, obj);
}
else if (type == &PyBytes_Type) {
return mpack_encode_bytes(self, obj);
}
else if (type == &PyByteArray_Type) {
return mpack_encode_bytearray(self, obj);
}
else if (type == &PyMemoryView_Type) {
return mpack_encode_memoryview(self, obj);
}
else if (PyTuple_Check(obj)) {
return mpack_encode_tuple(self, obj);
}
else if (type == PyDateTimeAPI->DateTimeType) {
return mpack_encode_datetime(self, obj);
}
else if (type == PyDateTimeAPI->DateType) {
return mpack_encode_date(self, obj);
}
else if (type == PyDateTimeAPI->TimeType) {
return mpack_encode_time(self, obj);
}
else if (type == PyDateTimeAPI->DeltaType) {
return mpack_encode_timedelta(self, obj);
}
else if (type == &Ext_Type) {
return mpack_encode_ext(self, obj);
}
else if (type == &Raw_Type) {
return mpack_encode_raw(self, obj);
}
else if (Py_TYPE(type) == self->mod->EnumMetaType) {
return mpack_encode_enum(self, obj);
}
else if (type == (PyTypeObject *)(self->mod->DecimalType)) {
return mpack_encode_decimal(self, obj);
}
else if (PyType_IsSubtype(type, (PyTypeObject *)(self->mod->UUIDType))) {
return mpack_encode_uuid(self, obj);
}
else if (PyAnySet_Check(obj)) {
return mpack_encode_set(self, obj);
}
else if (!PyType_Check(obj) && type->tp_dict != NULL) {
PyObject *fields = PyObject_GetAttr(obj, self->mod->str___dataclass_fields__);
if (fields != NULL) {
int status = mpack_encode_dataclass(self, obj, fields);
Py_DECREF(fields);
return status;
}
else {
PyErr_Clear();
}
if (PyDict_Contains(type->tp_dict, self->mod->str___attrs_attrs__)) {
return mpack_encode_object(self, obj);
}
}
if (self->enc_hook != NULL) {
int status = -1;
PyObject *temp;
temp = PyObject_CallOneArg(self->enc_hook, obj);
if (temp == NULL) return -1;
if (!Py_EnterRecursiveCall(" while serializing an object")) {
status = mpack_encode(self, temp);
Py_LeaveRecursiveCall();
}
Py_DECREF(temp);
return status;
}
return ms_encode_err_type_unsupported(type);
}
static MS_INLINE int
mpack_encode_inline(EncoderState *self, PyObject *obj)
{
PyTypeObject *type = Py_TYPE(obj);
if (type == &PyUnicode_Type) {
return mpack_encode_str(self, obj);
}
else if (type == &PyLong_Type) {
return mpack_encode_long(self, obj);
}
else if (type == &PyFloat_Type) {
return mpack_encode_float(self, obj);
}
else if (PyList_Check(obj)) {
return mpack_encode_list(self, obj);
}
else if (PyDict_Check(obj)) {
return mpack_encode_dict(self, obj);
}
else {
return mpack_encode_uncommon(self, type, obj);
}
}
static MS_INLINE int
mpack_encode_dict_key_inline(EncoderState *self, PyObject *obj)
{
PyTypeObject *type = Py_TYPE(obj);
if (PyUnicode_Check(obj)) {
return mpack_encode_str(self, obj);
}
else if (type == &PyLong_Type) {
return mpack_encode_long(self, obj);
}
else if (type == &PyFloat_Type) {
return mpack_encode_float(self, obj);
}
else if (PyList_Check(obj)) {
return mpack_encode_list(self, obj);
}
else if (PyDict_Check(obj)) {
return mpack_encode_dict(self, obj);
}
else {
return mpack_encode_uncommon(self, type, obj);
}
}
static int
mpack_encode(EncoderState *self, PyObject *obj) {
return mpack_encode_inline(self, obj);
}
static PyObject*
Encoder_encode_into(Encoder *self, PyObject *const *args, Py_ssize_t nargs)
{
return encoder_encode_into_common(self, args, nargs, &mpack_encode);
}
static PyObject*
Encoder_encode(Encoder *self, PyObject *const *args, Py_ssize_t nargs)
{
return encoder_encode_common(self, args, nargs, &mpack_encode);
}
static struct PyMethodDef Encoder_methods[] = {
{
"encode", (PyCFunction) Encoder_encode, METH_FASTCALL,
Encoder_encode__doc__,
},
{
"encode_into", (PyCFunction) Encoder_encode_into, METH_FASTCALL,
Encoder_encode_into__doc__,
},
{NULL, NULL} /* sentinel */
};
static PyTypeObject Encoder_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec.msgpack.Encoder",
.tp_doc = Encoder__doc__,
.tp_basicsize = sizeof(Encoder),
.tp_dealloc = (destructor)Encoder_dealloc,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_traverse = (traverseproc)Encoder_traverse,
.tp_clear = (inquiry)Encoder_clear,
.tp_new = PyType_GenericNew,
.tp_init = (initproc)Encoder_init,
.tp_methods = Encoder_methods,
.tp_members = Encoder_members,
.tp_getset = Encoder_getset,
};
PyDoc_STRVAR(msgspec_msgpack_encode__doc__,
"msgpack_encode(obj, *, enc_hook=None, order=None)\n"
"--\n"
"\n"
"Serialize an object as MessagePack.\n"
"\n"
"Parameters\n"
"----------\n"
"obj : Any\n"
" The object to serialize.\n"
"enc_hook : callable, optional\n"
" A callable to call for objects that aren't supported msgspec types. Takes\n"
" the unsupported object and should return a supported object, or raise a\n"
" ``NotImplementedError`` if unsupported.\n"
"order : {None, 'deterministic', 'sorted'}, optional\n"
" The ordering to use when encoding unordered compound types.\n"
"\n"
" - ``None``: All objects are encoded in the most efficient manner matching\n"
" their in-memory representations. The default.\n"
" - `'deterministic'`: Unordered collections (sets, dicts) are sorted to\n"
" ensure a consistent output between runs. Useful when comparison/hashing\n"
" of the encoded binary output is necessary.\n"
" - `'sorted'`: Like `'deterministic'`, but *all* object-like types (structs,\n"
" dataclasses, ...) are also sorted by field name before encoding. This is\n"
" slower than `'deterministic'`, but may produce more human-readable output.\n"
"\n"
"Returns\n"
"-------\n"
"data : bytes\n"
" The serialized object.\n"
"\n"
"See Also\n"
"--------\n"
"Encoder.encode"
);
static PyObject*
msgspec_msgpack_encode(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
return encode_common(self, args, nargs, kwnames, &mpack_encode);
}
/*************************************************************************
* JSON Encoder *
*************************************************************************/
PyDoc_STRVAR(JSONEncoder__doc__,
"Encoder(*, enc_hook=None, decimal_format='string', uuid_format='canonical', order=None)\n"
"--\n"
"\n"
"A JSON encoder.\n"
"\n"
"Parameters\n"
"----------\n"
"enc_hook : callable, optional\n"
" A callable to call for objects that aren't supported msgspec types. Takes\n"
" the unsupported object and should return a supported object, or raise a\n"
" ``NotImplementedError`` if unsupported.\n"
"decimal_format : {'string', 'number'}, optional\n"
" The format to use for encoding `decimal.Decimal` objects. If 'string'\n"
" they're encoded as strings, if 'number', they're encoded as floats.\n"
" Defaults to 'string', which is the recommended value since 'number'\n"
" may result in precision loss when decoding for some JSON library\n"
" implementations.\n"
"uuid_format : {'canonical', 'hex'}, optional\n"
" The format to use for encoding `uuid.UUID` objects. The 'canonical'\n"
" and 'hex' formats encode them as strings with and without hyphens\n"
" respectively. Defaults to 'canonical'.\n"
"order : {None, 'deterministic', 'sorted'}, optional\n"
" The ordering to use when encoding unordered compound types.\n"
"\n"
" - ``None``: All objects are encoded in the most efficient manner matching\n"
" their in-memory representations. The default.\n"
" - `'deterministic'`: Unordered collections (sets, dicts) are sorted to\n"
" ensure a consistent output between runs. Useful when comparison/hashing\n"
" of the encoded binary output is necessary.\n"
" - `'sorted'`: Like `'deterministic'`, but *all* object-like types (structs,\n"
" dataclasses, ...) are also sorted by field name before encoding. This is\n"
" slower than `'deterministic'`, but may produce more human-readable output."
);
static int json_encode_inline(EncoderState*, PyObject*);
static int json_encode(EncoderState*, PyObject*);
static MS_NOINLINE int
json_encode_long_fallback(EncoderState *self, PyObject *obj) {
int out = -1;
PyObject *encoded = PyLong_Type.tp_repr(obj);
if (MS_LIKELY(encoded != NULL)) {
Py_ssize_t len;
const char* buf = unicode_str_and_size(encoded, &len);
if (MS_LIKELY(buf != NULL)) {
out = ms_write(self, buf, len);
}
Py_DECREF(encoded);
}
return out;
}
static MS_NOINLINE int
json_encode_long(EncoderState *self, PyObject *obj) {
uint64_t x;
bool neg, overflow;
overflow = fast_long_extract_parts(obj, &neg, &x);
if (MS_UNLIKELY(overflow)) {
return json_encode_long_fallback(self, obj);
}
if (ms_ensure_space(self, 20) < 0) return -1;
char *p = self->output_buffer_raw + self->output_len;
if (neg) {
*p++ = '-';
}
self->output_len = write_u64(x, p) - self->output_buffer_raw;
return 0;
}
static int
json_encode_long_as_str(EncoderState *self, PyObject *obj) {
if (ms_write(self, "\"", 1) < 0) return -1;
if (json_encode_long(self, obj) < 0) return -1;
return ms_write(self, "\"", 1);
}
static MS_NOINLINE int
json_encode_float(EncoderState *self, PyObject *obj) {
double x = PyFloat_AS_DOUBLE(obj);
if (ms_ensure_space(self, 24) < 0) return -1;
char *p = self->output_buffer_raw + self->output_len;
self->output_len += write_f64(x, p, false);
return 0;
}
static MS_NOINLINE int
json_encode_float_as_str(EncoderState *self, PyObject *obj) {
double x = PyFloat_AS_DOUBLE(obj);
if (ms_ensure_space(self, 26) < 0) return -1;
char *p = self->output_buffer_raw + self->output_len;
*p = '"';
int n = write_f64(x, p + 1, true);
*(p + 1 + n) = '"';
self->output_len += n + 2;
return 0;
}
/* A table of escape characters to use for each byte (0 if no escape needed) */
static const char escape_table[256] = {
'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u',
'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u',
0, 0, '"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '\\', 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
static int
json_str_requires_escaping(PyObject *obj) {
Py_ssize_t i, len;
const char* buf = unicode_str_and_size(obj, &len);
if (buf == NULL) return -1;
for (i = 0; i < len; i++) {
char escape = escape_table[(uint8_t)buf[i]];
if (escape != 0) {
return 1;
}
}
return 0;
}
static MS_INLINE int
json_encode_cstr_inline(EncoderState *self, const char *src, Py_ssize_t len) {
const char* src_end = src + len;
if (ms_ensure_space(self, len + 2) < 0) return -1;
char *out = self->output_buffer_raw + self->output_len;
char *out_end = self->output_buffer_raw + self->max_output_len;
*out++ = '"';
noescape:
#define write_ascii_pre(i) \
if (MS_UNLIKELY(escape_table[(uint8_t)src[i]])) goto write_ascii_##i;
#define write_ascii_post(i) \
write_ascii_##i: \
memcpy(out, src, i); \
out += i; \
src += i; \
goto escape;
while (src_end - src >= 8) {
repeat8(write_ascii_pre);
memcpy(out, src, 8);
out += 8;
src += 8;
}
while (MS_LIKELY(src_end > src)) {
write_ascii_pre(0);
*out++ = *src++;
}
*out++ = '"';
self->output_len = out - self->output_buffer_raw;
return 0;
repeat8(write_ascii_post);
escape:
{
char c = *src++;
char escape = escape_table[(uint8_t)c];
/* Ensure enough space for the escape, final quote, and any remaining characters */
Py_ssize_t remaining = 7 + src_end - src;
if (MS_UNLIKELY(remaining > out_end - out)) {
Py_ssize_t output_len = out - self->output_buffer_raw;
if (MS_UNLIKELY(ms_resize(self, remaining + output_len) < 0)) return -1;
out = self->output_buffer_raw + output_len;
out_end = self->output_buffer_raw + self->max_output_len;
}
/* Write the escaped character */
char escaped[6] = {'\\', escape, '0', '0'};
if (MS_UNLIKELY(escape == 'u')) {
escaped[4] = hex_encode_table[c >> 4];
escaped[5] = hex_encode_table[c & 0xF];
memcpy(out, escaped, 6);
out += 6;
}
else {
memcpy(out, escaped, 2);
out += 2;
}
goto noescape;
}
}
static int
json_encode_cstr(EncoderState *self, const char *src, Py_ssize_t len) {
return json_encode_cstr_inline(self, src, len);
}
static MS_NOINLINE int
json_encode_str(EncoderState *self, PyObject *obj) {
Py_ssize_t len;
const char* buf = unicode_str_and_size(obj, &len);
if (buf == NULL) return -1;
return json_encode_cstr_inline(self, buf, len);
}
static MS_INLINE int
json_encode_cstr_noescape(EncoderState *self, const char *str, Py_ssize_t size) {
if (ms_ensure_space(self, size + 2) < 0) return -1;
char *p = self->output_buffer_raw + self->output_len;
*p++ = '"';
memcpy(p, str, size);
*(p + size) = '"';
self->output_len += size + 2;
return 0;
}
static inline int
json_encode_str_noescape(EncoderState *self, PyObject *obj) {
Py_ssize_t len;
const char* buf = unicode_str_and_size_nocheck(obj, &len);
return json_encode_cstr_noescape(self, buf, len);
}
static int
json_encode_bin(EncoderState *self, const char* buf, Py_ssize_t len) {
/* Preallocate the buffer (ceil(4/3 * len) + 2) */
Py_ssize_t encoded_len = ms_encode_base64_size(self->mod, len);
if (encoded_len < 0) return -1;
if (ms_ensure_space(self, encoded_len + 2) < 0) return -1;
/* Write to the buffer directly */
char *out = self->output_buffer_raw + self->output_len;
*out++ = '"';
ms_encode_base64(buf, len, out);
out += encoded_len;
*out++ = '"';
self->output_len += encoded_len + 2;
return 0;
}
static int
json_encode_bytes(EncoderState *self, PyObject *obj)
{
Py_ssize_t len = PyBytes_GET_SIZE(obj);
const char* buf = PyBytes_AS_STRING(obj);
return json_encode_bin(self, buf, len);
}
static int
json_encode_bytearray(EncoderState *self, PyObject *obj)
{
Py_ssize_t len = PyByteArray_GET_SIZE(obj);
const char* buf = PyByteArray_AS_STRING(obj);
return json_encode_bin(self, buf, len);
}
static int
json_encode_memoryview(EncoderState *self, PyObject *obj)
{
int out;
Py_buffer buffer;
if (PyObject_GetBuffer(obj, &buffer, PyBUF_CONTIG_RO) < 0) return -1;
out = json_encode_bin(self, buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
return out;
}
static int
json_encode_raw(EncoderState *self, PyObject *obj)
{
Raw *raw = (Raw *)obj;
return ms_write(self, raw->buf, raw->len);
}
static int json_encode_dict_key_noinline(EncoderState *, PyObject *);
static int
json_encode_enum(EncoderState *self, PyObject *obj, bool is_key)
{
if (PyLong_Check(obj)) {
return is_key ? json_encode_long_as_str(self, obj) : json_encode_long(self, obj);
}
if (PyUnicode_Check(obj)) {
return json_encode_str(self, obj);
}
PyObject *value = PyObject_GetAttr(obj, self->mod->str__value_);
if (value == NULL) return -1;
int status = (
is_key ? json_encode_dict_key_noinline(self, value) : json_encode(self, value)
);
Py_DECREF(value);
return status;
}
static int
json_encode_uuid(EncoderState *self, PyObject *obj)
{
char buf[38];
buf[0] = '"';
bool canonical = self->uuid_format == UUID_FORMAT_CANONICAL;
if (ms_encode_uuid(self->mod, obj, buf + 1, canonical) < 0) return -1;
int size = canonical ? 36 : 32;
buf[size + 1] = '"';
return ms_write(self, buf, size + 2);
}
static int
json_encode_decimal(EncoderState *self, PyObject *obj)
{
PyObject *temp = PyObject_Str(obj);
if (temp == NULL) return -1;
Py_ssize_t size;
const char* buf = unicode_str_and_size_nocheck(temp, &size);
bool decimal_as_string = (self->decimal_format == DECIMAL_FORMAT_STRING);
Py_ssize_t required = size + (2 * decimal_as_string);
if (ms_ensure_space(self, size + 2) < 0) {
Py_DECREF(temp);
return -1;
}
char *p = self->output_buffer_raw + self->output_len;
if (MS_LIKELY(decimal_as_string)) *p++ = '"';
memcpy(p, buf, size);
if (MS_LIKELY(decimal_as_string)) *(p + size) = '"';
self->output_len += required;
Py_DECREF(temp);
return 0;
}
static int
json_encode_date(EncoderState *self, PyObject *obj)
{
if (ms_ensure_space(self, 12) < 0) return -1;
char *p = self->output_buffer_raw + self->output_len;
*p = '"';
ms_encode_date(obj, p + 1);
*(p + 11) = '"';
self->output_len += 12;
return 0;
}
static int
json_encode_time(EncoderState *self, PyObject *obj)
{
if (ms_ensure_space(self, 23) < 0) return -1;
char *p = self->output_buffer_raw + self->output_len;
*p = '"';
int size = ms_encode_time(self->mod, obj, p + 1);
if (size < 0) return -1;
*(p + size + 1) = '"';
self->output_len += (size + 2);
return 0;
}
static int
json_encode_datetime(EncoderState *self, PyObject *obj)
{
if (ms_ensure_space(self, 34) < 0) return -1;
char *p = self->output_buffer_raw + self->output_len;
*p = '"';
int size = ms_encode_datetime(self->mod, obj, p + 1);
if (size < 0) return -1;
*(p + size + 1) = '"';
self->output_len += (size + 2);
return 0;
}
static int
json_encode_timedelta(EncoderState *self, PyObject *obj)
{
char buf[28];
buf[0] = '"';
int n = ms_encode_timedelta(obj, buf + 1);
buf[1 + n] = '"';
return ms_write(self, buf, 2 + n);
}
static MS_INLINE int
json_encode_sequence(EncoderState *self, Py_ssize_t size, PyObject **arr)
{
int status = -1;
if (size == 0) return ms_write(self, "[]", 2);
if (ms_write(self, "[", 1) < 0) return -1;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
for (Py_ssize_t i = 0; i < size; i++) {
if (json_encode_inline(self, *(arr + i)) < 0) goto cleanup;
if (ms_write(self, ",", 1) < 0) goto cleanup;
}
/* Overwrite trailing comma with ] */
*(self->output_buffer_raw + self->output_len - 1) = ']';
status = 0;
cleanup:
Py_LeaveRecursiveCall();
return status;
}
static MS_NOINLINE int
json_encode_list(EncoderState *self, PyObject *obj)
{
return json_encode_sequence(
self, PyList_GET_SIZE(obj), ((PyListObject *)obj)->ob_item
);
}
static MS_NOINLINE int
json_encode_tuple(EncoderState *self, PyObject *obj)
{
return json_encode_sequence(
self, PyTuple_GET_SIZE(obj), ((PyTupleObject *)obj)->ob_item
);
}
static int
json_encode_set(EncoderState *self, PyObject *obj)
{
Py_ssize_t len = 0;
PyObject *item;
int status = -1;
len = PySet_GET_SIZE(obj);
if (len == 0) return ms_write(self, "[]", 2);
if (MS_UNLIKELY(self->order != ORDER_DEFAULT)) {
PyObject *temp = PySequence_List(obj);
if (temp == NULL) return -1;
if (PyList_Sort(temp) == 0) {
status = json_encode_list(self, temp);
}
Py_DECREF(temp);
return status;
}
if (ms_write(self, "[", 1) < 0) return -1;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
PyObject *iter = PyObject_GetIter(obj);
if (iter == NULL) goto cleanup;
while ((item = PyIter_Next(iter))) {
if (json_encode_inline(self, item) < 0) goto cleanup;
if (ms_write(self, ",", 1) < 0) goto cleanup;
}
/* Overwrite trailing comma with ] */
*(self->output_buffer_raw + self->output_len - 1) = ']';
status = 0;
cleanup:
Py_LeaveRecursiveCall();
Py_XDECREF(iter);
return status;
}
static MS_INLINE int
json_encode_dict_key(EncoderState *self, PyObject *key) {
if (MS_LIKELY(PyUnicode_Check(key))) {
return json_encode_str(self, key);
}
return json_encode_dict_key_noinline(self, key);
}
static MS_NOINLINE int
json_encode_dict_key_noinline(EncoderState *self, PyObject *obj) {
PyTypeObject *type = Py_TYPE(obj);
if (type == &PyLong_Type) {
return json_encode_long_as_str(self, obj);
}
else if (type == &PyFloat_Type) {
return json_encode_float_as_str(self, obj);
}
else if (Py_TYPE(type) == self->mod->EnumMetaType) {
return json_encode_enum(self, obj, true);
}
else if (type == PyDateTimeAPI->DateTimeType) {
return json_encode_datetime(self, obj);
}
else if (type == PyDateTimeAPI->DateType) {
return json_encode_date(self, obj);
}
else if (type == PyDateTimeAPI->TimeType) {
return json_encode_time(self, obj);
}
else if (type == PyDateTimeAPI->DeltaType) {
return json_encode_timedelta(self, obj);
}
else if (type == &PyBytes_Type) {
return json_encode_bytes(self, obj);
}
else if (type == (PyTypeObject *)(self->mod->DecimalType)) {
return json_encode_decimal(self, obj);
}
else if (PyType_IsSubtype(type, (PyTypeObject *)(self->mod->UUIDType))) {
return json_encode_uuid(self, obj);
}
else if (self->enc_hook != NULL) {
int status = -1;
PyObject *temp;
temp = PyObject_CallOneArg(self->enc_hook, obj);
if (temp == NULL) return -1;
if (!Py_EnterRecursiveCall(" while serializing an object")) {
status = json_encode_dict_key(self, temp);
Py_LeaveRecursiveCall();
}
Py_DECREF(temp);
return status;
}
else {
PyErr_SetString(
PyExc_TypeError,
"Only dicts with str-like or number-like keys are supported"
);
return -1;
}
}
static int
json_encode_and_free_assoclist(EncoderState *self, AssocList *list, bool escape) {
if (list == NULL) return -1;
int status = -1;
AssocList_Sort(list);
if (Py_EnterRecursiveCall(" while serializing an object")) goto cleanup2;
if (ms_write(self, "{", 1) < 0) goto cleanup;
Py_ssize_t start_len = self->output_len;
if (escape) {
for (Py_ssize_t i = 0; i < list->size; i++) {
AssocItem *item = &(list->items[i]);
if (json_encode_cstr(self, item->key, item->key_size) < 0) goto cleanup;
if (ms_write(self, ":", 1) < 0) goto cleanup;
if (json_encode_inline(self, item->val) < 0) goto cleanup;
if (ms_write(self, ",", 1) < 0) goto cleanup;
}
}
else {
for (Py_ssize_t i = 0; i < list->size; i++) {
AssocItem *item = &(list->items[i]);
if (json_encode_cstr_noescape(self, item->key, item->key_size) < 0) goto cleanup;
if (ms_write(self, ":", 1) < 0) goto cleanup;
if (json_encode_inline(self, item->val) < 0) goto cleanup;
if (ms_write(self, ",", 1) < 0) goto cleanup;
}
}
if (MS_UNLIKELY(start_len == self->output_len)) {
/* Empty, append "}" */
if (ms_write(self, "}", 1) < 0) goto cleanup;
}
else {
/* Overwrite trailing comma with } */
*(self->output_buffer_raw + self->output_len - 1) = '}';
}
status = 0;
cleanup:
Py_LeaveRecursiveCall();
cleanup2:
AssocList_Free(list);
return status;
}
static MS_NOINLINE int
json_encode_dict(EncoderState *self, PyObject *obj)
{
PyObject *key, *val;
Py_ssize_t len, pos = 0;
int status = -1;
len = PyDict_GET_SIZE(obj);
if (len == 0) return ms_write(self, "{}", 2);
if (MS_UNLIKELY(self->order != ORDER_DEFAULT)) {
return json_encode_and_free_assoclist(self, AssocList_FromDict(obj), true);
}
if (ms_write(self, "{", 1) < 0) return -1;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
while (PyDict_Next(obj, &pos, &key, &val)) {
if (json_encode_dict_key(self, key) < 0) goto cleanup;
if (ms_write(self, ":", 1) < 0) goto cleanup;
if (json_encode_inline(self, val) < 0) goto cleanup;
if (ms_write(self, ",", 1) < 0) goto cleanup;
}
/* Overwrite trailing comma with } */
*(self->output_buffer_raw + self->output_len - 1) = '}';
status = 0;
cleanup:
Py_LeaveRecursiveCall();
return status;
}
static int
json_encode_dataclass(EncoderState *self, PyObject *obj, PyObject *fields)
{
if (MS_UNLIKELY(self->order == ORDER_SORTED)) {
return json_encode_and_free_assoclist(
self, AssocList_FromDataclass(obj, fields), false
);
}
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
int status = -1;
DataclassIter iter;
if (!dataclass_iter_setup(&iter, obj, fields)) goto cleanup;
if (ms_write(self, "{", 1) < 0) goto cleanup;
Py_ssize_t start_offset = self->output_len;
PyObject *field, *val;
while (dataclass_iter_next(&iter, &field, &val)) {
Py_ssize_t field_len;
const char* field_buf = unicode_str_and_size(field, &field_len);
bool errored = (
(field_buf == NULL) ||
(json_encode_cstr_noescape(self, field_buf, field_len) < 0) ||
(ms_write(self, ":", 1) < 0) ||
(json_encode(self, val) < 0) ||
(ms_write(self, ",", 1) < 0)
);
Py_DECREF(val);
if (errored) goto cleanup;
}
/* If any fields written, overwrite trailing comma with }, otherwise append } */
if (MS_LIKELY(self->output_len != start_offset)) {
*(self->output_buffer_raw + self->output_len - 1) = '}';
status = 0;
}
else {
status = ms_write(self, "}", 1);
}
cleanup:
Py_LeaveRecursiveCall();
dataclass_iter_cleanup(&iter);
return status;
}
/* This method encodes an object as a map, with fields taken from `__dict__`,
* followed by all `__slots__` in the class hierarchy. Any unset slots are
* ignored, and `__weakref__` is not included. */
static int
json_encode_object(EncoderState *self, PyObject *obj)
{
if (MS_UNLIKELY(self->order == ORDER_SORTED)) {
return json_encode_and_free_assoclist(self, AssocList_FromObject(obj), false);
}
int status = -1;
if (ms_write(self, "{", 1) < 0) return -1;
Py_ssize_t start_offset = self->output_len;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
/* First encode everything in `__dict__` */
PyObject *dict = PyObject_GenericGetDict(obj, NULL);
if (MS_UNLIKELY(dict == NULL)) {
PyErr_Clear();
}
else {
PyObject *key, *val;
Py_ssize_t pos = 0;
while (PyDict_Next(dict, &pos, &key, &val)) {
if (MS_LIKELY(PyUnicode_CheckExact(key))) {
Py_ssize_t key_len;
const char* key_buf = unicode_str_and_size(key, &key_len);
if (MS_UNLIKELY(val == UNSET)) continue;
if (MS_UNLIKELY(key_buf == NULL)) goto cleanup;
if (MS_UNLIKELY(*key_buf == '_')) continue;
if (MS_UNLIKELY(json_encode_cstr_noescape(self, key_buf, key_len) < 0)) goto cleanup;
if (MS_UNLIKELY(ms_write(self, ":", 1) < 0)) goto cleanup;
if (MS_UNLIKELY(json_encode(self, val) < 0)) goto cleanup;
if (MS_UNLIKELY(ms_write(self, ",", 1) < 0)) goto cleanup;
}
}
}
/* Then encode everything in slots */
PyTypeObject *type = Py_TYPE(obj);
while (type != NULL) {
Py_ssize_t n = Py_SIZE(type);
if (n) {
PyMemberDef *mp = MS_PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
for (Py_ssize_t i = 0; i < n; i++, mp++) {
if (MS_LIKELY(mp->type == T_OBJECT_EX && !(mp->flags & READONLY))) {
char *addr = (char *)obj + mp->offset;
PyObject *val = *(PyObject **)addr;
if (MS_UNLIKELY(val == NULL)) continue;
if (MS_UNLIKELY(val == UNSET)) continue;
if (MS_UNLIKELY(*mp->name == '_')) continue;
if (MS_UNLIKELY(json_encode_cstr_noescape(self, mp->name, strlen(mp->name)) < 0)) goto cleanup;
if (MS_UNLIKELY(ms_write(self, ":", 1) < 0)) goto cleanup;
if (MS_UNLIKELY(json_encode(self, val) < 0)) goto cleanup;
if (MS_UNLIKELY(ms_write(self, ",", 1) < 0)) goto cleanup;
}
}
}
type = type->tp_base;
}
/* If any fields written, overwrite trailing comma with }, otherwise append } */
if (MS_LIKELY(self->output_len != start_offset)) {
*(self->output_buffer_raw + self->output_len - 1) = '}';
status = 0;
}
else {
status = ms_write(self, "}", 1);
}
cleanup:
Py_XDECREF(dict);
Py_LeaveRecursiveCall();
return status;
}
static int
json_encode_struct_tag(EncoderState *self, PyObject *obj)
{
PyTypeObject *type = Py_TYPE(obj);
if (type == &PyUnicode_Type) {
return json_encode_str(self, obj);
}
else {
return json_encode_long(self, obj);
}
}
static int
json_encode_struct_object(
EncoderState *self, StructMetaObject *struct_type, PyObject *obj
) {
if (MS_UNLIKELY(self->order == ORDER_SORTED)) {
return json_encode_and_free_assoclist(self, AssocList_FromStruct(obj), false);
}
PyObject *key, *val, *fields, *defaults, *tag_field, *tag_value;
Py_ssize_t i, nfields, nunchecked;
int status = -1;
tag_field = struct_type->struct_tag_field;
tag_value = struct_type->struct_tag_value;
fields = struct_type->struct_encode_fields;
defaults = struct_type->struct_defaults;
nfields = PyTuple_GET_SIZE(fields);
nunchecked = nfields;
if (struct_type->omit_defaults == OPT_TRUE) {
nunchecked -= PyTuple_GET_SIZE(defaults);
}
if (ms_write(self, "{", 1) < 0) return -1;
Py_ssize_t start_len = self->output_len;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
if (tag_value != NULL) {
if (json_encode_str(self, tag_field) < 0) goto cleanup;
if (ms_write(self, ":", 1) < 0) goto cleanup;
if (json_encode_struct_tag(self, tag_value) < 0) goto cleanup;
if (ms_write(self, ",", 1) < 0) goto cleanup;
}
for (i = 0; i < nunchecked; i++) {
key = PyTuple_GET_ITEM(fields, i);
val = Struct_get_index(obj, i);
if (MS_UNLIKELY(val == NULL)) goto cleanup;
if (MS_UNLIKELY(val == UNSET)) continue;
if (json_encode_str_noescape(self, key) < 0) goto cleanup;
if (ms_write(self, ":", 1) < 0) goto cleanup;
if (json_encode(self, val) < 0) goto cleanup;
if (ms_write(self, ",", 1) < 0) goto cleanup;
}
for (i = nunchecked; i < nfields; i++) {
key = PyTuple_GET_ITEM(fields, i);
val = Struct_get_index(obj, i);
if (MS_UNLIKELY(val == NULL)) goto cleanup;
if (MS_UNLIKELY(val == UNSET)) continue;
PyObject *default_val = PyTuple_GET_ITEM(defaults, i - nunchecked);
if (!is_default(val, default_val)) {
if (json_encode_str_noescape(self, key) < 0) goto cleanup;
if (ms_write(self, ":", 1) < 0) goto cleanup;
if (json_encode(self, val) < 0) goto cleanup;
if (ms_write(self, ",", 1) < 0) goto cleanup;
}
}
if (MS_UNLIKELY(start_len == self->output_len)) {
/* Empty struct, append "}" */
if (ms_write(self, "}", 1) < 0) goto cleanup;
}
else {
/* Overwrite trailing comma with } */
*(self->output_buffer_raw + self->output_len - 1) = '}';
}
status = 0;
cleanup:
Py_LeaveRecursiveCall();
return status;
}
static int
json_encode_struct_array(
EncoderState *self, StructMetaObject *struct_type, PyObject *obj
) {
int status = -1;
PyObject *tag_value = struct_type->struct_tag_value;
PyObject *fields = struct_type->struct_encode_fields;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
if (nfields == 0 && tag_value == NULL) return ms_write(self, "[]", 2);
if (ms_write(self, "[", 1) < 0) return -1;
if (Py_EnterRecursiveCall(" while serializing an object")) return -1;
if (tag_value != NULL) {
if (json_encode_struct_tag(self, tag_value) < 0) goto cleanup;
if (ms_write(self, ",", 1) < 0) goto cleanup;
}
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *val = Struct_get_index(obj, i);
if (val == NULL) goto cleanup;
if (json_encode(self, val) < 0) goto cleanup;
if (ms_write(self, ",", 1) < 0) goto cleanup;
}
/* Overwrite trailing comma with ] */
*(self->output_buffer_raw + self->output_len - 1) = ']';
status = 0;
cleanup:
Py_LeaveRecursiveCall();
return status;
}
static int
json_encode_struct(EncoderState *self, PyObject *obj)
{
StructMetaObject *struct_type = (StructMetaObject *)Py_TYPE(obj);
if (struct_type->array_like == OPT_TRUE) {
return json_encode_struct_array(self, struct_type, obj);
}
return json_encode_struct_object(self, struct_type, obj);
}
static MS_NOINLINE int
json_encode_uncommon(EncoderState *self, PyTypeObject *type, PyObject *obj) {
if (obj == Py_None) {
return ms_write(self, "null", 4);
}
else if (obj == Py_True) {
return ms_write(self, "true", 4);
}
else if (obj == Py_False) {
return ms_write(self, "false", 5);
}
else if (Py_TYPE(type) == &StructMetaType) {
return json_encode_struct(self, obj);
}
else if (PyTuple_Check(obj)) {
return json_encode_tuple(self, obj);
}
else if (type == PyDateTimeAPI->DateTimeType) {
return json_encode_datetime(self, obj);
}
else if (type == PyDateTimeAPI->DateType) {
return json_encode_date(self, obj);
}
else if (type == PyDateTimeAPI->TimeType) {
return json_encode_time(self, obj);
}
else if (type == PyDateTimeAPI->DeltaType) {
return json_encode_timedelta(self, obj);
}
else if (type == &PyBytes_Type) {
return json_encode_bytes(self, obj);
}
else if (type == &PyByteArray_Type) {
return json_encode_bytearray(self, obj);
}
else if (type == &PyMemoryView_Type) {
return json_encode_memoryview(self, obj);
}
else if (type == &Raw_Type) {
return json_encode_raw(self, obj);
}
else if (Py_TYPE(type) == self->mod->EnumMetaType) {
return json_encode_enum(self, obj, false);
}
else if (PyType_IsSubtype(type, (PyTypeObject *)(self->mod->UUIDType))) {
return json_encode_uuid(self, obj);
}
else if (type == (PyTypeObject *)(self->mod->DecimalType)) {
return json_encode_decimal(self, obj);
}
else if (PyAnySet_Check(obj)) {
return json_encode_set(self, obj);
}
else if (!PyType_Check(obj) && type->tp_dict != NULL) {
PyObject *fields = PyObject_GetAttr(obj, self->mod->str___dataclass_fields__);
if (fields != NULL) {
int status = json_encode_dataclass(self, obj, fields);
Py_DECREF(fields);
return status;
}
else {
PyErr_Clear();
}
if (PyDict_Contains(type->tp_dict, self->mod->str___attrs_attrs__)) {
return json_encode_object(self, obj);
}
}
if (self->enc_hook != NULL) {
int status = -1;
PyObject *temp;
temp = PyObject_CallOneArg(self->enc_hook, obj);
if (temp == NULL) return -1;
if (!Py_EnterRecursiveCall(" while serializing an object")) {
status = json_encode(self, temp);
Py_LeaveRecursiveCall();
}
Py_DECREF(temp);
return status;
}
return ms_encode_err_type_unsupported(type);
}
static MS_INLINE int
json_encode_inline(EncoderState *self, PyObject *obj)
{
PyTypeObject *type = Py_TYPE(obj);
if (type == &PyUnicode_Type) {
return json_encode_str(self, obj);
}
else if (type == &PyLong_Type) {
return json_encode_long(self, obj);
}
else if (type == &PyFloat_Type) {
return json_encode_float(self, obj);
}
else if (PyList_Check(obj)) {
return json_encode_list(self, obj);
}
else if (PyDict_Check(obj)) {
return json_encode_dict(self, obj);
}
else {
return json_encode_uncommon(self, type, obj);
}
}
static int
json_encode(EncoderState *self, PyObject *obj)
{
return json_encode_inline(self, obj);
}
static PyObject*
JSONEncoder_encode_into(Encoder *self, PyObject *const *args, Py_ssize_t nargs)
{
return encoder_encode_into_common(self, args, nargs, &json_encode);
}
static PyObject*
JSONEncoder_encode(Encoder *self, PyObject *const *args, Py_ssize_t nargs)
{
return encoder_encode_common(self, args, nargs, &json_encode);
}
PyDoc_STRVAR(JSONEncoder_encode_lines__doc__,
"encode_lines(self, items)\n"
"--\n"
"\n"
"Encode an iterable of items as newline-delimited JSON, one item per line.\n"
"\n"
"Parameters\n"
"----------\n"
"items : iterable\n"
" An iterable of items to encode.\n"
"\n"
"Returns\n"
"-------\n"
"data : bytes\n"
" The items encoded as newline-delimited JSON, one item per line.\n"
"\n"
"Examples\n"
"--------\n"
">>> import msgspec\n"
">>> items = [{\"name\": \"alice\"}, {\"name\": \"ben\"}]\n"
">>> encoder = msgspec.json.Encoder()\n"
">>> encoder.encode_lines(items)\n"
"b'{\"name\":\"alice\"}\\n{\"name\":\"ben\"}\\n'"
);
static PyObject *
JSONEncoder_encode_lines(Encoder *self, PyObject *const *args, Py_ssize_t nargs)
{
if (!check_positional_nargs(nargs, 1, 1)) return NULL;
EncoderState state = {
.mod = self->mod,
.enc_hook = self->enc_hook,
.decimal_format = self->decimal_format,
.uuid_format = self->uuid_format,
.order = self->order,
.output_len = 0,
.max_output_len = ENC_LINES_INIT_BUFSIZE,
.resize_buffer = &ms_resize_bytes
};
state.output_buffer = PyBytes_FromStringAndSize(NULL, state.max_output_len);
if (state.output_buffer == NULL) return NULL;
state.output_buffer_raw = PyBytes_AS_STRING(state.output_buffer);
PyObject *input = args[0];
if (MS_LIKELY(PyList_Check(input))) {
for (Py_ssize_t i = 0; i < PyList_GET_SIZE(input); i++) {
if (json_encode(&state, PyList_GET_ITEM(input, i)) < 0) goto error;
if (ms_write(&state, "\n", 1) < 0) goto error;
}
}
else {
PyObject *iter = PyObject_GetIter(input);
if (iter == NULL) goto error;
PyObject *item;
while ((item = PyIter_Next(iter))) {
if (json_encode(&state, item) < 0) goto error;
if (ms_write(&state, "\n", 1) < 0) goto error;
}
if (PyErr_Occurred()) goto error;
}
FAST_BYTES_SHRINK(state.output_buffer, state.output_len);
return state.output_buffer;
error:
Py_DECREF(state.output_buffer);
return NULL;
}
static struct PyMethodDef JSONEncoder_methods[] = {
{
"encode", (PyCFunction) JSONEncoder_encode, METH_FASTCALL,
Encoder_encode__doc__,
},
{
"encode_into", (PyCFunction) JSONEncoder_encode_into, METH_FASTCALL,
Encoder_encode_into__doc__,
},
{
"encode_lines", (PyCFunction) JSONEncoder_encode_lines, METH_FASTCALL,
JSONEncoder_encode_lines__doc__,
},
{NULL, NULL} /* sentinel */
};
static PyTypeObject JSONEncoder_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec.json.Encoder",
.tp_doc = JSONEncoder__doc__,
.tp_basicsize = sizeof(Encoder),
.tp_dealloc = (destructor)Encoder_dealloc,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_traverse = (traverseproc)Encoder_traverse,
.tp_clear = (inquiry)Encoder_clear,
.tp_new = PyType_GenericNew,
.tp_init = (initproc)Encoder_init,
.tp_methods = JSONEncoder_methods,
.tp_members = Encoder_members,
.tp_getset = Encoder_getset,
};
PyDoc_STRVAR(msgspec_json_encode__doc__,
"json_encode(obj, *, enc_hook=None, order=None)\n"
"--\n"
"\n"
"Serialize an object as JSON.\n"
"\n"
"Parameters\n"
"----------\n"
"obj : Any\n"
" The object to serialize.\n"
"enc_hook : callable, optional\n"
" A callable to call for objects that aren't supported msgspec types. Takes\n"
" the unsupported object and should return a supported object, or raise a\n"
" ``NotImplementedError`` if unsupported.\n"
"order : {None, 'deterministic', 'sorted'}, optional\n"
" The ordering to use when encoding unordered compound types.\n"
"\n"
" - ``None``: All objects are encoded in the most efficient manner matching\n"
" their in-memory representations. The default.\n"
" - `'deterministic'`: Unordered collections (sets, dicts) are sorted to\n"
" ensure a consistent output between runs. Useful when comparison/hashing\n"
" of the encoded binary output is necessary.\n"
" - `'sorted'`: Like `'deterministic'`, but *all* object-like types (structs,\n"
" dataclasses, ...) are also sorted by field name before encoding. This is\n"
" slower than `'deterministic'`, but may produce more human-readable output.\n"
"\n"
"Returns\n"
"-------\n"
"data : bytes\n"
" The serialized object.\n"
"\n"
"See Also\n"
"--------\n"
"Encoder.encode"
);
static PyObject*
msgspec_json_encode(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
return encode_common(self, args, nargs, kwnames, &json_encode);
}
/*************************************************************************
* MessagePack Decoder *
*************************************************************************/
typedef struct DecoderState {
/* Configuration */
TypeNode *type;
PyObject *dec_hook;
PyObject *ext_hook;
bool strict;
/* Per-message attributes */
PyObject *buffer_obj;
char *input_start;
char *input_pos;
char *input_end;
} DecoderState;
typedef struct Decoder {
PyObject_HEAD
PyObject *orig_type;
/* Configuration */
TypeNode *type;
char strict;
PyObject *dec_hook;
PyObject *ext_hook;
} Decoder;
PyDoc_STRVAR(Decoder__doc__,
"Decoder(type='Any', *, strict=True, dec_hook=None, ext_hook=None)\n"
"--\n"
"\n"
"A MessagePack decoder.\n"
"\n"
"Parameters\n"
"----------\n"
"type : type, optional\n"
" A Python type (in type annotation form) to decode the object as. If\n"
" provided, the message will be type checked and decoded as the specified\n"
" type. Defaults to `Any`, in which case the message will be decoded using\n"
" the default MessagePack types.\n"
"strict : bool, optional\n"
" Whether type coercion rules should be strict. Setting to False enables a\n"
" wider set of coercion rules from string to non-string types for all values.\n"
" Default is True.\n"
"dec_hook : callable, optional\n"
" An optional callback for handling decoding custom types. Should have the\n"
" signature ``dec_hook(type: Type, obj: Any) -> Any``, where ``type`` is the\n"
" expected message type, and ``obj`` is the decoded representation composed\n"
" of only basic MessagePack types. This hook should transform ``obj`` into\n"
" type ``type``, or raise a ``NotImplementedError`` if unsupported.\n"
"ext_hook : callable, optional\n"
" An optional callback for decoding MessagePack extensions. Should have the\n"
" signature ``ext_hook(code: int, data: memoryview) -> Any``. If provided,\n"
" this will be called to deserialize all extension types found in the\n"
" message. Note that ``data`` is a memoryview into the larger message\n"
" buffer - any references created to the underlying buffer without copying\n"
" the data out will cause the full message buffer to persist in memory.\n"
" If not provided, extension types will decode as ``msgspec.Ext`` objects."
);
static int
Decoder_init(Decoder *self, PyObject *args, PyObject *kwds)
{
char *kwlist[] = {"type", "strict", "dec_hook", "ext_hook", NULL};
MsgspecState *st = msgspec_get_global_state();
PyObject *type = st->typing_any;
PyObject *ext_hook = NULL;
PyObject *dec_hook = NULL;
int strict = 1;
if (!PyArg_ParseTupleAndKeywords(
args, kwds, "|O$pOO", kwlist, &type, &strict, &dec_hook, &ext_hook
)) {
return -1;
}
/* Handle strict */
self->strict = strict;
/* Handle dec_hook */
if (dec_hook == Py_None) {
dec_hook = NULL;
}
if (dec_hook != NULL) {
if (!PyCallable_Check(dec_hook)) {
PyErr_SetString(PyExc_TypeError, "dec_hook must be callable");
return -1;
}
Py_INCREF(dec_hook);
}
self->dec_hook = dec_hook;
/* Handle ext_hook */
if (ext_hook == Py_None) {
ext_hook = NULL;
}
if (ext_hook != NULL) {
if (!PyCallable_Check(ext_hook)) {
PyErr_SetString(PyExc_TypeError, "ext_hook must be callable");
return -1;
}
Py_INCREF(ext_hook);
}
self->ext_hook = ext_hook;
/* Handle type */
self->type = TypeNode_Convert(type);
if (self->type == NULL) {
return -1;
}
Py_INCREF(type);
self->orig_type = type;
return 0;
}
static int
Decoder_traverse(Decoder *self, visitproc visit, void *arg)
{
int out = TypeNode_traverse(self->type, visit, arg);
if (out != 0) return out;
Py_VISIT(self->orig_type);
Py_VISIT(self->dec_hook);
Py_VISIT(self->ext_hook);
return 0;
}
static void
Decoder_dealloc(Decoder *self)
{
PyObject_GC_UnTrack(self);
TypeNode_Free(self->type);
Py_XDECREF(self->orig_type);
Py_XDECREF(self->dec_hook);
Py_XDECREF(self->ext_hook);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
Decoder_repr(Decoder *self) {
int recursive;
PyObject *typstr, *out = NULL;
recursive = Py_ReprEnter((PyObject *)self);
if (recursive != 0) {
return (recursive < 0) ? NULL : PyUnicode_FromString("..."); /* cpylint-ignore */
}
typstr = PyObject_Repr(self->orig_type);
if (typstr != NULL) {
out = PyUnicode_FromFormat("msgspec.msgpack.Decoder(%U)", typstr);
}
Py_XDECREF(typstr);
Py_ReprLeave((PyObject *)self);
return out;
}
static MS_INLINE int
mpack_read1(DecoderState *self, char *s)
{
if (MS_UNLIKELY(self->input_pos == self->input_end)) {
return ms_err_truncated();
}
*s = *self->input_pos++;
return 0;
}
static MS_INLINE int
mpack_read(DecoderState *self, char **s, Py_ssize_t n)
{
if (MS_LIKELY(n <= self->input_end - self->input_pos)) {
*s = self->input_pos;
self->input_pos += n;
return 0;
}
return ms_err_truncated();
}
static MS_INLINE bool
mpack_has_trailing_characters(DecoderState *self)
{
if (self->input_pos != self->input_end) {
PyErr_Format(
msgspec_get_global_state()->DecodeError,
"MessagePack data is malformed: trailing characters (byte %zd)",
(Py_ssize_t)(self->input_pos - self->input_start)
);
return true;
}
return false;
}
static MS_INLINE Py_ssize_t
mpack_decode_size1(DecoderState *self) {
char s = 0;
if (mpack_read1(self, &s) < 0) return -1;
return (Py_ssize_t)((unsigned char)s);
}
static MS_INLINE Py_ssize_t
mpack_decode_size2(DecoderState *self) {
char *s = NULL;
if (mpack_read(self, &s, 2) < 0) return -1;
return (Py_ssize_t)(_msgspec_load16(uint16_t, s));
}
static MS_INLINE Py_ssize_t
mpack_decode_size4(DecoderState *self) {
char *s = NULL;
if (mpack_read(self, &s, 4) < 0) return -1;
return (Py_ssize_t)(_msgspec_load32(uint32_t, s));
}
static PyObject *
mpack_error_expected(char op, char *expected, PathNode *path) {
char *got;
if (('\x00' <= op && op <= '\x7f') || ('\xe0' <= op && op <= '\xff')) {
got = "int";
}
else if ('\xa0' <= op && op <= '\xbf') {
got = "str";
}
else if ('\x90' <= op && op <= '\x9f') {
got = "array";
}
else if ('\x80' <= op && op <= '\x8f') {
got = "object";
}
else {
switch ((enum mpack_code)op) {
case MP_NIL:
got = "null";
break;
case MP_TRUE:
case MP_FALSE:
got = "bool";
break;
case MP_UINT8:
case MP_UINT16:
case MP_UINT32:
case MP_UINT64:
case MP_INT8:
case MP_INT16:
case MP_INT32:
case MP_INT64:
got = "int";
break;
case MP_FLOAT32:
case MP_FLOAT64:
got = "float";
break;
case MP_STR8:
case MP_STR16:
case MP_STR32:
got = "str";
break;
case MP_BIN8:
case MP_BIN16:
case MP_BIN32:
got = "bytes";
break;
case MP_ARRAY16:
case MP_ARRAY32:
got = "array";
break;
case MP_MAP16:
case MP_MAP32:
got = "object";
break;
case MP_FIXEXT1:
case MP_FIXEXT2:
case MP_FIXEXT4:
case MP_FIXEXT8:
case MP_FIXEXT16:
case MP_EXT8:
case MP_EXT16:
case MP_EXT32:
got = "ext";
break;
default:
got = "unknown";
break;
}
}
ms_raise_validation_error(path, "Expected `%s`, got `%s`%U", expected, got);
return NULL;
}
static MS_INLINE Py_ssize_t
mpack_decode_cstr(DecoderState *self, char ** out, PathNode *path) {
char op = 0;
Py_ssize_t size;
if (mpack_read1(self, &op) < 0) return -1;
if ('\xa0' <= op && op <= '\xbf') {
size = op & 0x1f;
}
else if (op == MP_STR8) {
size = mpack_decode_size1(self);
}
else if (op == MP_STR16) {
size = mpack_decode_size2(self);
}
else if (op == MP_STR32) {
size = mpack_decode_size4(self);
}
else {
mpack_error_expected(op, "str", path);
return -1;
}
if (mpack_read(self, out, size) < 0) return -1;
return size;
}
/* Decode an integer. If the value fits in an int64_t, it will be stored in
* `out`, otherwise it will be stored in `uout`. A return value of -1 indicates
* an error. */
static int
mpack_decode_cint(DecoderState *self, int64_t *out, uint64_t *uout, PathNode *path) {
char op = 0;
char *s = NULL;
if (mpack_read1(self, &op) < 0) return -1;
if (('\x00' <= op && op <= '\x7f') || ('\xe0' <= op && op <= '\xff')) {
*out = *((int8_t *)(&op));
}
else if (op == MP_UINT8) {
if (MS_UNLIKELY(mpack_read(self, &s, 1) < 0)) return -1;
*out = *(uint8_t *)s;
}
else if (op == MP_UINT16) {
if (MS_UNLIKELY(mpack_read(self, &s, 2) < 0)) return -1;
*out = _msgspec_load16(uint16_t, s);
}
else if (op == MP_UINT32) {
if (MS_UNLIKELY(mpack_read(self, &s, 4) < 0)) return -1;
*out = _msgspec_load32(uint32_t, s);
}
else if (op == MP_UINT64) {
if (MS_UNLIKELY(mpack_read(self, &s, 8) < 0)) return -1;
uint64_t ux = _msgspec_load64(uint64_t, s);
if (ux > LLONG_MAX) {
*uout = ux;
}
else {
*out = ux;
}
}
else if (op == MP_INT8) {
if (MS_UNLIKELY(mpack_read(self, &s, 1) < 0)) return -1;
*out = *(int8_t *)s;
}
else if (op == MP_INT16) {
if (MS_UNLIKELY(mpack_read(self, &s, 2) < 0)) return -1;
*out = _msgspec_load16(int16_t, s);
}
else if (op == MP_INT32) {
if (MS_UNLIKELY(mpack_read(self, &s, 4) < 0)) return -1;
*out = _msgspec_load32(int32_t, s);
}
else if (op == MP_INT64) {
if (MS_UNLIKELY(mpack_read(self, &s, 8) < 0)) return -1;
*out = _msgspec_load64(int64_t, s);
}
else {
mpack_error_expected(op, "int", path);
return -1;
}
return 0;
}
static PyObject *
mpack_decode_datetime(
DecoderState *self, const char *data_buf, Py_ssize_t size,
TypeNode *type, PathNode *path
) {
uint64_t data64;
uint32_t nanoseconds;
int64_t seconds;
switch (size) {
case 4:
seconds = _msgspec_load32(uint32_t, data_buf);
nanoseconds = 0;
break;
case 8:
data64 = _msgspec_load64(uint64_t, data_buf);
seconds = data64 & 0x00000003ffffffffL;
nanoseconds = data64 >> 34;
break;
case 12:
nanoseconds = _msgspec_load32(uint32_t, data_buf);
seconds = _msgspec_load64(uint64_t, data_buf + 4);
break;
default:
return ms_error_with_path(
"Invalid MessagePack timestamp%U",
path
);
}
if (nanoseconds > 999999999) {
return ms_error_with_path(
"Invalid MessagePack timestamp: nanoseconds out of range%U",
path
);
}
return datetime_from_epoch(seconds, nanoseconds, type, path);
}
static int mpack_skip(DecoderState *self);
static int
mpack_skip_array(DecoderState *self, Py_ssize_t size) {
int status = -1;
Py_ssize_t i;
if (size < 0) return -1;
if (size == 0) return 0;
if (Py_EnterRecursiveCall(" while deserializing an object")) return -1;
for (i = 0; i < size; i++) {
if (mpack_skip(self) < 0) goto done;
}
status = 0;
done:
Py_LeaveRecursiveCall();
return status;
}
static int
mpack_skip_map(DecoderState *self, Py_ssize_t size) {
return mpack_skip_array(self, size * 2);
}
static int
mpack_skip_ext(DecoderState *self, Py_ssize_t size) {
char *s;
if (size < 0) return -1;
return mpack_read(self, &s, size + 1);
}
static int
mpack_skip(DecoderState *self) {
char *s = NULL;
char op = 0;
Py_ssize_t size;
if (mpack_read1(self, &op) < 0) return -1;
if (('\x00' <= op && op <= '\x7f') || ('\xe0' <= op && op <= '\xff')) {
return 0;
}
else if ('\xa0' <= op && op <= '\xbf') {
return mpack_read(self, &s, op & 0x1f);
}
else if ('\x90' <= op && op <= '\x9f') {
return mpack_skip_array(self, op & 0x0f);
}
else if ('\x80' <= op && op <= '\x8f') {
return mpack_skip_map(self, op & 0x0f);
}
switch ((enum mpack_code)op) {
case MP_NIL:
case MP_TRUE:
case MP_FALSE:
return 0;
case MP_UINT8:
case MP_INT8:
return mpack_read1(self, &op);
case MP_UINT16:
case MP_INT16:
return mpack_read(self, &s, 2);
case MP_UINT32:
case MP_INT32:
case MP_FLOAT32:
return mpack_read(self, &s, 4);
case MP_UINT64:
case MP_INT64:
case MP_FLOAT64:
return mpack_read(self, &s, 8);
case MP_STR8:
case MP_BIN8:
if ((size = mpack_decode_size1(self)) < 0) return -1;
return mpack_read(self, &s, size);
case MP_STR16:
case MP_BIN16:
if ((size = mpack_decode_size2(self)) < 0) return -1;
return mpack_read(self, &s, size);
case MP_STR32:
case MP_BIN32:
if ((size = mpack_decode_size4(self)) < 0) return -1;
return mpack_read(self, &s, size);
case MP_ARRAY16:
return mpack_skip_array(self, mpack_decode_size2(self));
case MP_ARRAY32:
return mpack_skip_array(self, mpack_decode_size4(self));
case MP_MAP16:
return mpack_skip_map(self, mpack_decode_size2(self));
case MP_MAP32:
return mpack_skip_map(self, mpack_decode_size4(self));
case MP_FIXEXT1:
return mpack_skip_ext(self, 1);
case MP_FIXEXT2:
return mpack_skip_ext(self, 2);
case MP_FIXEXT4:
return mpack_skip_ext(self, 4);
case MP_FIXEXT8:
return mpack_skip_ext(self, 8);
case MP_FIXEXT16:
return mpack_skip_ext(self, 16);
case MP_EXT8:
return mpack_skip_ext(self, mpack_decode_size1(self));
case MP_EXT16:
return mpack_skip_ext(self, mpack_decode_size2(self));
case MP_EXT32:
return mpack_skip_ext(self, mpack_decode_size4(self));
default:
PyErr_Format(
msgspec_get_global_state()->DecodeError,
"MessagePack data is malformed: invalid opcode '\\x%02x' (byte %zd)",
(unsigned char)op,
(Py_ssize_t)(self->input_pos - self->input_start - 1)
);
return -1;
}
}
static PyObject * mpack_decode(
DecoderState *self, TypeNode *type, PathNode *path, bool is_key
);
static PyObject *
mpack_decode_none(DecoderState *self, TypeNode *type, PathNode *path) {
if (type->types & (MS_TYPE_ANY | MS_TYPE_NONE)) {
Py_INCREF(Py_None);
return Py_None;
}
return ms_validation_error("None", type, path);
}
static PyObject *
mpack_decode_bool(DecoderState *self, PyObject *val, TypeNode *type, PathNode *path) {
if (type->types & (MS_TYPE_ANY | MS_TYPE_BOOL)) {
Py_INCREF(val);
return val;
}
return ms_validation_error("bool", type, path);
}
static PyObject *
mpack_decode_float(DecoderState *self, double x, TypeNode *type, PathNode *path) {
if (MS_LIKELY(type->types & (MS_TYPE_ANY | MS_TYPE_FLOAT))) {
return ms_decode_float(x, type, path);
}
else if (type->types & MS_TYPE_DECIMAL) {
return ms_decode_decimal_from_float(x, path, NULL);
}
else if (!self->strict) {
if (type->types & MS_TYPE_INT) {
int64_t out;
if (double_as_int64(x, &out)) {
return ms_post_decode_int64(out, type, path, self->strict, false);
}
}
if (type->types & MS_TYPE_DATETIME) {
return ms_decode_datetime_from_float(x, type, path);
}
if (type->types & MS_TYPE_TIMEDELTA) {
return ms_decode_timedelta_from_float(x, path);
}
}
return ms_validation_error("float", type, path);
}
static PyObject *
mpack_decode_str(DecoderState *self, Py_ssize_t size, TypeNode *type, PathNode *path) {
char *s = NULL;
if (MS_UNLIKELY(mpack_read(self, &s, size) < 0)) return NULL;
if (MS_LIKELY(type->types & (MS_TYPE_STR | MS_TYPE_ANY))) {
return ms_check_str_constraints(
PyUnicode_DecodeUTF8(s, size, NULL), type, path
);
}
else if (MS_UNLIKELY(!self->strict)) {
bool invalid = false;
PyObject *out = ms_decode_str_lax(s, size, type, path, &invalid);
if (!invalid) return out;
}
if (MS_UNLIKELY(type->types & (MS_TYPE_ENUM | MS_TYPE_STRLITERAL))) {
return ms_decode_str_enum_or_literal(s, size, type, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_DATETIME)) {
return ms_decode_datetime_from_str(s, size, type, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_DATE)) {
return ms_decode_date(s, size, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_TIME)) {
return ms_decode_time(s, size, type, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_TIMEDELTA)) {
return ms_decode_timedelta(s, size, type, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_UUID)) {
return ms_decode_uuid_from_str(s, size, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_DECIMAL)) {
return ms_decode_decimal(s, size, false, path, NULL);
}
return ms_validation_error("str", type, path);
}
static PyObject *
mpack_decode_bin(
DecoderState *self, Py_ssize_t size, TypeNode *type, PathNode *path
) {
if (MS_UNLIKELY(size < 0)) return NULL;
if (MS_UNLIKELY(!ms_passes_bytes_constraints(size, type, path))) return NULL;
char *s = NULL;
if (MS_UNLIKELY(mpack_read(self, &s, size) < 0)) return NULL;
if (type->types & (MS_TYPE_ANY | MS_TYPE_BYTES)) {
return PyBytes_FromStringAndSize(s, size);
}
else if (type->types & MS_TYPE_BYTEARRAY) {
return PyByteArray_FromStringAndSize(s, size);
}
else if (type->types & MS_TYPE_UUID) {
return ms_decode_uuid_from_bytes(s, size, path);
}
else if (type->types & MS_TYPE_MEMORYVIEW) {
PyObject *view = PyMemoryView_GetContiguous(
self->buffer_obj, PyBUF_READ, 'C'
);
if (view == NULL) return NULL;
Py_buffer *buffer = PyMemoryView_GET_BUFFER(view);
buffer->buf = s;
buffer->len = size;
return view;
}
return ms_validation_error("bytes", type, path);
}
static PyObject *
mpack_decode_list(
DecoderState *self, Py_ssize_t size, TypeNode *el_type, PathNode *path
) {
Py_ssize_t i;
PyObject *res, *item;
/* XXX: Preallocate all elements for lists <= 16 elements in length.
*
* This minimizes the ability of malicious messages to cause a massive
* overallocation, while not penalizing decoding speed for small lists.
* With this restriction, a malicious message can preallocate at most:
*
* sys.getsizeof(list(range(16))) * sys.getrecursionlimit()
*
* bytes, which should be low enough to not matter (500 KiB on my machine).
* Dropping this optimization (resulting in the same allocation pattern as
* the JSON decoder would reduce this to
*
* sys.getsizeof([]) * sys.getrecursionlimit()
*
* which is roughly 1/3 the size. This reduction is deemed not worth it.
*/
res = PyList_New(Py_MIN(16, size));
if (res == NULL) return NULL;
Py_SET_SIZE(res, 0);
if (size == 0) return res;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(res);
return NULL; /* cpylint-ignore */
}
for (i = 0; i < size; i++) {
PathNode el_path = {path, i};
item = mpack_decode(self, el_type, &el_path, false);
if (MS_UNLIKELY(item == NULL)) {
Py_CLEAR(res);
break;
}
/* Append item to list */
if (MS_LIKELY((LIST_CAPACITY(res) > Py_SIZE(res)))) {
PyList_SET_ITEM(res, Py_SIZE(res), item);
Py_SET_SIZE(res, Py_SIZE(res) + 1);
}
else {
int status = PyList_Append(res, item);
Py_DECREF(item);
if (MS_UNLIKELY(status < 0)) {
Py_CLEAR(res);
break;
}
}
}
Py_LeaveRecursiveCall();
return res;
}
static PyObject *
mpack_decode_set(
DecoderState *self, bool mutable, Py_ssize_t size, TypeNode *el_type, PathNode *path
) {
Py_ssize_t i;
PyObject *res, *item;
res = mutable ? PySet_New(NULL) : PyFrozenSet_New(NULL);
if (res == NULL) return NULL;
if (size == 0) return res;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(res);
return NULL; /* cpylint-ignore */
}
for (i = 0; i < size; i++) {
PathNode el_path = {path, i};
item = mpack_decode(self, el_type, &el_path, true);
if (MS_UNLIKELY(item == NULL || PySet_Add(res, item) < 0)) {
Py_XDECREF(item);
Py_CLEAR(res);
break;
}
Py_DECREF(item);
}
Py_LeaveRecursiveCall();
return res;
}
static PyObject *
mpack_decode_vartuple(
DecoderState *self, Py_ssize_t size, TypeNode *el_type, PathNode *path, bool is_key
) {
if (MS_UNLIKELY(size > 16)) {
/* For variadic tuples of length > 16, we fallback to decoding into a
* list, then converting to a tuple. This lets us avoid pre-allocating
* extremely large tuples. See the comment in `mpack_decode_list` for
* more info. */
PyObject *temp = mpack_decode_list(self, size, el_type, path);
if (temp == NULL) return NULL;
PyObject *res = PyList_AsTuple(temp);
Py_DECREF(temp);
return res;
}
PyObject *res = PyTuple_New(size);
if (res == NULL) return NULL;
if (size == 0) return res;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(res);
return NULL; /* cpylint-ignore */
}
for (Py_ssize_t i = 0; i < size; i++) {
PathNode el_path = {path, i};
PyObject *item = mpack_decode(self, el_type, &el_path, is_key);
if (MS_UNLIKELY(item == NULL)) {
Py_CLEAR(res);
break;
}
PyTuple_SET_ITEM(res, i, item);
}
Py_LeaveRecursiveCall();
return res;
}
static PyObject *
mpack_decode_fixtuple(
DecoderState *self, Py_ssize_t size, TypeNode *type, PathNode *path, bool is_key
) {
PyObject *res, *item;
Py_ssize_t i, fixtuple_size, offset;
TypeNode_get_fixtuple(type, &offset, &fixtuple_size);
if (size != fixtuple_size) {
/* tuple is the incorrect size, raise and return */
ms_raise_validation_error(
path,
"Expected `array` of length %zd, got %zd%U",
fixtuple_size,
size
);
return NULL;
}
res = PyTuple_New(size);
if (res == NULL) return NULL;
if (size == 0) return res;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(res);
return NULL; /* cpylint-ignore */
}
for (i = 0; i < fixtuple_size; i++) {
PathNode el_path = {path, i};
item = mpack_decode(self, type->details[offset + i].pointer, &el_path, is_key);
if (MS_UNLIKELY(item == NULL)) {
Py_CLEAR(res);
break;
}
PyTuple_SET_ITEM(res, i, item);
}
Py_LeaveRecursiveCall();
return res;
}
static PyObject *
mpack_decode_namedtuple(
DecoderState *self, Py_ssize_t size, TypeNode *type, PathNode *path, bool is_key
) {
NamedTupleInfo *info = TypeNode_get_namedtuple_info(type);
Py_ssize_t nfields = Py_SIZE(info);
Py_ssize_t ndefaults = info->defaults == NULL ? 0 : PyTuple_GET_SIZE(info->defaults);
Py_ssize_t nrequired = nfields - ndefaults;
if (size < nrequired || nfields < size) {
/* tuple is the incorrect size, raise and return */
if (ndefaults == 0) {
ms_raise_validation_error(
path,
"Expected `array` of length %zd, got %zd%U",
nfields,
size
);
}
else {
ms_raise_validation_error(
path,
"Expected `array` of length %zd to %zd, got %zd%U",
nrequired,
nfields,
size
);
}
return NULL;
}
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
PyTypeObject *nt_type = (PyTypeObject *)(info->class);
PyObject *res = nt_type->tp_alloc(nt_type, nfields);
if (res == NULL) goto error;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyTuple_SET_ITEM(res, i, NULL);
}
for (Py_ssize_t i = 0; i < size; i++) {
PathNode el_path = {path, i};
PyObject *item = mpack_decode(self, info->types[i], &el_path, is_key);
if (MS_UNLIKELY(item == NULL)) goto error;
PyTuple_SET_ITEM(res, i, item);
}
for (Py_ssize_t i = size; i < nfields; i++) {
PyObject *item = PyTuple_GET_ITEM(info->defaults, i - nrequired);
Py_INCREF(item);
PyTuple_SET_ITEM(res, i, item);
}
Py_LeaveRecursiveCall();
return res;
error:
Py_LeaveRecursiveCall();
Py_CLEAR(res);
return NULL;
}
static int
mpack_ensure_tag_matches(
DecoderState *self, PathNode *path, PyObject *expected_tag
) {
if (PyUnicode_CheckExact(expected_tag)) {
char *tag = NULL;
Py_ssize_t tag_size;
tag_size = mpack_decode_cstr(self, &tag, path);
if (tag_size < 0) return -1;
/* Check that tag matches expected tag value */
Py_ssize_t expected_size;
const char *expected_str = unicode_str_and_size_nocheck(
expected_tag, &expected_size
);
if (tag_size != expected_size || memcmp(tag, expected_str, expected_size) != 0) {
/* Tag doesn't match the expected value, error nicely */
ms_invalid_cstr_value(tag, tag_size, path);
return -1;
}
}
else {
int64_t tag = 0;
uint64_t utag = 0;
if (mpack_decode_cint(self, &tag, &utag, path) < 0) return -1;
int64_t expected = PyLong_AsLongLong(expected_tag);
/* Tags must be int64s, if utag != 0 then we know the tags don't match.
* We parse the full uint64 value only to validate the message and
* raise a nice error */
if (utag != 0) {
ms_invalid_cuint_value(utag, path);
return -1;
}
if (tag != expected) {
ms_invalid_cint_value(tag, path);
return -1;
}
}
return 0;
}
static StructInfo *
mpack_decode_tag_and_lookup_type(
DecoderState *self, Lookup *lookup, PathNode *path
) {
StructInfo *out = NULL;
if (Lookup_IsStrLookup(lookup)) {
Py_ssize_t tag_size;
char *tag = NULL;
tag_size = mpack_decode_cstr(self, &tag, path);
if (tag_size < 0) return NULL;
out = (StructInfo *)StrLookup_Get((StrLookup *)lookup, tag, tag_size);
if (out == NULL) {
ms_invalid_cstr_value(tag, tag_size, path);
}
}
else {
int64_t tag = 0;
uint64_t utag = 0;
if (mpack_decode_cint(self, &tag, &utag, path) < 0) return NULL;
if (utag == 0) {
out = (StructInfo *)IntLookup_GetInt64((IntLookup *)lookup, tag);
if (out == NULL) {
ms_invalid_cint_value(tag, path);
}
}
else {
out = (StructInfo *)IntLookup_GetUInt64((IntLookup *)lookup, utag);
if (out == NULL) {
ms_invalid_cuint_value(utag, path);
}
}
}
return out;
}
static PyObject *
mpack_decode_struct_array_inner(
DecoderState *self, Py_ssize_t size, bool tag_already_read,
StructInfo *info, PathNode *path, bool is_key
) {
Py_ssize_t i, nfields, ndefaults, nrequired, npos;
PyObject *res, *val = NULL;
StructMetaObject *st_type = info->class;
bool is_gc, should_untrack;
bool tagged = st_type->struct_tag_value != NULL;
PathNode item_path = {path, 0};
nfields = PyTuple_GET_SIZE(st_type->struct_encode_fields);
ndefaults = PyTuple_GET_SIZE(st_type->struct_defaults);
nrequired = tagged + nfields - st_type->n_trailing_defaults;
npos = nfields - ndefaults;
if (size < nrequired) {
ms_raise_validation_error(
path,
"Expected `array` of at least length %zd, got %zd%U",
nrequired,
size
);
return NULL;
}
if (tagged) {
if (!tag_already_read) {
if (mpack_ensure_tag_matches(self, &item_path, st_type->struct_tag_value) < 0) {
return NULL;
}
}
size--;
item_path.index++;
}
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
res = Struct_alloc((PyTypeObject *)(st_type));
if (res == NULL) goto error;
is_gc = MS_TYPE_IS_GC(st_type);
should_untrack = is_gc;
for (i = 0; i < nfields; i++) {
if (size > 0) {
val = mpack_decode(self, info->types[i], &item_path, is_key);
if (MS_UNLIKELY(val == NULL)) goto error;
size--;
item_path.index++;
}
else {
val = get_default(
PyTuple_GET_ITEM(st_type->struct_defaults, i - npos)
);
if (val == NULL)
goto error;
}
Struct_set_index(res, i, val);
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(val);
}
}
if (MS_UNLIKELY(size > 0)) {
if (MS_UNLIKELY(st_type->forbid_unknown_fields == OPT_TRUE)) {
ms_raise_validation_error(
path,
"Expected `array` of at most length %zd, got %zd%U",
nfields,
nfields + size
);
goto error;
}
else {
/* Ignore all trailing fields */
while (size > 0) {
if (mpack_skip(self) < 0)
goto error;
size--;
}
}
}
if (Struct_decode_post_init(st_type, res, path) < 0) goto error;
Py_LeaveRecursiveCall();
if (is_gc && !should_untrack)
PyObject_GC_Track(res);
return res;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(res);
return NULL;
}
static PyObject *
mpack_decode_struct_array(
DecoderState *self, Py_ssize_t size, TypeNode *type, PathNode *path, bool is_key
) {
StructInfo *info = TypeNode_get_struct_info(type);
return mpack_decode_struct_array_inner(self, size, false, info, path, is_key);
}
static PyObject *
mpack_decode_struct_array_union(
DecoderState *self, Py_ssize_t size, TypeNode *type, PathNode *path, bool is_key
) {
Lookup *lookup = TypeNode_get_struct_union(type);
if (size == 0) {
return ms_error_with_path(
"Expected `array` of at least length 1, got 0%U", path
);
}
/* Decode and lookup tag */
PathNode tag_path = {path, 0};
StructInfo *info = mpack_decode_tag_and_lookup_type(self, lookup, &tag_path);
if (info == NULL) return NULL;
/* Finish decoding the rest of the struct */
return mpack_decode_struct_array_inner(self, size, true, info, path, is_key);
}
static PyObject *
mpack_decode_array(
DecoderState *self, Py_ssize_t size, TypeNode *type, PathNode *path, bool is_key
) {
if (MS_UNLIKELY(!ms_passes_array_constraints(size, type, path))) return NULL;
if (type->types & MS_TYPE_ANY) {
TypeNode type_any = {MS_TYPE_ANY};
if (is_key) {
return mpack_decode_vartuple(self, size, &type_any, path, is_key);
}
else {
return mpack_decode_list(self, size, &type_any, path);
}
}
else if (type->types & MS_TYPE_LIST) {
return mpack_decode_list(self, size, TypeNode_get_array(type), path);
}
else if (type->types & (MS_TYPE_SET | MS_TYPE_FROZENSET)) {
return mpack_decode_set(
self, type->types & MS_TYPE_SET, size, TypeNode_get_array(type), path
);
}
else if (type->types & MS_TYPE_VARTUPLE) {
return mpack_decode_vartuple(self, size, TypeNode_get_array(type), path, is_key);
}
else if (type->types & MS_TYPE_FIXTUPLE) {
return mpack_decode_fixtuple(self, size, type, path, is_key);
}
else if (type->types & MS_TYPE_NAMEDTUPLE) {
return mpack_decode_namedtuple(self, size, type, path, is_key);
}
else if (type->types & MS_TYPE_STRUCT_ARRAY) {
return mpack_decode_struct_array(self, size, type, path, is_key);
}
else if (type->types & MS_TYPE_STRUCT_ARRAY_UNION) {
return mpack_decode_struct_array_union(self, size, type, path, is_key);
}
return ms_validation_error("array", type, path);
}
/* Specialized mpack_decode for dict keys, handling caching of short string keys */
static PyObject *
mpack_decode_key(DecoderState *self, TypeNode *type, PathNode *path) {
char op;
if (MS_UNLIKELY(self->input_pos == self->input_end)) {
ms_err_truncated();
return NULL;
}
/* Peek at the next op */
op = *self->input_pos;
bool is_str = type->types == MS_TYPE_ANY || type->types == MS_TYPE_STR;
if (MS_LIKELY(is_str && '\xa0' <= op && op <= '\xbf')) {
/* A short (<= 31 byte) unicode str */
self->input_pos++; /* consume op */
Py_ssize_t size = op & 0x1f;
/* Don't cache the empty string */
if (MS_UNLIKELY(size == 0)) return PyUnicode_New(0, 127);
/* Read in the string buffer */
char *str;
if (MS_UNLIKELY(mpack_read(self, &str, size) < 0)) return NULL;
/* Attempt a cache lookup. We don't know if it's ascii yet, but
* checking if it's ascii is more expensive than just doing a lookup,
* and most dict key strings are ascii */
uint32_t hash = murmur2(str, size);
uint32_t index = hash % STRING_CACHE_SIZE;
PyObject *existing = string_cache[index];
if (MS_LIKELY(existing != NULL)) {
Py_ssize_t e_size = ((PyASCIIObject *)existing)->length;
char *e_str = ascii_get_buffer(existing);
if (MS_LIKELY(size == e_size && memcmp(str, e_str, size) == 0)) {
Py_INCREF(existing);
return existing;
}
}
/* Cache miss, create a new string */
PyObject *new = PyUnicode_DecodeUTF8(str, size, NULL);
if (new == NULL) return NULL;
/* If ascii, add it to the cache */
if (PyUnicode_IS_COMPACT_ASCII(new)) {
Py_XDECREF(existing);
Py_INCREF(new);
string_cache[index] = new;
}
return new;
}
/* Fallback to standard decode */
return mpack_decode(self, type, path, true);
}
static PyObject *
mpack_decode_dict(
DecoderState *self, Py_ssize_t size, TypeNode *key_type,
TypeNode *val_type, PathNode *path
) {
Py_ssize_t i;
PyObject *res, *key = NULL, *val = NULL;
PathNode key_path = {path, PATH_KEY, NULL};
PathNode val_path = {path, PATH_ELLIPSIS, NULL};
res = PyDict_New();
if (res == NULL) return NULL;
if (size == 0) return res;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(res);
return NULL; /* cpylint-ignore */
}
for (i = 0; i < size; i++) {
key = mpack_decode_key(self, key_type, &key_path);
if (MS_UNLIKELY(key == NULL))
goto error;
val = mpack_decode(self, val_type, &val_path, false);
if (MS_UNLIKELY(val == NULL))
goto error;
if (MS_UNLIKELY(PyDict_SetItem(res, key, val) < 0))
goto error;
Py_CLEAR(key);
Py_CLEAR(val);
}
Py_LeaveRecursiveCall();
return res;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(key);
Py_XDECREF(val);
Py_DECREF(res);
return NULL;
}
static PyObject *
mpack_decode_typeddict(
DecoderState *self, Py_ssize_t size, TypeNode *type, PathNode *path
) {
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
PyObject *res = PyDict_New();
if (res == NULL) goto error;
TypedDictInfo *info = TypeNode_get_typeddict_info(type);
Py_ssize_t nrequired = 0, pos = 0;
for (Py_ssize_t i = 0; i < size; i++) {
char *key;
PathNode key_path = {path, PATH_KEY, NULL};
Py_ssize_t key_size = mpack_decode_cstr(self, &key, &key_path);
if (MS_UNLIKELY(key_size < 0)) goto error;
TypeNode *field_type;
PyObject *field = TypedDictInfo_lookup_key(info, key, key_size, &field_type, &pos);
if (field != NULL) {
PathNode field_path = {path, PATH_STR, field};
PyObject *val = mpack_decode(self, field_type, &field_path, false);
if (val == NULL) goto error;
/* We want to keep a count of required fields we've decoded. Since
* duplicates can occur, we stash the current dict size, then only
* increment if the dict size has changed _and_ the field is
* required. */
Py_ssize_t cur_size = PyDict_GET_SIZE(res);
int status = PyDict_SetItem(res, field, val);
/* Always decref value, no need to decref key since it's a borrowed
* reference. */
Py_DECREF(val);
if (status < 0) goto error;
if ((PyDict_GET_SIZE(res) != cur_size) && (field_type->types & MS_EXTRA_FLAG)) {
nrequired++;
}
}
else {
/* Unknown field, skip */
if (mpack_skip(self) < 0) goto error;
}
}
if (nrequired < info->nrequired) {
/* A required field is missing, determine which one and raise */
TypedDictInfo_error_missing(info, res, path);
goto error;
}
Py_LeaveRecursiveCall();
return res;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(res);
return NULL;
}
static PyObject *
mpack_decode_dataclass(
DecoderState *self, Py_ssize_t size, TypeNode *type, PathNode *path
) {
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
DataclassInfo *info = TypeNode_get_dataclass_info(type);
PyTypeObject *dataclass_type = (PyTypeObject *)(info->class);
PyObject *out = dataclass_type->tp_alloc(dataclass_type, 0);
if (out == NULL) goto error;
if (info->pre_init != NULL) {
PyObject *res = PyObject_CallOneArg(info->pre_init, out);
if (res == NULL) goto error;
Py_DECREF(res);
}
Py_ssize_t pos = 0;
for (Py_ssize_t i = 0; i < size; i++) {
char *key;
PathNode key_path = {path, PATH_KEY, NULL};
Py_ssize_t key_size = mpack_decode_cstr(self, &key, &key_path);
if (MS_UNLIKELY(key_size < 0)) goto error;
TypeNode *field_type;
PyObject *field = DataclassInfo_lookup_key(info, key, key_size, &field_type, &pos);
if (field != NULL) {
PathNode field_path = {path, PATH_STR, field};
PyObject *val = mpack_decode(self, field_type, &field_path, false);
if (val == NULL) goto error;
int status = PyObject_GenericSetAttr(out, field, val);
Py_DECREF(val);
if (status < 0) goto error;
}
else {
/* Unknown field, skip */
if (mpack_skip(self) < 0) goto error;
}
}
if (DataclassInfo_post_decode(info, out, path) < 0) goto error;
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(out);
return NULL;
}
static PyObject *
mpack_decode_struct_map(
DecoderState *self, Py_ssize_t size,
StructInfo *info, PathNode *path, bool is_key
) {
StructMetaObject *st_type = info->class;
Py_ssize_t i, key_size, field_index, pos = 0;
char *key = NULL;
PyObject *res, *val = NULL;
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
res = Struct_alloc((PyTypeObject *)(st_type));
if (res == NULL) goto error;
for (i = 0; i < size; i++) {
PathNode key_path = {path, PATH_KEY, NULL};
key_size = mpack_decode_cstr(self, &key, &key_path);
if (MS_UNLIKELY(key_size < 0)) goto error;
field_index = StructMeta_get_field_index(st_type, key, key_size, &pos);
if (field_index < 0) {
if (MS_UNLIKELY(field_index == -2)) {
PathNode tag_path = {path, PATH_STR, st_type->struct_tag_field};
if (mpack_ensure_tag_matches(self, &tag_path, st_type->struct_tag_value) < 0) {
goto error;
}
}
else {
/* Unknown field */
if (MS_UNLIKELY(st_type->forbid_unknown_fields == OPT_TRUE)) {
ms_error_unknown_field(key, key_size, path);
goto error;
}
else {
if (mpack_skip(self) < 0) goto error;
}
}
}
else {
PathNode field_path = {path, field_index, (PyObject *)st_type};
val = mpack_decode(self, info->types[field_index], &field_path, is_key);
if (val == NULL) goto error;
Struct_set_index(res, field_index, val);
}
}
if (Struct_fill_in_defaults(st_type, res, path) < 0) goto error;
Py_LeaveRecursiveCall();
return res;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(res);
return NULL;
}
static PyObject *
mpack_decode_struct_union(
DecoderState *self, Py_ssize_t size, TypeNode *type,
PathNode *path, bool is_key
) {
Lookup *lookup = TypeNode_get_struct_union(type);
PathNode key_path = {path, PATH_KEY, NULL};
Py_ssize_t tag_field_size;
const char *tag_field = unicode_str_and_size_nocheck(
Lookup_tag_field(lookup), &tag_field_size
);
/* Cache the current input position in case we need to reset it once the
* tag is found */
char *orig_input_pos = self->input_pos;
for (Py_ssize_t i = 0; i < size; i++) {
Py_ssize_t key_size;
char *key = NULL;
key_size = mpack_decode_cstr(self, &key, &key_path);
if (key_size < 0) return NULL;
if (key_size == tag_field_size && memcmp(key, tag_field, key_size) == 0) {
/* Decode and lookup tag */
PathNode tag_path = {path, PATH_STR, Lookup_tag_field(lookup)};
StructInfo *info = mpack_decode_tag_and_lookup_type(self, lookup, &tag_path);
if (info == NULL) return NULL;
if (i == 0) {
/* Common case, tag is first field. No need to reset, just mark
* that the first field has been read. */
size--;
}
else {
self->input_pos = orig_input_pos;
}
return mpack_decode_struct_map(self, size, info, path, is_key);
}
else {
/* Not the tag field, skip the value and try again */
if (mpack_skip(self) < 0) return NULL;
}
}
ms_missing_required_field(Lookup_tag_field(lookup), path);
return NULL;
}
static PyObject *
mpack_decode_map(
DecoderState *self, Py_ssize_t size, TypeNode *type,
PathNode *path, bool is_key
) {
if (type->types & MS_TYPE_STRUCT) {
StructInfo *info = TypeNode_get_struct_info(type);
return mpack_decode_struct_map(self, size, info, path, is_key);
}
else if (type->types & MS_TYPE_TYPEDDICT) {
return mpack_decode_typeddict(self, size, type, path);
}
else if (type->types & MS_TYPE_DATACLASS) {
return mpack_decode_dataclass(self, size, type, path);
}
else if (type->types & (MS_TYPE_DICT | MS_TYPE_ANY)) {
if (MS_UNLIKELY(!ms_passes_map_constraints(size, type, path))) {
return NULL;
}
TypeNode *key, *val;
TypeNode type_any = {MS_TYPE_ANY};
if (type->types & MS_TYPE_ANY) {
key = &type_any;
val = &type_any;
}
else {
TypeNode_get_dict(type, &key, &val);
}
return mpack_decode_dict(self, size, key, val, path);
}
else if (type->types & MS_TYPE_STRUCT_UNION) {
return mpack_decode_struct_union(self, size, type, path, is_key);
}
return ms_validation_error("object", type, path);
}
static PyObject *
mpack_decode_ext(
DecoderState *self, Py_ssize_t size, TypeNode *type, PathNode *path
) {
Py_buffer *buffer;
char c_code = 0, *data_buf = NULL;
long code;
PyObject *data, *pycode = NULL, *view = NULL, *out = NULL;
if (size < 0) return NULL;
if (mpack_read1(self, &c_code) < 0) return NULL;
code = *((int8_t *)(&c_code));
if (mpack_read(self, &data_buf, size) < 0) return NULL;
if (type->types & MS_TYPE_DATETIME && code == -1) {
return mpack_decode_datetime(self, data_buf, size, type, path);
}
else if (type->types & MS_TYPE_EXT) {
data = PyBytes_FromStringAndSize(data_buf, size);
if (data == NULL) return NULL;
return Ext_New(code, data);
}
else if (!(type->types & MS_TYPE_ANY)) {
return ms_validation_error("ext", type, path);
}
/* Decode Any.
* - datetime if code == -1
* - call ext_hook if available
* - otherwise return Ext object
* */
if (code == -1) {
return mpack_decode_datetime(self, data_buf, size, type, path);
}
else if (self->ext_hook == NULL) {
data = PyBytes_FromStringAndSize(data_buf, size);
if (data == NULL) return NULL;
return Ext_New(code, data);
}
else {
pycode = PyLong_FromLong(code);
if (pycode == NULL) goto done;
}
view = PyMemoryView_GetContiguous(self->buffer_obj, PyBUF_READ, 'C');
if (view == NULL) goto done;
buffer = PyMemoryView_GET_BUFFER(view);
buffer->buf = data_buf;
buffer->len = size;
out = PyObject_CallFunctionObjArgs(self->ext_hook, pycode, view, NULL);
done:
Py_XDECREF(pycode);
Py_XDECREF(view);
return out;
}
static MS_NOINLINE PyObject *
mpack_decode_raw(DecoderState *self) {
char *start = self->input_pos;
if (mpack_skip(self) < 0) return NULL;
Py_ssize_t size = self->input_pos - start;
return Raw_FromView(self->buffer_obj, start, size);
}
static MS_INLINE PyObject *
mpack_decode_nocustom(
DecoderState *self, TypeNode *type, PathNode *path, bool is_key
) {
char op = 0;
char *s = NULL;
if (mpack_read1(self, &op) < 0) {
return NULL;
}
if (('\x00' <= op && op <= '\x7f') || ('\xe0' <= op && op <= '\xff')) {
return ms_post_decode_int64(*((int8_t *)(&op)), type, path, self->strict, false);
}
else if ('\xa0' <= op && op <= '\xbf') {
return mpack_decode_str(self, op & 0x1f, type, path);
}
else if ('\x90' <= op && op <= '\x9f') {
return mpack_decode_array(self, op & 0x0f, type, path, is_key);
}
else if ('\x80' <= op && op <= '\x8f') {
return mpack_decode_map(self, op & 0x0f, type, path, is_key);
}
switch ((enum mpack_code)op) {
case MP_NIL:
return mpack_decode_none(self, type, path);
case MP_TRUE:
return mpack_decode_bool(self, Py_True, type, path);
case MP_FALSE:
return mpack_decode_bool(self, Py_False, type, path);
case MP_UINT8:
if (MS_UNLIKELY(mpack_read(self, &s, 1) < 0)) return NULL;
return ms_post_decode_uint64(*(uint8_t *)s, type, path, self->strict, false);
case MP_UINT16:
if (MS_UNLIKELY(mpack_read(self, &s, 2) < 0)) return NULL;
return ms_post_decode_uint64(_msgspec_load16(uint16_t, s), type, path, self->strict, false);
case MP_UINT32:
if (MS_UNLIKELY(mpack_read(self, &s, 4) < 0)) return NULL;
return ms_post_decode_uint64(_msgspec_load32(uint32_t, s), type, path, self->strict, false);
case MP_UINT64:
if (MS_UNLIKELY(mpack_read(self, &s, 8) < 0)) return NULL;
return ms_post_decode_uint64(_msgspec_load64(uint64_t, s), type, path, self->strict, false);
case MP_INT8:
if (MS_UNLIKELY(mpack_read(self, &s, 1) < 0)) return NULL;
return ms_post_decode_int64(*(int8_t *)s, type, path, self->strict, false);
case MP_INT16:
if (MS_UNLIKELY(mpack_read(self, &s, 2) < 0)) return NULL;
return ms_post_decode_int64(_msgspec_load16(int16_t, s), type, path, self->strict, false);
case MP_INT32:
if (MS_UNLIKELY(mpack_read(self, &s, 4) < 0)) return NULL;
return ms_post_decode_int64(_msgspec_load32(int32_t, s), type, path, self->strict, false);
case MP_INT64:
if (MS_UNLIKELY(mpack_read(self, &s, 8) < 0)) return NULL;
return ms_post_decode_int64(_msgspec_load64(int64_t, s), type, path, self->strict, false);
case MP_FLOAT32: {
float f = 0;
uint32_t uf;
if (mpack_read(self, &s, 4) < 0) return NULL;
uf = _msgspec_load32(uint32_t, s);
memcpy(&f, &uf, 4);
return mpack_decode_float(self, f, type, path);
}
case MP_FLOAT64: {
double f = 0;
uint64_t uf;
if (mpack_read(self, &s, 8) < 0) return NULL;
uf = _msgspec_load64(uint64_t, s);
memcpy(&f, &uf, 8);
return mpack_decode_float(self, f, type, path);
}
case MP_STR8: {
Py_ssize_t size = mpack_decode_size1(self);
if (MS_UNLIKELY(size < 0)) return NULL;
return mpack_decode_str(self, size, type, path);
}
case MP_STR16: {
Py_ssize_t size = mpack_decode_size2(self);
if (MS_UNLIKELY(size < 0)) return NULL;
return mpack_decode_str(self, size, type, path);
}
case MP_STR32: {
Py_ssize_t size = mpack_decode_size4(self);
if (MS_UNLIKELY(size < 0)) return NULL;
return mpack_decode_str(self, size, type, path);
}
case MP_BIN8:
return mpack_decode_bin(self, mpack_decode_size1(self), type, path);
case MP_BIN16:
return mpack_decode_bin(self, mpack_decode_size2(self), type, path);
case MP_BIN32:
return mpack_decode_bin(self, mpack_decode_size4(self), type, path);
case MP_ARRAY16: {
Py_ssize_t size = mpack_decode_size2(self);
if (MS_UNLIKELY(size < 0)) return NULL;
return mpack_decode_array(self, size, type, path, is_key);
}
case MP_ARRAY32: {
Py_ssize_t size = mpack_decode_size4(self);
if (MS_UNLIKELY(size < 0)) return NULL;
return mpack_decode_array(self, size, type, path, is_key);
}
case MP_MAP16: {
Py_ssize_t size = mpack_decode_size2(self);
if (MS_UNLIKELY(size < 0)) return NULL;
return mpack_decode_map(self, size, type, path, is_key);
}
case MP_MAP32: {
Py_ssize_t size = mpack_decode_size4(self);
if (MS_UNLIKELY(size < 0)) return NULL;
return mpack_decode_map(self, size, type, path, is_key);
}
case MP_FIXEXT1:
return mpack_decode_ext(self, 1, type, path);
case MP_FIXEXT2:
return mpack_decode_ext(self, 2, type, path);
case MP_FIXEXT4:
return mpack_decode_ext(self, 4, type, path);
case MP_FIXEXT8:
return mpack_decode_ext(self, 8, type, path);
case MP_FIXEXT16:
return mpack_decode_ext(self, 16, type, path);
case MP_EXT8:
return mpack_decode_ext(self, mpack_decode_size1(self), type, path);
case MP_EXT16:
return mpack_decode_ext(self, mpack_decode_size2(self), type, path);
case MP_EXT32:
return mpack_decode_ext(self, mpack_decode_size4(self), type, path);
default:
PyErr_Format(
msgspec_get_global_state()->DecodeError,
"MessagePack data is malformed: invalid opcode '\\x%02x' (byte %zd)",
(unsigned char)op,
(Py_ssize_t)(self->input_pos - self->input_start - 1)
);
return NULL;
}
}
static PyObject *
mpack_decode(
DecoderState *self, TypeNode *type, PathNode *path, bool is_key
) {
if (MS_UNLIKELY(type->types == 0)) {
return mpack_decode_raw(self);
}
PyObject *obj = mpack_decode_nocustom(self, type, path, is_key);
if (MS_UNLIKELY(type->types & (MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC))) {
return ms_decode_custom(obj, self->dec_hook, type, path);
}
return obj;
}
PyDoc_STRVAR(Decoder_decode__doc__,
"decode(self, buf)\n"
"--\n"
"\n"
"Deserialize an object from MessagePack.\n"
"\n"
"Parameters\n"
"----------\n"
"buf : bytes-like\n"
" The message to decode.\n"
"\n"
"Returns\n"
"-------\n"
"obj : Any\n"
" The deserialized object.\n"
);
static PyObject*
Decoder_decode(Decoder *self, PyObject *const *args, Py_ssize_t nargs)
{
if (!check_positional_nargs(nargs, 1, 1)) {
return NULL;
}
DecoderState state = {
.type = self->type,
.strict = self->strict,
.dec_hook = self->dec_hook,
.ext_hook = self->ext_hook
};
Py_buffer buffer;
buffer.buf = NULL;
if (PyObject_GetBuffer(args[0], &buffer, PyBUF_CONTIG_RO) >= 0) {
state.buffer_obj = args[0];
state.input_start = buffer.buf;
state.input_pos = buffer.buf;
state.input_end = state.input_pos + buffer.len;
PyObject *res = mpack_decode(&state, state.type, NULL, false);
if (res != NULL && mpack_has_trailing_characters(&state)) {
Py_CLEAR(res);
}
PyBuffer_Release(&buffer);
return res;
}
return NULL;
}
static struct PyMethodDef Decoder_methods[] = {
{
"decode", (PyCFunction) Decoder_decode, METH_FASTCALL,
Decoder_decode__doc__,
},
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS},
{NULL, NULL} /* sentinel */
};
static PyMemberDef Decoder_members[] = {
{"type", T_OBJECT_EX, offsetof(Decoder, orig_type), READONLY, "The Decoder type"},
{"strict", T_BOOL, offsetof(Decoder, strict), READONLY, "The Decoder strict setting"},
{"dec_hook", T_OBJECT, offsetof(Decoder, dec_hook), READONLY, "The Decoder dec_hook"},
{"ext_hook", T_OBJECT, offsetof(Decoder, ext_hook), READONLY, "The Decoder ext_hook"},
{NULL},
};
static PyTypeObject Decoder_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec.msgpack.Decoder",
.tp_doc = Decoder__doc__,
.tp_basicsize = sizeof(Decoder),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_new = PyType_GenericNew,
.tp_init = (initproc)Decoder_init,
.tp_traverse = (traverseproc)Decoder_traverse,
.tp_dealloc = (destructor)Decoder_dealloc,
.tp_repr = (reprfunc)Decoder_repr,
.tp_methods = Decoder_methods,
.tp_members = Decoder_members,
};
PyDoc_STRVAR(msgspec_msgpack_decode__doc__,
"msgpack_decode(buf, *, type='Any', strict=True, dec_hook=None, ext_hook=None)\n"
"--\n"
"\n"
"Deserialize an object from MessagePack.\n"
"\n"
"Parameters\n"
"----------\n"
"buf : bytes-like\n"
" The message to decode.\n"
"type : type, optional\n"
" A Python type (in type annotation form) to decode the object as. If\n"
" provided, the message will be type checked and decoded as the specified\n"
" type. Defaults to `Any`, in which case the message will be decoded using\n"
" the default MessagePack types.\n"
"strict : bool, optional\n"
" Whether type coercion rules should be strict. Setting to False enables a\n"
" wider set of coercion rules from string to non-string types for all values.\n"
" Default is True.\n"
"dec_hook : callable, optional\n"
" An optional callback for handling decoding custom types. Should have the\n"
" signature ``dec_hook(type: Type, obj: Any) -> Any``, where ``type`` is the\n"
" expected message type, and ``obj`` is the decoded representation composed\n"
" of only basic MessagePack types. This hook should transform ``obj`` into\n"
" type ``type``, or raise a ``NotImplementedError`` if unsupported.\n"
"ext_hook : callable, optional\n"
" An optional callback for decoding MessagePack extensions. Should have the\n"
" signature ``ext_hook(code: int, data: memoryview) -> Any``. If provided,\n"
" this will be called to deserialize all extension types found in the\n"
" message. Note that ``data`` is a memoryview into the larger message\n"
" buffer - any references created to the underlying buffer without copying\n"
" the data out will cause the full message buffer to persist in memory.\n"
" If not provided, extension types will decode as ``msgspec.Ext`` objects.\n"
"\n"
"Returns\n"
"-------\n"
"obj : Any\n"
" The deserialized object.\n"
"\n"
"See Also\n"
"--------\n"
"Decoder.decode"
);
static PyObject*
msgspec_msgpack_decode(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *res = NULL, *buf = NULL, *type = NULL, *strict_obj = NULL;
PyObject *dec_hook = NULL, *ext_hook = NULL;
MsgspecState *mod = msgspec_get_state(self);
int strict = 1;
/* Parse arguments */
if (!check_positional_nargs(nargs, 1, 1)) return NULL;
buf = args[0];
if (kwnames != NULL) {
Py_ssize_t nkwargs = PyTuple_GET_SIZE(kwnames);
if ((type = find_keyword(kwnames, args + nargs, mod->str_type)) != NULL) nkwargs--;
if ((strict_obj = find_keyword(kwnames, args + nargs, mod->str_strict)) != NULL) nkwargs--;
if ((dec_hook = find_keyword(kwnames, args + nargs, mod->str_dec_hook)) != NULL) nkwargs--;
if ((ext_hook = find_keyword(kwnames, args + nargs, mod->str_ext_hook)) != NULL) nkwargs--;
if (nkwargs > 0) {
PyErr_SetString(
PyExc_TypeError,
"Extra keyword arguments provided"
);
return NULL;
}
}
/* Handle strict */
if (strict_obj != NULL) {
strict = PyObject_IsTrue(strict_obj);
if (strict < 0) return NULL;
}
/* Handle dec_hook */
if (dec_hook == Py_None) {
dec_hook = NULL;
}
if (dec_hook != NULL) {
if (!PyCallable_Check(dec_hook)) {
PyErr_SetString(PyExc_TypeError, "dec_hook must be callable");
return NULL;
}
}
/* Handle ext_hook */
if (ext_hook == Py_None) {
ext_hook = NULL;
}
if (ext_hook != NULL) {
if (!PyCallable_Check(ext_hook)) {
PyErr_SetString(PyExc_TypeError, "ext_hook must be callable");
return NULL;
}
}
DecoderState state = {
.strict = strict,
.dec_hook = dec_hook,
.ext_hook = ext_hook
};
/* Allocate Any & Struct type nodes (simple, common cases) on the stack,
* everything else on the heap */
TypeNode typenode_any = {MS_TYPE_ANY};
TypeNodeSimple typenode_struct;
if (type == NULL || type == mod->typing_any) {
state.type = &typenode_any;
}
else if (Py_TYPE(type) == &StructMetaType) {
PyObject *info = StructInfo_Convert(type);
if (info == NULL) return NULL;
bool array_like = ((StructMetaObject *)type)->array_like == OPT_TRUE;
typenode_struct.types = array_like ? MS_TYPE_STRUCT_ARRAY : MS_TYPE_STRUCT;
typenode_struct.details[0].pointer = info;
state.type = (TypeNode *)(&typenode_struct);
}
else {
state.type = TypeNode_Convert(type);
if (state.type == NULL) return NULL;
}
Py_buffer buffer;
buffer.buf = NULL;
if (PyObject_GetBuffer(buf, &buffer, PyBUF_CONTIG_RO) >= 0) {
state.buffer_obj = buf;
state.input_start = buffer.buf;
state.input_pos = buffer.buf;
state.input_end = state.input_pos + buffer.len;
res = mpack_decode(&state, state.type, NULL, false);
PyBuffer_Release(&buffer);
if (res != NULL && mpack_has_trailing_characters(&state)) {
Py_CLEAR(res);
}
}
if (state.type == (TypeNode *)&typenode_struct) {
Py_DECREF(typenode_struct.details[0].pointer);
}
else if (state.type != &typenode_any) {
TypeNode_Free(state.type);
}
return res;
}
/*************************************************************************
* JSON Decoder *
*************************************************************************/
typedef struct JSONDecoderState {
/* Configuration */
TypeNode *type;
PyObject *dec_hook;
PyObject *float_hook;
bool strict;
/* Temporary scratch space */
unsigned char *scratch;
Py_ssize_t scratch_capacity;
Py_ssize_t scratch_len;
/* Per-message attributes */
PyObject *buffer_obj;
unsigned char *input_start;
unsigned char *input_pos;
unsigned char *input_end;
} JSONDecoderState;
typedef struct JSONDecoder {
PyObject_HEAD
PyObject *orig_type;
/* Configuration */
TypeNode *type;
char strict;
PyObject *dec_hook;
PyObject *float_hook;
} JSONDecoder;
PyDoc_STRVAR(JSONDecoder__doc__,
"Decoder(type='Any', *, strict=True, dec_hook=None, float_hook=None)\n"
"--\n"
"\n"
"A JSON decoder.\n"
"\n"
"Parameters\n"
"----------\n"
"type : type, optional\n"
" A Python type (in type annotation form) to decode the object as. If\n"
" provided, the message will be type checked and decoded as the specified\n"
" type. Defaults to `Any`, in which case the message will be decoded using\n"
" the default JSON types.\n"
"strict : bool, optional\n"
" Whether type coercion rules should be strict. Setting to False enables a\n"
" wider set of coercion rules from string to non-string types for all values.\n"
" Default is True.\n"
"dec_hook : callable, optional\n"
" An optional callback for handling decoding custom types. Should have the\n"
" signature ``dec_hook(type: Type, obj: Any) -> Any``, where ``type`` is the\n"
" expected message type, and ``obj`` is the decoded representation composed\n"
" of only basic JSON types. This hook should transform ``obj`` into type\n"
" ``type``, or raise a ``NotImplementedError`` if unsupported.\n"
"float_hook : callable, optional\n"
" An optional callback for handling decoding untyped float literals. Should\n"
" have the signature ``float_hook(val: str) -> Any``, where ``val`` is the\n"
" raw string value of the JSON float. This hook is called to decode any\n"
" \"untyped\" float value (e.g. ``typing.Any`` typed). The default is\n"
" equivalent to ``float_hook=float``, where all untyped JSON floats are\n"
" decoded as python floats. Specifying ``float_hook=decimal.Decimal``\n"
" will decode all untyped JSON floats as decimals instead."
);
static int
JSONDecoder_init(JSONDecoder *self, PyObject *args, PyObject *kwds)
{
char *kwlist[] = {"type", "strict", "dec_hook", "float_hook", NULL};
MsgspecState *st = msgspec_get_global_state();
PyObject *type = st->typing_any;
PyObject *dec_hook = NULL;
PyObject *float_hook = NULL;
int strict = 1;
if (!PyArg_ParseTupleAndKeywords(
args, kwds, "|O$pOO", kwlist, &type, &strict, &dec_hook, &float_hook)
) {
return -1;
}
/* Handle dec_hook */
if (dec_hook == Py_None) {
dec_hook = NULL;
}
if (dec_hook != NULL) {
if (!PyCallable_Check(dec_hook)) {
PyErr_SetString(PyExc_TypeError, "dec_hook must be callable");
return -1;
}
Py_INCREF(dec_hook);
}
self->dec_hook = dec_hook;
/* Handle float_hook */
if (float_hook == Py_None) {
float_hook = NULL;
}
if (float_hook != NULL) {
if (!PyCallable_Check(float_hook)) {
PyErr_SetString(PyExc_TypeError, "float_hook must be callable");
return -1;
}
Py_INCREF(float_hook);
}
self->float_hook = float_hook;
/* Handle strict */
self->strict = strict;
/* Handle type */
self->type = TypeNode_Convert(type);
if (self->type == NULL) return -1;
Py_INCREF(type);
self->orig_type = type;
return 0;
}
static int
JSONDecoder_traverse(JSONDecoder *self, visitproc visit, void *arg)
{
int out = TypeNode_traverse(self->type, visit, arg);
if (out != 0) return out;
Py_VISIT(self->orig_type);
Py_VISIT(self->dec_hook);
Py_VISIT(self->float_hook);
return 0;
}
static void
JSONDecoder_dealloc(JSONDecoder *self)
{
PyObject_GC_UnTrack(self);
TypeNode_Free(self->type);
Py_XDECREF(self->orig_type);
Py_XDECREF(self->dec_hook);
Py_XDECREF(self->float_hook);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
JSONDecoder_repr(JSONDecoder *self) {
int recursive;
PyObject *typstr, *out = NULL;
recursive = Py_ReprEnter((PyObject *)self);
if (recursive != 0) {
return (recursive < 0) ? NULL : PyUnicode_FromString("..."); /* cpylint-ignore */
}
typstr = PyObject_Repr(self->orig_type);
if (typstr != NULL) {
out = PyUnicode_FromFormat("msgspec.json.Decoder(%U)", typstr);
}
Py_XDECREF(typstr);
Py_ReprLeave((PyObject *)self);
return out;
}
static MS_INLINE bool
json_read1(JSONDecoderState *self, unsigned char *c)
{
if (MS_UNLIKELY(self->input_pos == self->input_end)) {
ms_err_truncated();
return false;
}
*c = *self->input_pos;
self->input_pos += 1;
return true;
}
static MS_INLINE char
json_peek_or_null(JSONDecoderState *self) {
if (MS_UNLIKELY(self->input_pos == self->input_end)) return '\0';
return *self->input_pos;
}
static MS_INLINE bool
json_peek_skip_ws(JSONDecoderState *self, unsigned char *s)
{
while (true) {
if (MS_UNLIKELY(self->input_pos == self->input_end)) {
ms_err_truncated();
return false;
}
unsigned char c = *self->input_pos;
if (MS_LIKELY(c != ' ' && c != '\n' && c != '\r' && c != '\t')) {
*s = c;
return true;
}
self->input_pos++;
}
}
static MS_INLINE bool
json_remaining(JSONDecoderState *self, ptrdiff_t remaining)
{
return self->input_end - self->input_pos >= remaining;
}
static PyObject *
json_err_invalid(JSONDecoderState *self, const char *msg)
{
PyErr_Format(
msgspec_get_global_state()->DecodeError,
"JSON is malformed: %s (byte %zd)",
msg,
(Py_ssize_t)(self->input_pos - self->input_start)
);
return NULL;
}
static MS_INLINE bool
json_has_trailing_characters(JSONDecoderState *self)
{
while (self->input_pos != self->input_end) {
unsigned char c = *self->input_pos++;
if (MS_UNLIKELY(!(c == ' ' || c == '\n' || c == '\t' || c == '\r'))) {
json_err_invalid(self, "trailing characters");
return true;
}
}
return false;
}
static int json_skip(JSONDecoderState *self);
static PyObject * json_decode(
JSONDecoderState *self, TypeNode *type, PathNode *path
);
static PyObject *
json_decode_none(JSONDecoderState *self, TypeNode *type, PathNode *path) {
self->input_pos++; /* Already checked as 'n' */
if (MS_UNLIKELY(!json_remaining(self, 3))) {
ms_err_truncated();
return NULL;
}
unsigned char c1 = *self->input_pos++;
unsigned char c2 = *self->input_pos++;
unsigned char c3 = *self->input_pos++;
if (MS_UNLIKELY(c1 != 'u' || c2 != 'l' || c3 != 'l')) {
return json_err_invalid(self, "invalid character");
}
if (type->types & (MS_TYPE_ANY | MS_TYPE_NONE)) {
Py_INCREF(Py_None);
return Py_None;
}
return ms_validation_error("null", type, path);
}
static PyObject *
json_decode_true(JSONDecoderState *self, TypeNode *type, PathNode *path) {
self->input_pos++; /* Already checked as 't' */
if (MS_UNLIKELY(!json_remaining(self, 3))) {
ms_err_truncated();
return NULL;
}
unsigned char c1 = *self->input_pos++;
unsigned char c2 = *self->input_pos++;
unsigned char c3 = *self->input_pos++;
if (MS_UNLIKELY(c1 != 'r' || c2 != 'u' || c3 != 'e')) {
return json_err_invalid(self, "invalid character");
}
if (type->types & (MS_TYPE_ANY | MS_TYPE_BOOL)) {
Py_INCREF(Py_True);
return Py_True;
}
return ms_validation_error("bool", type, path);
}
static PyObject *
json_decode_false(JSONDecoderState *self, TypeNode *type, PathNode *path) {
self->input_pos++; /* Already checked as 'f' */
if (MS_UNLIKELY(!json_remaining(self, 4))) {
ms_err_truncated();
return NULL;
}
unsigned char c1 = *self->input_pos++;
unsigned char c2 = *self->input_pos++;
unsigned char c3 = *self->input_pos++;
unsigned char c4 = *self->input_pos++;
if (MS_UNLIKELY(c1 != 'a' || c2 != 'l' || c3 != 's' || c4 != 'e')) {
return json_err_invalid(self, "invalid character");
}
if (type->types & (MS_TYPE_ANY | MS_TYPE_BOOL)) {
Py_INCREF(Py_False);
return Py_False;
}
return ms_validation_error("bool", type, path);
}
#define JS_SCRATCH_MAX_SIZE 1024
static int
json_scratch_resize(JSONDecoderState *state, Py_ssize_t size) {
unsigned char *temp = PyMem_Realloc(state->scratch, size);
if (MS_UNLIKELY(temp == NULL)) {
PyErr_NoMemory();
return -1;
}
state->scratch = temp;
state->scratch_capacity = size;
return 0;
}
static MS_NOINLINE int
json_scratch_expand(JSONDecoderState *state, Py_ssize_t required) {
size_t new_size = Py_MAX(8, 1.5 * required);
return json_scratch_resize(state, new_size);
}
static int
json_scratch_extend(JSONDecoderState *state, const void *buf, Py_ssize_t size) {
Py_ssize_t required = state->scratch_len + size;
if (MS_UNLIKELY(required >= state->scratch_capacity)) {
if (MS_UNLIKELY(json_scratch_expand(state, required) < 0)) return -1;
}
memcpy(state->scratch + state->scratch_len, buf, size);
state->scratch_len += size;
return 0;
}
/* -1: '\', '"', and forbidden characters
* 0: ascii
* 1: non-ascii */
static const int8_t char_types[256] = {
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
0, 0, -1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
};
/* Is char `"`, `\`, or nonascii? */
static MS_INLINE bool char_is_special_or_nonascii(unsigned char c) {
return char_types[c] != 0;
}
/* Is char `"` or `\`? */
static MS_INLINE bool char_is_special(unsigned char c) {
return char_types[c] < 0;
}
static int
json_read_codepoint(JSONDecoderState *self, unsigned int *out) {
unsigned char c;
unsigned int cp = 0;
if (!json_remaining(self, 4)) return ms_err_truncated();
for (int i = 0; i < 4; i++) {
c = *self->input_pos++;
if (c >= '0' && c <= '9') {
c -= '0';
}
else if (c >= 'a' && c <= 'f') {
c = c - 'a' + 10;
}
else if (c >= 'A' && c <= 'F') {
c = c - 'A' + 10;
}
else {
json_err_invalid(self, "invalid character in unicode escape");
return -1;
}
cp = (cp << 4) + c;
}
*out = cp;
return 0;
}
static MS_NOINLINE int
json_handle_unicode_escape(JSONDecoderState *self) {
unsigned int cp;
if (json_read_codepoint(self, &cp) < 0) return -1;
if (0xDC00 <= cp && cp <= 0xDFFF) {
json_err_invalid(self, "invalid utf-16 surrogate pair");
return -1;
}
else if (0xD800 <= cp && cp <= 0xDBFF) {
/* utf-16 pair, parse 2nd pair */
unsigned int cp2;
if (!json_remaining(self, 6)) return ms_err_truncated();
if (self->input_pos[0] != '\\' || self->input_pos[1] != 'u') {
json_err_invalid(self, "unexpected end of escaped utf-16 surrogate pair");
return -1;
}
self->input_pos += 2;
if (json_read_codepoint(self, &cp2) < 0) return -1;
if (cp2 < 0xDC00 || cp2 > 0xDFFF) {
json_err_invalid(self, "invalid utf-16 surrogate pair");
return -1;
}
cp = 0x10000 + (((cp - 0xD800) << 10) | (cp2 - 0xDC00));
}
/* Encode the codepoint as utf-8 */
unsigned char *p = self->scratch + self->scratch_len;
if (cp < 0x80) {
*p++ = cp;
self->scratch_len += 1;
} else if (cp < 0x800) {
*p++ = 0xC0 | (cp >> 6);
*p++ = 0x80 | (cp & 0x3F);
self->scratch_len += 2;
} else if (cp < 0x10000) {
*p++ = 0xE0 | (cp >> 12);
*p++ = 0x80 | ((cp >> 6) & 0x3F);
*p++ = 0x80 | (cp & 0x3F);
self->scratch_len += 3;
} else {
*p++ = 0xF0 | (cp >> 18);
*p++ = 0x80 | ((cp >> 12) & 0x3F);
*p++ = 0x80 | ((cp >> 6) & 0x3F);
*p++ = 0x80 | (cp & 0x3F);
self->scratch_len += 4;
}
return 0;
}
#define parse_ascii_pre(i) \
if (MS_UNLIKELY(char_is_special_or_nonascii(self->input_pos[i]))) goto parse_ascii_##i;
#define parse_ascii_post(i) \
parse_ascii_##i: \
self->input_pos += i; \
goto parse_ascii_end;
#define parse_unicode_pre(i) \
if (MS_UNLIKELY(char_is_special(self->input_pos[i]))) goto parse_unicode_##i;
#define parse_unicode_post(i) \
parse_unicode_##i: \
self->input_pos += i; \
goto parse_unicode_end;
static MS_NOINLINE Py_ssize_t
json_decode_string_view_copy(
JSONDecoderState *self, char **out, bool *is_ascii, unsigned char *start
) {
unsigned char c;
self->scratch_len = 0;
top:
OPT_FORCE_RELOAD(*self->input_pos);
c = *self->input_pos;
if (c == '\\') {
/* Write the current block to scratch */
Py_ssize_t block_size = self->input_pos - start;
/* An escape string requires at most 4 bytes to decode */
Py_ssize_t required = self->scratch_len + block_size + 4;
if (MS_UNLIKELY(required >= self->scratch_capacity)) {
if (MS_UNLIKELY(json_scratch_expand(self, required) < 0)) return -1;
}
memcpy(self->scratch + self->scratch_len, start, block_size);
self->scratch_len += block_size;
self->input_pos++;
if (!json_read1(self, &c)) return -1;
switch (c) {
case 'n': {
*(self->scratch + self->scratch_len) = '\n';
self->scratch_len++;
break;
}
case '"': {
*(self->scratch + self->scratch_len) = '"';
self->scratch_len++;
break;
}
case 't': {
*(self->scratch + self->scratch_len) = '\t';
self->scratch_len++;
break;
}
case 'r': {
*(self->scratch + self->scratch_len) = '\r';
self->scratch_len++;
break;
}
case '\\': {
*(self->scratch + self->scratch_len) = '\\';
self->scratch_len++;
break;
}
case '/': {
*(self->scratch + self->scratch_len) = '/';
self->scratch_len++;
break;
}
case 'b': {
*(self->scratch + self->scratch_len) = '\b';
self->scratch_len++;
break;
}
case 'f': {
*(self->scratch + self->scratch_len) = '\f';
self->scratch_len++;
break;
}
case 'u': {
*is_ascii = false;
if (json_handle_unicode_escape(self) < 0) return -1;
break;
}
default:
json_err_invalid(self, "invalid escape character in string");
return -1;
}
start = self->input_pos;
}
else if (c == '"') {
if (json_scratch_extend(self, start, self->input_pos - start) < 0) return -1;
self->input_pos++;
*out = (char *)(self->scratch);
return self->scratch_len;
}
else {
json_err_invalid(self, "invalid character");
return -1;
}
/* Loop until `"`, `\`, or a non-ascii character */
while (self->input_end - self->input_pos >= 8) {
repeat8(parse_ascii_pre);
self->input_pos += 8;
continue;
repeat8(parse_ascii_post);
}
while (true) {
if (MS_UNLIKELY(self->input_pos == self->input_end)) return ms_err_truncated();
if (MS_UNLIKELY(char_is_special_or_nonascii(*self->input_pos))) break;
self->input_pos++;
}
parse_ascii_end:
OPT_FORCE_RELOAD(*self->input_pos);
if (MS_UNLIKELY(*self->input_pos & 0x80)) {
*is_ascii = false;
/* Loop until `"` or `\` */
while (self->input_end - self->input_pos >= 8) {
repeat8(parse_unicode_pre);
self->input_pos += 8;
continue;
repeat8(parse_unicode_post);
}
while (true) {
if (MS_UNLIKELY(self->input_pos == self->input_end)) return ms_err_truncated();
if (MS_UNLIKELY(char_is_special(*self->input_pos))) break;
self->input_pos++;
}
}
parse_unicode_end:
goto top;
}
static Py_ssize_t
json_decode_string_view(JSONDecoderState *self, char **out, bool *is_ascii) {
self->input_pos++; /* Skip '"' */
unsigned char *start = self->input_pos;
/* Loop until `"`, `\`, or a non-ascii character */
while (self->input_end - self->input_pos >= 8) {
repeat8(parse_ascii_pre);
self->input_pos += 8;
continue;
repeat8(parse_ascii_post);
}
while (true) {
if (MS_UNLIKELY(self->input_pos == self->input_end)) return ms_err_truncated();
if (MS_UNLIKELY(char_is_special_or_nonascii(*self->input_pos))) break;
self->input_pos++;
}
parse_ascii_end:
OPT_FORCE_RELOAD(*self->input_pos);
if (MS_LIKELY(*self->input_pos == '"')) {
Py_ssize_t size = self->input_pos - start;
self->input_pos++;
*out = (char *)start;
return size;
}
if (MS_UNLIKELY(*self->input_pos & 0x80)) {
*is_ascii = false;
/* Loop until `"` or `\` */
while (self->input_end - self->input_pos >= 8) {
repeat8(parse_unicode_pre);
self->input_pos += 8;
continue;
repeat8(parse_unicode_post);
}
while (true) {
if (MS_UNLIKELY(self->input_pos == self->input_end)) return ms_err_truncated();
if (MS_UNLIKELY(char_is_special(*self->input_pos))) break;
self->input_pos++;
}
}
parse_unicode_end:
OPT_FORCE_RELOAD(*self->input_pos);
if (MS_LIKELY(*self->input_pos == '"')) {
Py_ssize_t size = self->input_pos - start;
self->input_pos++;
*out = (char *)start;
return size;
}
return json_decode_string_view_copy(self, out, is_ascii, start);
}
static int
json_skip_string(JSONDecoderState *self) {
self->input_pos++; /* Skip '"' */
parse_unicode:
/* Loop until `"` or `\` */
while (self->input_end - self->input_pos >= 8) {
repeat8(parse_unicode_pre);
self->input_pos += 8;
continue;
repeat8(parse_unicode_post);
}
while (true) {
if (MS_UNLIKELY(self->input_pos == self->input_end)) return ms_err_truncated();
if (MS_UNLIKELY(char_is_special(*self->input_pos))) break;
self->input_pos++;
}
parse_unicode_end:
OPT_FORCE_RELOAD(*self->input_pos);
if (MS_LIKELY(*self->input_pos == '"')) {
self->input_pos++;
return 0;
}
else if (*self->input_pos == '\\') {
self->input_pos++;
if (MS_UNLIKELY(self->input_pos == self->input_end)) return ms_err_truncated();
switch (*self->input_pos) {
case '"':
case '\\':
case '/':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
self->input_pos++;
break;
case 'u': {
self->input_pos++;
unsigned int cp;
if (json_read_codepoint(self, &cp) < 0) return -1;
if (0xDC00 <= cp && cp <= 0xDFFF) {
json_err_invalid(self, "invalid utf-16 surrogate pair");
return -1;
}
else if (0xD800 <= cp && cp <= 0xDBFF) {
/* utf-16 pair, parse 2nd pair */
unsigned int cp2;
if (!json_remaining(self, 6)) return ms_err_truncated();
if (self->input_pos[0] != '\\' || self->input_pos[1] != 'u') {
json_err_invalid(self, "unexpected end of hex escape");
return -1;
}
self->input_pos += 2;
if (json_read_codepoint(self, &cp2) < 0) return -1;
if (cp2 < 0xDC00 || cp2 > 0xDFFF) {
json_err_invalid(self, "invalid utf-16 surrogate pair");
return -1;
}
cp = 0x10000 + (((cp - 0xD800) << 10) | (cp2 - 0xDC00));
}
break;
}
default: {
json_err_invalid(self, "invalid escaped character");
return -1;
}
}
goto parse_unicode;
}
else {
json_err_invalid(self, "invalid character");
return -1;
}
}
#undef parse_ascii_pre
#undef parse_ascii_post
#undef parse_unicode_pre
#undef parse_unicode_post
/* A table of the corresponding base64 value for each character, or -1 if an
* invalid character in the base64 alphabet (note the padding char '=' is
* handled elsewhere, so is marked as invalid here as well) */
static const uint8_t base64_decode_table[] = {
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1,
-1, 0, 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,-1, -1,-1,-1,-1,
-1,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,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
};
static PyObject *
json_decode_binary(
const char *buffer, Py_ssize_t size, TypeNode *type, PathNode *path
) {
PyObject *out = NULL;
char *bin_buffer;
Py_ssize_t bin_size, i;
if (size % 4 != 0) goto invalid;
int npad = 0;
if (size > 0 && buffer[size - 1] == '=') npad++;
if (size > 1 && buffer[size - 2] == '=') npad++;
bin_size = (size / 4) * 3 - npad;
if (!ms_passes_bytes_constraints(bin_size, type, path)) return NULL;
if (type->types & MS_TYPE_BYTES) {
out = PyBytes_FromStringAndSize(NULL, bin_size);
if (out == NULL) return NULL;
bin_buffer = PyBytes_AS_STRING(out);
}
else if (type->types & MS_TYPE_BYTEARRAY) {
out = PyByteArray_FromStringAndSize(NULL, bin_size);
if (out == NULL) return NULL;
bin_buffer = PyByteArray_AS_STRING(out);
}
else {
PyObject *temp = PyBytes_FromStringAndSize(NULL, bin_size);
if (temp == NULL) return NULL;
bin_buffer = PyBytes_AS_STRING(temp);
out = PyMemoryView_FromObject(temp);
Py_DECREF(temp);
if (out == NULL) return NULL;
}
int quad = 0;
uint8_t left_c = 0;
for (i = 0; i < size - npad; i++) {
uint8_t c = base64_decode_table[(uint8_t)(buffer[i])];
if (c >= 64) goto invalid;
switch (quad) {
case 0:
quad = 1;
left_c = c;
break;
case 1:
quad = 2;
*bin_buffer++ = (left_c << 2) | (c >> 4);
left_c = c & 0x0f;
break;
case 2:
quad = 3;
*bin_buffer++ = (left_c << 4) | (c >> 2);
left_c = c & 0x03;
break;
case 3:
quad = 0;
*bin_buffer++ = (left_c << 6) | c;
left_c = 0;
break;
}
}
return out;
invalid:
Py_XDECREF(out);
return ms_error_with_path("Invalid base64 encoded string%U", path);
}
static PyObject *
json_decode_string(JSONDecoderState *self, TypeNode *type, PathNode *path) {
char *view = NULL;
bool is_ascii = true;
Py_ssize_t size = json_decode_string_view(self, &view, &is_ascii);
if (size < 0) return NULL;
if (MS_LIKELY(type->types & (MS_TYPE_STR | MS_TYPE_ANY))) {
PyObject *out;
if (MS_LIKELY(is_ascii)) {
out = PyUnicode_New(size, 127);
memcpy(ascii_get_buffer(out), view, size);
}
else {
out = PyUnicode_DecodeUTF8(view, size, NULL);
}
return ms_check_str_constraints(out, type, path);
}
else if (MS_UNLIKELY(!self->strict)) {
bool invalid = false;
PyObject *out = ms_decode_str_lax(view, size, type, path, &invalid);
if (!invalid) return out;
}
if (MS_UNLIKELY(type->types & MS_TYPE_DATETIME)) {
return ms_decode_datetime_from_str(view, size, type, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_DATE)) {
return ms_decode_date(view, size, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_TIME)) {
return ms_decode_time(view, size, type, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_TIMEDELTA)) {
return ms_decode_timedelta(view, size, type, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_UUID)) {
return ms_decode_uuid_from_str(view, size, path);
}
else if (MS_UNLIKELY(type->types & MS_TYPE_DECIMAL)) {
return ms_decode_decimal(view, size, is_ascii, path, NULL);
}
else if (
MS_UNLIKELY(type->types &
(MS_TYPE_BYTES | MS_TYPE_BYTEARRAY | MS_TYPE_MEMORYVIEW)
)
) {
return json_decode_binary(view, size, type, path);
}
else if (MS_UNLIKELY(type->types & (MS_TYPE_ENUM | MS_TYPE_STRLITERAL))) {
return ms_decode_str_enum_or_literal(view, size, type, path);
}
return ms_validation_error("str", type, path);
}
static PyObject *
json_decode_dict_key_fallback(
JSONDecoderState *self,
const char *view, Py_ssize_t size, bool is_ascii, TypeNode *type, PathNode *path
) {
if (type->types & (MS_TYPE_STR | MS_TYPE_ANY)) {
PyObject *out;
if (is_ascii) {
out = PyUnicode_New(size, 127);
if (MS_UNLIKELY(out == NULL)) return NULL;
memcpy(ascii_get_buffer(out), view, size);
}
else {
out = PyUnicode_DecodeUTF8(view, size, NULL);
}
if (MS_UNLIKELY(type->types & (MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC))) {
return ms_decode_custom(out, self->dec_hook, type, path);
}
return ms_check_str_constraints(out, type, path);
}
if (type->types & (
MS_TYPE_INT | MS_TYPE_INTENUM | MS_TYPE_INTLITERAL |
MS_TYPE_FLOAT | MS_TYPE_DECIMAL |
((!self->strict) * (MS_TYPE_DATETIME | MS_TYPE_TIMEDELTA))
)
) {
PyObject *out;
if (maybe_parse_number(view, size, type, path, self->strict, &out)) {
return out;
}
}
if (type->types & (MS_TYPE_ENUM | MS_TYPE_STRLITERAL)) {
return ms_decode_str_enum_or_literal(view, size, type, path);
}
else if (type->types & MS_TYPE_UUID) {
return ms_decode_uuid_from_str(view, size, path);
}
else if (type->types & MS_TYPE_DATETIME) {
return ms_decode_datetime_from_str(view, size, type, path);
}
else if (type->types & MS_TYPE_DATE) {
return ms_decode_date(view, size, path);
}
else if (type->types & MS_TYPE_TIME) {
return ms_decode_time(view, size, type, path);
}
else if (type->types & MS_TYPE_TIMEDELTA) {
return ms_decode_timedelta(view, size, type, path);
}
else if (type->types & (MS_TYPE_BYTES | MS_TYPE_MEMORYVIEW)) {
return json_decode_binary(view, size, type, path);
}
else {
return ms_validation_error("str", type, path);
}
}
static PyObject *
json_decode_dict_key(JSONDecoderState *self, TypeNode *type, PathNode *path) {
bool is_ascii = true;
char *view = NULL;
Py_ssize_t size;
bool is_str = type->types == MS_TYPE_ANY || type->types == MS_TYPE_STR;
size = json_decode_string_view(self, &view, &is_ascii);
if (size < 0) return NULL;
bool cacheable = is_str && is_ascii && size > 0 && size <= STRING_CACHE_MAX_STRING_LENGTH;
if (MS_UNLIKELY(!cacheable)) {
return json_decode_dict_key_fallback(self, view, size, is_ascii, type, path);
}
uint32_t hash = murmur2(view, size);
uint32_t index = hash % STRING_CACHE_SIZE;
PyObject *existing = string_cache[index];
if (MS_LIKELY(existing != NULL)) {
Py_ssize_t e_size = ((PyASCIIObject *)existing)->length;
char *e_str = ascii_get_buffer(existing);
if (MS_LIKELY(size == e_size && memcmp(view, e_str, size) == 0)) {
Py_INCREF(existing);
return existing;
}
}
/* Create a new ASCII str object */
PyObject *new = PyUnicode_New(size, 127);
if (MS_UNLIKELY(new == NULL)) return NULL;
memcpy(ascii_get_buffer(new), view, size);
/* Swap out the str in the cache */
Py_XDECREF(existing);
Py_INCREF(new);
string_cache[index] = new;
return new;
}
static PyObject *
json_decode_list(JSONDecoderState *self, TypeNode *type, TypeNode *el_type, PathNode *path) {
unsigned char c;
bool first = true;
PathNode el_path = {path, 0, NULL};
self->input_pos++; /* Skip '[' */
PyObject *out = PyList_New(0);
if (out == NULL) return NULL;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
while (true) {
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
/* Parse ']' or ',', then peek the next character */
if (c == ']') {
self->input_pos++;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
}
else if (first) {
/* Only the first item doesn't need a comma delimiter */
first = false;
}
else {
json_err_invalid(self, "expected ',' or ']'");
goto error;
}
if (MS_UNLIKELY(c == ']')) {
json_err_invalid(self, "trailing comma in array");
goto error;
}
/* Parse item */
PyObject *item = json_decode(self, el_type, &el_path);
if (item == NULL) goto error;
el_path.index++;
/* Append item to list */
if (MS_LIKELY((LIST_CAPACITY(out) > Py_SIZE(out)))) {
PyList_SET_ITEM(out, Py_SIZE(out), item);
Py_SET_SIZE(out, Py_SIZE(out) + 1);
}
else {
int status = PyList_Append(out, item);
Py_DECREF(item);
if (MS_UNLIKELY(status < 0)) goto error;
}
}
if (MS_UNLIKELY(!ms_passes_array_constraints(PyList_GET_SIZE(out), type, path))) {
goto error;
}
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_DECREF(out);
return NULL;
}
static PyObject *
json_decode_set(
JSONDecoderState *self, TypeNode *type, TypeNode *el_type, PathNode *path
) {
PyObject *out, *item = NULL;
unsigned char c;
bool first = true;
PathNode el_path = {path, 0, NULL};
self->input_pos++; /* Skip '[' */
out = (type->types & MS_TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL);
if (out == NULL) return NULL;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
while (true) {
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
/* Parse ']' or ',', then peek the next character */
if (c == ']') {
self->input_pos++;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
}
else if (first) {
/* Only the first item doesn't need a comma delimiter */
first = false;
}
else {
json_err_invalid(self, "expected ',' or ']'");
goto error;
}
if (MS_UNLIKELY(c == ']')) {
json_err_invalid(self, "trailing comma in array");
goto error;
}
/* Parse item */
item = json_decode(self, el_type, &el_path);
if (item == NULL) goto error;
el_path.index++;
/* Append item to set */
if (PySet_Add(out, item) < 0) goto error;
Py_CLEAR(item);
}
if (MS_UNLIKELY(!ms_passes_array_constraints(PySet_GET_SIZE(out), type, path))) {
goto error;
}
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_DECREF(out);
Py_XDECREF(item);
return NULL;
}
static PyObject *
json_decode_vartuple(JSONDecoderState *self, TypeNode *type, TypeNode *el_type, PathNode *path) {
PyObject *list, *item, *out = NULL;
Py_ssize_t size, i;
list = json_decode_list(self, type, el_type, path);
if (list == NULL) return NULL;
size = PyList_GET_SIZE(list);
out = PyTuple_New(size);
if (out != NULL) {
for (i = 0; i < size; i++) {
item = PyList_GET_ITEM(list, i);
PyTuple_SET_ITEM(out, i, item);
PyList_SET_ITEM(list, i, NULL); /* Drop reference in old list */
}
}
Py_DECREF(list);
return out;
}
static PyObject *
json_decode_fixtuple(JSONDecoderState *self, TypeNode *type, PathNode *path) {
PyObject *out, *item;
unsigned char c;
bool first = true;
PathNode el_path = {path, 0, NULL};
Py_ssize_t i = 0, offset, fixtuple_size;
TypeNode_get_fixtuple(type, &offset, &fixtuple_size);
self->input_pos++; /* Skip '[' */
out = PyTuple_New(fixtuple_size);
if (out == NULL) return NULL;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
while (true) {
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
/* Parse ']' or ',', then peek the next character */
if (c == ']') {
self->input_pos++;
if (MS_UNLIKELY(i < fixtuple_size)) goto size_error;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
}
else if (first) {
/* Only the first item doesn't need a comma delimiter */
first = false;
}
else {
json_err_invalid(self, "expected ',' or ']'");
goto error;
}
if (MS_UNLIKELY(c == ']')) {
json_err_invalid(self, "trailing comma in array");
goto error;
}
/* Check we don't have too many elements */
if (MS_UNLIKELY(i >= fixtuple_size)) goto size_error;
/* Parse item */
item = json_decode(self, type->details[offset + i].pointer, &el_path);
if (item == NULL) goto error;
el_path.index++;
/* Add item to tuple */
PyTuple_SET_ITEM(out, i, item);
i++;
}
Py_LeaveRecursiveCall();
return out;
size_error:
ms_raise_validation_error(
path,
"Expected `array` of length %zd%U",
fixtuple_size
);
error:
Py_LeaveRecursiveCall();
Py_DECREF(out);
return NULL;
}
static PyObject *
json_decode_namedtuple(JSONDecoderState *self, TypeNode *type, PathNode *path) {
unsigned char c;
bool first = true;
Py_ssize_t nfields, ndefaults, nrequired;
NamedTupleInfo *info = TypeNode_get_namedtuple_info(type);
nfields = Py_SIZE(info);
ndefaults = info->defaults == NULL ? 0 : PyTuple_GET_SIZE(info->defaults);
nrequired = nfields - ndefaults;
self->input_pos++; /* Skip '[' */
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
PyTypeObject *nt_type = (PyTypeObject *)(info->class);
PyObject *out = nt_type->tp_alloc(nt_type, nfields);
if (out == NULL) goto error;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyTuple_SET_ITEM(out, i, NULL);
}
Py_ssize_t i = 0;
while (true) {
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
/* Parse ']' or ',', then peek the next character */
if (c == ']') {
self->input_pos++;
if (MS_UNLIKELY(i < nrequired)) goto size_error;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
}
else if (first) {
/* Only the first item doesn't need a comma delimiter */
first = false;
}
else {
json_err_invalid(self, "expected ',' or ']'");
goto error;
}
if (MS_UNLIKELY(c == ']')) {
json_err_invalid(self, "trailing comma in array");
goto error;
}
/* Check we don't have too many elements */
if (MS_UNLIKELY(i >= nfields)) goto size_error;
/* Parse item */
PathNode el_path = {path, i, NULL};
PyObject *item = json_decode(self, info->types[i], &el_path);
if (item == NULL) goto error;
/* Add item to tuple */
PyTuple_SET_ITEM(out, i, item);
i++;
}
Py_LeaveRecursiveCall();
/* Fill in defaults */
for (; i < nfields; i++) {
PyObject *item = PyTuple_GET_ITEM(info->defaults, i - nrequired);
Py_INCREF(item);
PyTuple_SET_ITEM(out, i, item);
}
return out;
size_error:
if (ndefaults == 0) {
ms_raise_validation_error(
path,
"Expected `array` of length %zd%U",
nfields
);
}
else {
ms_raise_validation_error(
path,
"Expected `array` of length %zd to %zd%U",
nrequired,
nfields
);
}
error:
Py_LeaveRecursiveCall();
Py_DECREF(out);
return NULL;
}
static PyObject *
json_decode_struct_array_inner(
JSONDecoderState *self, StructInfo *info, PathNode *path,
Py_ssize_t starting_index
) {
Py_ssize_t nfields, ndefaults, nrequired, npos, i = 0;
PyObject *out, *item = NULL;
unsigned char c;
bool is_gc, should_untrack;
bool first = starting_index == 0;
StructMetaObject *st_type = info->class;
PathNode item_path = {path, starting_index};
out = Struct_alloc((PyTypeObject *)(st_type));
if (out == NULL) return NULL;
nfields = PyTuple_GET_SIZE(st_type->struct_encode_fields);
ndefaults = PyTuple_GET_SIZE(st_type->struct_defaults);
nrequired = nfields - st_type->n_trailing_defaults;
npos = nfields - ndefaults;
is_gc = MS_TYPE_IS_GC(st_type);
should_untrack = is_gc;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
while (true) {
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
/* Parse ']' or ',', then peek the next character */
if (c == ']') {
self->input_pos++;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
}
else if (first) {
/* Only the first item doesn't need a comma delimiter */
first = false;
}
else {
json_err_invalid(self, "expected ',' or ']'");
goto error;
}
if (MS_UNLIKELY(c == ']')) {
json_err_invalid(self, "trailing comma in array");
goto error;
}
if (MS_LIKELY(i < nfields)) {
/* Parse item */
item = json_decode(self, info->types[i], &item_path);
if (MS_UNLIKELY(item == NULL)) goto error;
Struct_set_index(out, i, item);
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(item);
}
i++;
item_path.index++;
}
else {
if (MS_UNLIKELY(st_type->forbid_unknown_fields == OPT_TRUE)) {
ms_raise_validation_error(
path,
"Expected `array` of at most length %zd",
nfields
);
goto error;
}
else {
/* Skip trailing fields */
if (json_skip(self) < 0) goto error;
}
}
}
/* Check for missing required fields */
if (i < nrequired) {
ms_raise_validation_error(
path,
"Expected `array` of at least length %zd, got %zd%U",
nrequired + starting_index,
i + starting_index
);
goto error;
}
/* Fill in missing fields with defaults */
for (; i < nfields; i++) {
item = get_default(
PyTuple_GET_ITEM(st_type->struct_defaults, i - npos)
);
if (item == NULL) goto error;
Struct_set_index(out, i, item);
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(item);
}
}
if (Struct_decode_post_init(st_type, out, path) < 0) goto error;
Py_LeaveRecursiveCall();
if (is_gc && !should_untrack)
PyObject_GC_Track(out);
return out;
error:
Py_LeaveRecursiveCall();
Py_DECREF(out);
return NULL;
}
/* Decode an integer. If the value fits in an int64_t, it will be stored in
* `out`, otherwise it will be stored in `uout`. A return value of -1 indicates
* an error. */
static int
json_decode_cint(JSONDecoderState *self, int64_t *out, uint64_t *uout, PathNode *path) {
uint64_t mantissa = 0;
bool is_negative = false;
unsigned char c;
unsigned char *orig_input_pos = self->input_pos;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) return -1;
/* Parse minus sign (if present) */
if (c == '-') {
self->input_pos++;
c = json_peek_or_null(self);
is_negative = true;
}
/* Parse integer */
if (MS_UNLIKELY(c == '0')) {
/* Ensure at most one leading zero */
self->input_pos++;
c = json_peek_or_null(self);
if (MS_UNLIKELY(is_digit(c))) {
json_err_invalid(self, "invalid number");
return -1;
}
}
else {
/* Parse the integer part of the number.
*
* We can read the first 19 digits safely into a uint64 without
* checking for overflow. Removing overflow checks from the loop gives
* a measurable performance boost. */
size_t remaining = self->input_end - self->input_pos;
size_t n_safe = Py_MIN(19, remaining);
while (n_safe) {
c = *self->input_pos;
if (!is_digit(c)) goto end_integer;
self->input_pos++;
n_safe--;
mantissa = mantissa * 10 + (uint64_t)(c - '0');
}
if (MS_UNLIKELY(remaining > 19)) {
/* Reading a 20th digit may or may not cause overflow. Any
* additional digits definitely will. Read the 20th digit (and
* check for a 21st), taking the slow path upon overflow. */
c = *self->input_pos;
if (MS_UNLIKELY(is_digit(c))) {
self->input_pos++;
uint64_t mantissa2 = mantissa * 10 + (uint64_t)(c - '0');
bool overflowed = (mantissa2 < mantissa) || ((mantissa2 - (uint64_t)(c - '0')) / 10) != mantissa;
if (MS_UNLIKELY(overflowed || is_digit(json_peek_or_null(self)))) {
goto error_not_int;
}
mantissa = mantissa2;
c = json_peek_or_null(self);
}
}
end_integer:
/* There must be at least one digit */
if (MS_UNLIKELY(mantissa == 0)) goto error_not_int;
}
if (c == '.' || c == 'e' || c == 'E') goto error_not_int;
if (is_negative) {
if (mantissa > 1ull << 63) goto error_not_int;
*out = -1 * (int64_t)mantissa;
}
else {
if (mantissa > LLONG_MAX) {
*uout = mantissa;
}
else {
*out = mantissa;
}
}
return 0;
error_not_int:
/* Use skip to catch malformed JSON */
self->input_pos = orig_input_pos;
if (json_skip(self) < 0) return -1;
ms_error_with_path("Expected `int`%U", path);
return -1;
}
static Py_ssize_t
json_decode_cstr(JSONDecoderState *self, char **out, PathNode *path) {
unsigned char c;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) return -1;
if (c != '"') {
/* Use skip to catch malformed JSON */
if (json_skip(self) < 0) return -1;
/* JSON is valid but the wrong type */
ms_error_with_path("Expected `str`%U", path);
return -1;
}
bool is_ascii = true;
return json_decode_string_view(self, out, &is_ascii);
}
static int
json_ensure_array_nonempty(
JSONDecoderState *self, StructMetaObject *st_type, PathNode *path
) {
unsigned char c;
/* Check for an early end to the array */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) return -1;
if (c == ']') {
Py_ssize_t expected_size;
if (st_type == NULL) {
/* If we don't know the type, the most we know is that the minimum
* size is 1 */
expected_size = 1;
}
else {
/* n_fields - n_optional_fields + 1 tag */
expected_size = PyTuple_GET_SIZE(st_type->struct_encode_fields)
- PyTuple_GET_SIZE(st_type->struct_defaults)
+ 1;
}
ms_raise_validation_error(
path,
"Expected `array` of at least length %zd, got 0%U",
expected_size
);
return -1;
}
return 0;
}
static int
json_ensure_tag_matches(
JSONDecoderState *self, PathNode *path, PyObject *expected_tag
) {
if (PyUnicode_CheckExact(expected_tag)) {
char *tag = NULL;
Py_ssize_t tag_size;
tag_size = json_decode_cstr(self, &tag, path);
if (tag_size < 0) return -1;
/* Check that tag matches expected tag value */
Py_ssize_t expected_size;
const char *expected_str = unicode_str_and_size_nocheck(
expected_tag, &expected_size
);
if (tag_size != expected_size || memcmp(tag, expected_str, expected_size) != 0) {
/* Tag doesn't match the expected value, error nicely */
ms_invalid_cstr_value(tag, tag_size, path);
return -1;
}
}
else {
int64_t tag = 0;
uint64_t utag = 0;
if (json_decode_cint(self, &tag, &utag, path) < 0) return -1;
int64_t expected = PyLong_AsLongLong(expected_tag);
/* Tags must be int64s, if utag != 0 then we know the tags don't match.
* We parse the full uint64 value only to validate the message and
* raise a nice error */
if (utag != 0) {
ms_invalid_cuint_value(utag, path);
return -1;
}
if (tag != expected) {
ms_invalid_cint_value(tag, path);
return -1;
}
}
return 0;
}
static StructInfo *
json_decode_tag_and_lookup_type(
JSONDecoderState *self, Lookup *lookup, PathNode *path
) {
StructInfo *out = NULL;
if (Lookup_IsStrLookup(lookup)) {
Py_ssize_t tag_size;
char *tag = NULL;
tag_size = json_decode_cstr(self, &tag, path);
if (tag_size < 0) return NULL;
out = (StructInfo *)StrLookup_Get((StrLookup *)lookup, tag, tag_size);
if (out == NULL) {
ms_invalid_cstr_value(tag, tag_size, path);
}
}
else {
int64_t tag = 0;
uint64_t utag = 0;
if (json_decode_cint(self, &tag, &utag, path) < 0) return NULL;
if (utag == 0) {
out = (StructInfo *)IntLookup_GetInt64((IntLookup *)lookup, tag);
if (out == NULL) {
ms_invalid_cint_value(tag, path);
}
}
else {
/* tags can't be uint64 values, we only decode to give a nice error */
ms_invalid_cuint_value(utag, path);
}
}
return out;
}
static PyObject *
json_decode_struct_array(
JSONDecoderState *self, TypeNode *type, PathNode *path
) {
Py_ssize_t starting_index = 0;
StructInfo *info = TypeNode_get_struct_info(type);
self->input_pos++; /* Skip '[' */
/* If this is a tagged struct, first read and validate the tag */
if (info->class->struct_tag_value != NULL) {
PathNode tag_path = {path, 0};
if (json_ensure_array_nonempty(self, info->class, path) < 0) return NULL;
if (json_ensure_tag_matches(self, &tag_path, info->class->struct_tag_value) < 0) return NULL;
starting_index = 1;
}
/* Decode the rest of the struct */
return json_decode_struct_array_inner(self, info, path, starting_index);
}
static PyObject *
json_decode_struct_array_union(
JSONDecoderState *self, TypeNode *type, PathNode *path
) {
PathNode tag_path = {path, 0};
Lookup *lookup = TypeNode_get_struct_union(type);
self->input_pos++; /* Skip '[' */
/* Decode & lookup struct type from tag */
if (json_ensure_array_nonempty(self, NULL, path) < 0) return NULL;
StructInfo *info = json_decode_tag_and_lookup_type(self, lookup, &tag_path);
if (info == NULL) return NULL;
/* Finish decoding the rest of the struct */
return json_decode_struct_array_inner(self, info, path, 1);
}
static PyObject *
json_decode_array(
JSONDecoderState *self, TypeNode *type, PathNode *path
) {
if (type->types & MS_TYPE_ANY) {
TypeNode type_any = {MS_TYPE_ANY};
return json_decode_list(self, type, &type_any, path);
}
else if (type->types & MS_TYPE_LIST) {
return json_decode_list(self, type, TypeNode_get_array(type), path);
}
else if (type->types & (MS_TYPE_SET | MS_TYPE_FROZENSET)) {
return json_decode_set(self, type, TypeNode_get_array(type), path);
}
else if (type->types & MS_TYPE_VARTUPLE) {
return json_decode_vartuple(self, type, TypeNode_get_array(type), path);
}
else if (type->types & MS_TYPE_FIXTUPLE) {
return json_decode_fixtuple(self, type, path);
}
else if (type->types & MS_TYPE_NAMEDTUPLE) {
return json_decode_namedtuple(self, type, path);
}
else if (type->types & MS_TYPE_STRUCT_ARRAY) {
return json_decode_struct_array(self, type, path);
}
else if (type->types & MS_TYPE_STRUCT_ARRAY_UNION) {
return json_decode_struct_array_union(self, type, path);
}
return ms_validation_error("array", type, path);
}
static PyObject *
json_decode_dict(
JSONDecoderState *self, TypeNode *type, TypeNode *key_type, TypeNode *val_type, PathNode *path
) {
PyObject *out, *key = NULL, *val = NULL;
unsigned char c;
bool first = true;
PathNode key_path = {path, PATH_KEY, NULL};
PathNode val_path = {path, PATH_ELLIPSIS, NULL};
self->input_pos++; /* Skip '{' */
out = PyDict_New();
if (out == NULL) return NULL;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
while (true) {
/* Parse '}' or ',', then peek the next character */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
if (c == '}') {
self->input_pos++;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
}
else if (first) {
/* Only the first item doesn't need a comma delimiter */
first = false;
}
else {
json_err_invalid(self, "expected ',' or '}'");
goto error;
}
/* Parse a string key */
if (c == '"') {
key = json_decode_dict_key(self, key_type, &key_path);
if (key == NULL) goto error;
}
else if (c == '}') {
json_err_invalid(self, "trailing comma in object");
goto error;
}
else {
json_err_invalid(self, "object keys must be strings");
goto error;
}
/* Parse colon */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
if (c != ':') {
json_err_invalid(self, "expected ':'");
goto error;
}
self->input_pos++;
/* Parse value */
val = json_decode(self, val_type, &val_path);
if (val == NULL) goto error;
/* Add item to dict */
if (MS_UNLIKELY(PyDict_SetItem(out, key, val) < 0))
goto error;
Py_CLEAR(key);
Py_CLEAR(val);
}
if (MS_UNLIKELY(!ms_passes_map_constraints(PyDict_GET_SIZE(out), type, path))) goto error;
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(key);
Py_XDECREF(val);
Py_DECREF(out);
return NULL;
}
static PyObject *
json_decode_typeddict(
JSONDecoderState *self, TypeNode *type, PathNode *path
) {
PyObject *out;
unsigned char c;
char *key = NULL;
bool first = true;
Py_ssize_t key_size, nrequired = 0, pos = 0;
TypedDictInfo *info = TypeNode_get_typeddict_info(type);
self->input_pos++; /* Skip '{' */
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
out = PyDict_New();
if (out == NULL) goto error;
while (true) {
/* Parse '}' or ',', then peek the next character */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
if (c == '}') {
self->input_pos++;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
}
else if (first) {
/* Only the first item doesn't need a comma delimiter */
first = false;
}
else {
json_err_invalid(self, "expected ',' or '}'");
goto error;
}
/* Parse a string key */
if (c == '"') {
bool is_ascii = true;
key_size = json_decode_string_view(self, &key, &is_ascii);
if (key_size < 0) goto error;
}
else if (c == '}') {
json_err_invalid(self, "trailing comma in object");
goto error;
}
else {
json_err_invalid(self, "object keys must be strings");
goto error;
}
/* Parse colon */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
if (c != ':') {
json_err_invalid(self, "expected ':'");
goto error;
}
self->input_pos++;
/* Parse value */
TypeNode *field_type;
PyObject *field = TypedDictInfo_lookup_key(info, key, key_size, &field_type, &pos);
if (field != NULL) {
PathNode field_path = {path, PATH_STR, field};
PyObject *val = json_decode(self, field_type, &field_path);
if (val == NULL) goto error;
/* We want to keep a count of required fields we've decoded. Since
* duplicates can occur, we stash the current dict size, then only
* increment if the dict size has changed _and_ the field is
* required. */
Py_ssize_t cur_size = PyDict_GET_SIZE(out);
int status = PyDict_SetItem(out, field, val);
/* Always decref value, no need to decref key since it's a borrowed
* reference. */
Py_DECREF(val);
if (status < 0) goto error;
if ((PyDict_GET_SIZE(out) != cur_size) && (field_type->types & MS_EXTRA_FLAG)) {
nrequired++;
}
}
else {
/* Skip unknown fields */
if (json_skip(self) < 0) goto error;
}
}
if (nrequired < info->nrequired) {
/* A required field is missing, determine which one and raise */
TypedDictInfo_error_missing(info, out, path);
goto error;
}
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_DECREF(out);
return NULL;
}
static PyObject *
json_decode_dataclass(
JSONDecoderState *self, TypeNode *type, PathNode *path
) {
PyObject *out;
unsigned char c;
char *key = NULL;
bool first = true;
Py_ssize_t key_size, pos = 0;
DataclassInfo *info = TypeNode_get_dataclass_info(type);
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
PyTypeObject *dataclass_type = (PyTypeObject *)(info->class);
out = dataclass_type->tp_alloc(dataclass_type, 0);
if (out == NULL) goto error;
if (info->pre_init != NULL) {
PyObject *res = PyObject_CallOneArg(info->pre_init, out);
if (res == NULL) goto error;
Py_DECREF(res);
}
self->input_pos++; /* Skip '{' */
while (true) {
/* Parse '}' or ',', then peek the next character */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
if (c == '}') {
self->input_pos++;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
}
else if (first) {
/* Only the first item doesn't need a comma delimiter */
first = false;
}
else {
json_err_invalid(self, "expected ',' or '}'");
goto error;
}
/* Parse a string key */
if (c == '"') {
bool is_ascii = true;
key_size = json_decode_string_view(self, &key, &is_ascii);
if (key_size < 0) goto error;
}
else if (c == '}') {
json_err_invalid(self, "trailing comma in object");
goto error;
}
else {
json_err_invalid(self, "object keys must be strings");
goto error;
}
/* Parse colon */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
if (c != ':') {
json_err_invalid(self, "expected ':'");
goto error;
}
self->input_pos++;
/* Parse value */
TypeNode *field_type;
PyObject *field = DataclassInfo_lookup_key(info, key, key_size, &field_type, &pos);
if (field != NULL) {
PathNode field_path = {path, PATH_STR, field};
PyObject *val = json_decode(self, field_type, &field_path);
if (val == NULL) goto error;
int status = PyObject_GenericSetAttr(out, field, val);
Py_DECREF(val);
if (status < 0) goto error;
}
else {
/* Skip unknown fields */
if (json_skip(self) < 0) goto error;
}
}
if (DataclassInfo_post_decode(info, out, path) < 0) goto error;
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(out);
return NULL;
}
static PyObject *
json_decode_struct_map_inner(
JSONDecoderState *self, StructInfo *info, PathNode *path,
Py_ssize_t starting_index
) {
PyObject *out, *val = NULL;
Py_ssize_t key_size, field_index, pos = 0;
unsigned char c;
char *key = NULL;
bool first = starting_index == 0;
StructMetaObject *st_type = info->class;
PathNode field_path = {path, 0, (PyObject *)st_type};
out = Struct_alloc((PyTypeObject *)(st_type));
if (out == NULL) return NULL;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
while (true) {
/* Parse '}' or ',', then peek the next character */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
if (c == '}') {
self->input_pos++;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
}
else if (first) {
/* Only the first item doesn't need a comma delimiter */
first = false;
}
else {
json_err_invalid(self, "expected ',' or '}'");
goto error;
}
/* Parse a string key */
if (c == '"') {
bool is_ascii = true;
key_size = json_decode_string_view(self, &key, &is_ascii);
if (key_size < 0) goto error;
}
else if (c == '}') {
json_err_invalid(self, "trailing comma in object");
goto error;
}
else {
json_err_invalid(self, "object keys must be strings");
goto error;
}
/* Parse colon */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) goto error;
if (c != ':') {
json_err_invalid(self, "expected ':'");
goto error;
}
self->input_pos++;
/* Parse value */
field_index = StructMeta_get_field_index(st_type, key, key_size, &pos);
if (MS_LIKELY(field_index >= 0)) {
field_path.index = field_index;
TypeNode *type = info->types[field_index];
val = json_decode(self, type, &field_path);
if (val == NULL) goto error;
Struct_set_index(out, field_index, val);
}
else if (MS_UNLIKELY(field_index == -2)) {
/* Decode and check that the tag value matches the expected value */
PathNode tag_path = {path, PATH_STR, st_type->struct_tag_field};
if (json_ensure_tag_matches(self, &tag_path, st_type->struct_tag_value) < 0) {
goto error;
}
}
else {
/* Unknown field */
if (MS_UNLIKELY(st_type->forbid_unknown_fields == OPT_TRUE)) {
ms_error_unknown_field(key, key_size, path);
goto error;
}
else {
if (json_skip(self) < 0) goto error;
}
}
}
if (Struct_fill_in_defaults(st_type, out, path) < 0) goto error;
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_DECREF(out);
return NULL;
}
static PyObject *
json_decode_struct_map(
JSONDecoderState *self, TypeNode *type, PathNode *path
) {
StructInfo *info = TypeNode_get_struct_info(type);
self->input_pos++; /* Skip '{' */
return json_decode_struct_map_inner(self, info, path, 0);
}
static PyObject *
json_decode_struct_union(
JSONDecoderState *self, TypeNode *type, PathNode *path
) {
Lookup *lookup = TypeNode_get_struct_union(type);
PathNode tag_path = {path, PATH_STR, Lookup_tag_field(lookup)};
Py_ssize_t tag_field_size;
const char *tag_field = unicode_str_and_size_nocheck(
Lookup_tag_field(lookup), &tag_field_size
);
self->input_pos++; /* Skip '{' */
/* Cache the current input position in case we need to reset it once the
* tag is found */
unsigned char *orig_input_pos = self->input_pos;
for (Py_ssize_t i = 0; ; i++) {
unsigned char c;
/* Parse '}' or ',', then peek the next character */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) return NULL;
if (c == '}') {
self->input_pos++;
break;
}
else if (c == ',' && (i != 0)) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) return NULL;
}
else if (i != 0) {
return json_err_invalid(self, "expected ',' or '}'");
}
/* Parse a string key */
Py_ssize_t key_size;
char *key = NULL;
if (c == '"') {
bool is_ascii = true;
key_size = json_decode_string_view(self, &key, &is_ascii);
if (key_size < 0) return NULL;
}
else if (c == '}') {
return json_err_invalid(self, "trailing comma in object");
}
else {
return json_err_invalid(self, "object keys must be strings");
}
/* Check if key matches tag_field */
bool tag_found = false;
if (key_size == tag_field_size && memcmp(key, tag_field, key_size) == 0) {
tag_found = true;
}
/* Parse colon */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) return NULL;
if (c != ':') {
return json_err_invalid(self, "expected ':'");
}
self->input_pos++;
/* Parse value */
if (tag_found) {
/* Decode & lookup struct type from tag */
StructInfo *info = json_decode_tag_and_lookup_type(self, lookup, &tag_path);
if (info == NULL) return NULL;
if (i != 0) {
/* tag wasn't first field, reset decoder position */
self->input_pos = orig_input_pos;
}
return json_decode_struct_map_inner(self, info, path, i == 0 ? 1 : 0);
}
else {
if (json_skip(self) < 0) return NULL;
}
}
ms_missing_required_field(Lookup_tag_field(lookup), path);
return NULL;
}
static PyObject *
json_decode_object(
JSONDecoderState *self, TypeNode *type, PathNode *path
) {
if (type->types & MS_TYPE_ANY) {
TypeNode type_any = {MS_TYPE_ANY};
return json_decode_dict(self, type, &type_any, &type_any, path);
}
else if (type->types & MS_TYPE_DICT) {
TypeNode *key, *val;
TypeNode_get_dict(type, &key, &val);
return json_decode_dict(self, type, key, val, path);
}
else if (type->types & MS_TYPE_TYPEDDICT) {
return json_decode_typeddict(self, type, path);
}
else if (type->types & MS_TYPE_DATACLASS) {
return json_decode_dataclass(self, type, path);
}
else if (type->types & MS_TYPE_STRUCT) {
return json_decode_struct_map(self, type, path);
}
else if (type->types & MS_TYPE_STRUCT_UNION) {
return json_decode_struct_union(self, type, path);
}
return ms_validation_error("object", type, path);
}
static PyObject *
json_maybe_decode_number(JSONDecoderState *self, TypeNode *type, PathNode *path) {
const char *errmsg = NULL;
const unsigned char *pout;
PyObject *out = parse_number_inline(
self->input_pos, self->input_end,
&pout, &errmsg,
type, path, self->strict, self->float_hook, false
);
self->input_pos = (unsigned char *)pout;
if (MS_UNLIKELY(out == NULL)) {
if (errmsg != NULL) {
json_err_invalid(self, errmsg);
}
}
return out;
}
static MS_NOINLINE PyObject *
json_decode_raw(JSONDecoderState *self) {
unsigned char c;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) return NULL;
const unsigned char *start = self->input_pos;
if (json_skip(self) < 0) return NULL;
Py_ssize_t size = self->input_pos - start;
return Raw_FromView(self->buffer_obj, (char *)start, size);
}
static MS_INLINE PyObject *
json_decode_nocustom(
JSONDecoderState *self, TypeNode *type, PathNode *path
) {
unsigned char c;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) return NULL;
switch (c) {
case 'n': return json_decode_none(self, type, path);
case 't': return json_decode_true(self, type, path);
case 'f': return json_decode_false(self, type, path);
case '[': return json_decode_array(self, type, path);
case '{': return json_decode_object(self, type, path);
case '"': return json_decode_string(self, type, path);
default: return json_maybe_decode_number(self, type, path);
}
}
static PyObject *
json_decode(
JSONDecoderState *self, TypeNode *type, PathNode *path
) {
if (MS_UNLIKELY(type->types == 0)) {
return json_decode_raw(self);
}
PyObject *obj = json_decode_nocustom(self, type, path);
if (MS_UNLIKELY(type->types & (MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC))) {
return ms_decode_custom(obj, self->dec_hook, type, path);
}
return obj;
}
static int
json_skip_ident(JSONDecoderState *self, const char *ident, size_t len) {
self->input_pos++; /* Already checked first char */
if (MS_UNLIKELY(!json_remaining(self, len))) return ms_err_truncated();
if (memcmp(self->input_pos, ident, len) != 0) {
json_err_invalid(self, "invalid character");
return -1;
}
self->input_pos += len;
return 0;
}
static int
json_skip_array(JSONDecoderState *self) {
unsigned char c;
bool first = true;
int out = -1;
self->input_pos++; /* Skip '[' */
if (Py_EnterRecursiveCall(" while deserializing an object")) return -1;
while (true) {
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) break;
if (c == ']') {
self->input_pos++;
out = 0;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) break;
}
else if (first) {
first = false;
}
else {
json_err_invalid(self, "expected ',' or ']'");
break;
}
if (MS_UNLIKELY(c == ']')) {
json_err_invalid(self, "trailing comma in array");
break;
}
if (json_skip(self) < 0) break;
}
Py_LeaveRecursiveCall();
return out;
}
static int
json_skip_object(JSONDecoderState *self) {
unsigned char c;
bool first = true;
int out = -1;
self->input_pos++; /* Skip '{' */
if (Py_EnterRecursiveCall(" while deserializing an object")) return -1;
while (true) {
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) break;
if (c == '}') {
self->input_pos++;
out = 0;
break;
}
else if (c == ',' && !first) {
self->input_pos++;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) break;
}
else if (first) {
first = false;
}
else {
json_err_invalid(self, "expected ',' or '}'");
break;
}
/* Skip key */
if (c == '"') {
if (json_skip_string(self) < 0) break;
}
else if (c == '}') {
json_err_invalid(self, "trailing comma in object");
break;
}
else {
json_err_invalid(self, "expected '\"'");
break;
}
/* Parse colon */
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) break;
if (c != ':') {
json_err_invalid(self, "expected ':'");
break;
}
self->input_pos++;
/* Skip value */
if (json_skip(self) < 0) break;
}
Py_LeaveRecursiveCall();
return out;
}
static int
json_maybe_skip_number(JSONDecoderState *self) {
/* We know there is at least one byte available when this function is
* called */
char c = *self->input_pos;
/* Parse minus sign (if present) */
if (c == '-') {
self->input_pos++;
c = json_peek_or_null(self);
}
/* Parse integer */
if (MS_UNLIKELY(c == '0')) {
/* Ensure at most one leading zero */
self->input_pos++;
c = json_peek_or_null(self);
if (MS_UNLIKELY(is_digit(c))) {
json_err_invalid(self, "invalid number");
return -1;
}
}
else {
/* Skip the integer part of the number. */
unsigned char *cur_pos = self->input_pos;
while (self->input_pos < self->input_end && is_digit(*self->input_pos)) {
self->input_pos++;
}
/* There must be at least one digit */
if (MS_UNLIKELY(cur_pos == self->input_pos)) {
json_err_invalid(self, "invalid character");
return -1;
}
}
c = json_peek_or_null(self);
if (c == '.') {
self->input_pos++;
/* Skip remaining digits until invalid/unknown character */
unsigned char *cur_pos = self->input_pos;
while (self->input_pos < self->input_end && is_digit(*self->input_pos)) {
self->input_pos++;
}
/* Error if no digits after decimal */
if (MS_UNLIKELY(cur_pos == self->input_pos)) {
json_err_invalid(self, "invalid number");
return -1;
}
c = json_peek_or_null(self);
}
if (c == 'e' || c == 'E') {
self->input_pos++;
/* Parse exponent sign (if any) */
c = json_peek_or_null(self);
if (c == '+' || c == '-') {
self->input_pos++;
}
/* Parse exponent digits */
unsigned char *cur_pos = self->input_pos;
while (self->input_pos < self->input_end && is_digit(*self->input_pos)) {
self->input_pos++;
}
/* Error if no digits in exponent */
if (MS_UNLIKELY(cur_pos == self->input_pos)) {
json_err_invalid(self, "invalid number");
return -1;
}
}
return 0;
}
static int
json_skip(JSONDecoderState *self)
{
unsigned char c;
if (MS_UNLIKELY(!json_peek_skip_ws(self, &c))) return -1;
switch (c) {
case 'n': return json_skip_ident(self, "ull", 3);
case 't': return json_skip_ident(self, "rue", 3);
case 'f': return json_skip_ident(self, "alse", 4);
case '"': return json_skip_string(self);
case '[': return json_skip_array(self);
case '{': return json_skip_object(self);
default: return json_maybe_skip_number(self);
}
}
static int
json_format(
JSONDecoderState *, EncoderState *,
Py_ssize_t indent, Py_ssize_t cur_indent
);
static int
json_write_indent(EncoderState *self, Py_ssize_t indent, Py_ssize_t cur_indent) {
if (indent <= 0) return 0;
if (ms_ensure_space(self, cur_indent + 1) < 0) return -1;
char *p = self->output_buffer_raw + self->output_len;
*p++ = '\n';
for (Py_ssize_t i = 0; i < cur_indent; i++) {
*p++ = ' ';
}
self->output_len += cur_indent + 1;
return 0;
}
static int
json_format_array(
JSONDecoderState *dec, EncoderState *enc,
Py_ssize_t indent, Py_ssize_t cur_indent
) {
unsigned char c;
bool first = true;
int out = -1;
Py_ssize_t el_indent = cur_indent + indent;
dec->input_pos++; /* Skip '[' */
if (ms_write(enc, "[", 1) < 0) return -1;
if (Py_EnterRecursiveCall(" while deserializing an object")) return -1;
while (true) {
if (MS_UNLIKELY(!json_peek_skip_ws(dec, &c))) break;
if (c == ']') {
dec->input_pos++;
if (!first) {
if (MS_UNLIKELY(json_write_indent(enc, indent, cur_indent) < 0)) break;
}
out = ms_write(enc, "]", 1);
break;
}
else if (c == ',' && !first) {
dec->input_pos++;
if (indent == 0) {
if (MS_UNLIKELY(ms_write(enc, ", ", 2) < 0)) break;
} else {
if (MS_UNLIKELY(ms_write(enc, ",", 1) < 0)) break;
}
if (MS_UNLIKELY(!json_peek_skip_ws(dec, &c))) break;
}
else if (first) {
first = false;
}
else {
json_err_invalid(dec, "expected ',' or ']'");
break;
}
if (MS_UNLIKELY(c == ']')) {
json_err_invalid(dec, "trailing comma in array");
break;
}
if (json_write_indent(enc, indent, el_indent) < 0) break;
if (json_format(dec, enc, indent, el_indent) < 0) break;
}
Py_LeaveRecursiveCall();
return out;
}
static int
json_format_object(
JSONDecoderState *dec, EncoderState *enc,
Py_ssize_t indent, Py_ssize_t cur_indent
) {
unsigned char c;
bool first = true;
int out = -1;
Py_ssize_t el_indent = cur_indent + indent;
dec->input_pos++; /* Skip '{' */
if (ms_write(enc, "{", 1) < 0) return -1;
if (Py_EnterRecursiveCall(" while deserializing an object")) return -1;
while (true) {
if (MS_UNLIKELY(!json_peek_skip_ws(dec, &c))) break;
if (c == '}') {
dec->input_pos++;
if (!first) {
if (MS_UNLIKELY(json_write_indent(enc, indent, cur_indent) < 0)) break;
}
out = ms_write(enc, "}", 1);
break;
}
else if (c == ',' && !first) {
dec->input_pos++;
if (indent == 0) {
if (MS_UNLIKELY(ms_write(enc, ", ", 2) < 0)) break;
} else {
if (MS_UNLIKELY(ms_write(enc, ",", 1) < 0)) break;
}
if (MS_UNLIKELY(!json_peek_skip_ws(dec, &c))) break;
}
else if (first) {
first = false;
}
else {
json_err_invalid(dec, "expected ',' or '}'");
break;
}
if (c == '"') {
if (json_write_indent(enc, indent, el_indent) < 0) break;
if (json_format(dec, enc, indent, el_indent) < 0) break;
}
else if (c == '}') {
json_err_invalid(dec, "trailing comma in object");
break;
}
else {
json_err_invalid(dec, "expected '\"'");
break;
}
if (MS_UNLIKELY(!json_peek_skip_ws(dec, &c))) break;
if (c != ':') {
json_err_invalid(dec, "expected ':'");
break;
}
dec->input_pos++;
if (indent >= 0) {
if (ms_write(enc, ": ", 2) < 0) break;
}
else {
if (ms_write(enc, ":", 1) < 0) break;
}
if (json_format(dec, enc, indent, el_indent) < 0) break;
}
Py_LeaveRecursiveCall();
return out;
}
static int
json_format(
JSONDecoderState *dec, EncoderState *enc,
Py_ssize_t indent, Py_ssize_t cur_indent
) {
unsigned char c;
if (MS_UNLIKELY(!json_peek_skip_ws(dec, &c))) return -1;
if (c == '[') {
return json_format_array(dec, enc, indent, cur_indent);
}
else if (c == '{') {
return json_format_object(dec, enc, indent, cur_indent);
}
else {
unsigned char *start = dec->input_pos;
if (json_skip(dec) < 0) return -1;
unsigned char *end = dec->input_pos;
return ms_write(enc, (char *)start, end - start);
}
}
PyDoc_STRVAR(msgspec_json_format__doc__,
"json_format(buf, *, indent=2)\n"
"--\n"
"\n"
"Format an existing JSON message, usually to be more human readable.\n"
"\n"
"Parameters\n"
"----------\n"
"buf : bytes-like or str\n"
" The JSON message to format.\n"
"indent : int, optional\n"
" How many spaces to indent for a single indentation level. Defaults to 2.\n"
" Set to 0 to format the message as a single line, with spaces added between\n"
" items for readability. Set to a negative number to strip all unnecessary\n"
" whitespace, minimizing the message size.\n"
"\n"
"Returns\n"
"-------\n"
"output : bytes or str\n"
" The formatted JSON message. Returns a str if input is a str, bytes otherwise."
);
static PyObject*
msgspec_json_format(PyObject *self, PyObject *args, PyObject *kwargs)
{
int status;
Py_buffer buffer;
PyObject *out = NULL, *buf = NULL;
char *kwlist[] = {"buf", "indent", NULL};
Py_ssize_t indent = 2;
/* Parse arguments */
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|$n", kwlist, &buf, &indent))
return NULL;
if (indent < 0) {
indent = -1;
}
buffer.buf = NULL;
if (ms_get_buffer(buf, &buffer) >= 0) {
JSONDecoderState dec;
EncoderState enc;
/* Init decoder */
dec.dec_hook = NULL;
dec.float_hook = NULL;
dec.type = NULL;
dec.scratch = NULL;
dec.scratch_capacity = 0;
dec.scratch_len = 0;
dec.buffer_obj = buf;
dec.input_start = buffer.buf;
dec.input_pos = buffer.buf;
dec.input_end = dec.input_pos + buffer.len;
/* Init encoder */
enc.mod = msgspec_get_state(self);
enc.enc_hook = NULL;
/* Assume pretty-printing will take at least as much space as the
* input. This is true unless there's existing whitespace. */
enc.max_output_len = (indent >= 0) ? buffer.len : ENC_INIT_BUFSIZE;
enc.output_len = 0;
enc.output_buffer = PyBytes_FromStringAndSize(NULL, enc.max_output_len);
if (enc.output_buffer != NULL) {
enc.output_buffer_raw = PyBytes_AS_STRING(enc.output_buffer);
enc.resize_buffer = &ms_resize_bytes;
status = json_format(&dec, &enc, indent, 0);
if (status == 0 && json_has_trailing_characters(&dec)) {
status = -1;
}
if (status == 0) {
if (PyUnicode_CheckExact(buf)) {
/* str input, str output */
out = PyUnicode_FromStringAndSize(
enc.output_buffer_raw,
enc.output_len
);
Py_CLEAR(enc.output_buffer);
}
else {
/* Trim output to length */
out = enc.output_buffer;
FAST_BYTES_SHRINK(out, enc.output_len);
}
} else {
/* Error, drop buffer */
Py_CLEAR(enc.output_buffer);
}
}
ms_release_buffer(&buffer);
}
return out;
}
PyDoc_STRVAR(JSONDecoder_decode__doc__,
"decode(self, buf)\n"
"--\n"
"\n"
"Deserialize an object from JSON.\n"
"\n"
"Parameters\n"
"----------\n"
"buf : bytes-like or str\n"
" The message to decode.\n"
"\n"
"Returns\n"
"-------\n"
"obj : Any\n"
" The deserialized object.\n"
);
static PyObject*
JSONDecoder_decode(JSONDecoder *self, PyObject *const *args, Py_ssize_t nargs)
{
if (!check_positional_nargs(nargs, 1, 1)) {
return NULL;
}
JSONDecoderState state = {
.type = self->type,
.strict = self->strict,
.dec_hook = self->dec_hook,
.float_hook = self->float_hook,
.scratch = NULL,
.scratch_capacity = 0,
.scratch_len = 0
};
Py_buffer buffer;
buffer.buf = NULL;
if (ms_get_buffer(args[0], &buffer) >= 0) {
state.buffer_obj = args[0];
state.input_start = buffer.buf;
state.input_pos = buffer.buf;
state.input_end = state.input_pos + buffer.len;
PyObject *res = json_decode(&state, state.type, NULL);
if (res != NULL && json_has_trailing_characters(&state)) {
Py_CLEAR(res);
}
ms_release_buffer(&buffer);
PyMem_Free(state.scratch);
return res;
}
return NULL;
}
PyDoc_STRVAR(JSONDecoder_decode_lines__doc__,
"decode_lines(self, buf)\n"
"--\n"
"\n"
"Decode a list of items from newline-delimited JSON.\n"
"\n"
"Parameters\n"
"----------\n"
"buf : bytes-like or str\n"
" The message to decode.\n"
"\n"
"Returns\n"
"-------\n"
"items : list\n"
" A list of decoded objects.\n"
"Examples\n"
"--------\n"
">>> import msgspec\n"
">>> msg = \"\"\"\n"
"... {\"x\": 1, \"y\": 2}\n"
"... {\"x\": 3, \"y\": 4}\n"
"... \"\"\"\n"
">>> dec = msgspec.json.Decoder()\n"
">>> dec.decode_lines(msg)\n"
"[{'x': 1, 'y': 2}, {'x': 3, 'y': 4}]"
);
static PyObject*
JSONDecoder_decode_lines(JSONDecoder *self, PyObject *const *args, Py_ssize_t nargs)
{
if (!check_positional_nargs(nargs, 1, 1)) {
return NULL;
}
JSONDecoderState state = {
.type = self->type,
.strict = self->strict,
.dec_hook = self->dec_hook,
.float_hook = self->float_hook,
.scratch = NULL,
.scratch_capacity = 0,
.scratch_len = 0
};
Py_buffer buffer;
buffer.buf = NULL;
if (ms_get_buffer(args[0], &buffer) >= 0) {
state.buffer_obj = args[0];
state.input_start = buffer.buf;
state.input_pos = buffer.buf;
state.input_end = state.input_pos + buffer.len;
PathNode path = {NULL, 0, NULL};
PyObject *out = PyList_New(0);
if (out == NULL) return NULL;
while (true) {
/* Skip until first non-whitespace character, or return if buffer
* exhausted */
while (true) {
if (state.input_pos == state.input_end) {
goto done;
}
unsigned char c = *state.input_pos;
if (MS_LIKELY(c != ' ' && c != '\n' && c != '\r' && c != '\t')) {
break;
}
state.input_pos++;
}
/* Read and append next item */
PyObject *item = json_decode(&state, state.type, &path);
path.index++;
if (item == NULL) {
Py_CLEAR(out);
goto done;
}
int status = PyList_Append(out, item);
Py_DECREF(item);
if (status < 0) {
Py_CLEAR(out);
goto done;
}
}
done:
ms_release_buffer(&buffer);
PyMem_Free(state.scratch);
return out;
}
return NULL;
}
static struct PyMethodDef JSONDecoder_methods[] = {
{
"decode", (PyCFunction) JSONDecoder_decode, METH_FASTCALL,
JSONDecoder_decode__doc__,
},
{
"decode_lines", (PyCFunction) JSONDecoder_decode_lines, METH_FASTCALL,
JSONDecoder_decode_lines__doc__,
},
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS},
{NULL, NULL} /* sentinel */
};
static PyMemberDef JSONDecoder_members[] = {
{"type", T_OBJECT_EX, offsetof(JSONDecoder, orig_type), READONLY, "The Decoder type"},
{"strict", T_BOOL, offsetof(JSONDecoder, strict), READONLY, "The Decoder strict setting"},
{"dec_hook", T_OBJECT, offsetof(JSONDecoder, dec_hook), READONLY, "The Decoder dec_hook"},
{"float_hook", T_OBJECT, offsetof(JSONDecoder, float_hook), READONLY, "The Decoder float_hook"},
{NULL},
};
static PyTypeObject JSONDecoder_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "msgspec.json.Decoder",
.tp_doc = JSONDecoder__doc__,
.tp_basicsize = sizeof(JSONDecoder),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_new = PyType_GenericNew,
.tp_init = (initproc)JSONDecoder_init,
.tp_traverse = (traverseproc)JSONDecoder_traverse,
.tp_dealloc = (destructor)JSONDecoder_dealloc,
.tp_repr = (reprfunc)JSONDecoder_repr,
.tp_methods = JSONDecoder_methods,
.tp_members = JSONDecoder_members,
};
PyDoc_STRVAR(msgspec_json_decode__doc__,
"json_decode(buf, *, type='Any', strict=True, dec_hook=None)\n"
"--\n"
"\n"
"Deserialize an object from JSON.\n"
"\n"
"Parameters\n"
"----------\n"
"buf : bytes-like or str\n"
" The message to decode.\n"
"type : type, optional\n"
" A Python type (in type annotation form) to decode the object as. If\n"
" provided, the message will be type checked and decoded as the specified\n"
" type. Defaults to `Any`, in which case the message will be decoded using\n"
" the default JSON types.\n"
"strict : bool, optional\n"
" Whether type coercion rules should be strict. Setting to False enables a\n"
" wider set of coercion rules from string to non-string types for all values.\n"
" Default is True.\n"
"dec_hook : callable, optional\n"
" An optional callback for handling decoding custom types. Should have the\n"
" signature ``dec_hook(type: Type, obj: Any) -> Any``, where ``type`` is the\n"
" expected message type, and ``obj`` is the decoded representation composed\n"
" of only basic JSON types. This hook should transform ``obj`` into type\n"
" ``type``, or raise a ``TypeError`` if unsupported.\n"
"\n"
"Returns\n"
"-------\n"
"obj : Any\n"
" The deserialized object.\n"
"\n"
"See Also\n"
"--------\n"
"Decoder.decode"
);
static PyObject*
msgspec_json_decode(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *res = NULL, *buf = NULL, *type = NULL, *dec_hook = NULL, *strict_obj = NULL;
int strict = 1;
MsgspecState *mod = msgspec_get_state(self);
/* Parse arguments */
if (!check_positional_nargs(nargs, 1, 1)) return NULL;
buf = args[0];
if (kwnames != NULL) {
Py_ssize_t nkwargs = PyTuple_GET_SIZE(kwnames);
if ((type = find_keyword(kwnames, args + nargs, mod->str_type)) != NULL) nkwargs--;
if ((strict_obj = find_keyword(kwnames, args + nargs, mod->str_strict)) != NULL) nkwargs--;
if ((dec_hook = find_keyword(kwnames, args + nargs, mod->str_dec_hook)) != NULL) nkwargs--;
if (nkwargs > 0) {
PyErr_SetString(
PyExc_TypeError,
"Extra keyword arguments provided"
);
return NULL;
}
}
/* Handle dec_hook */
if (dec_hook == Py_None) {
dec_hook = NULL;
}
if (dec_hook != NULL) {
if (!PyCallable_Check(dec_hook)) {
PyErr_SetString(PyExc_TypeError, "dec_hook must be callable");
return NULL;
}
}
/* Handle strict */
if (strict_obj != NULL) {
strict = PyObject_IsTrue(strict_obj);
if (strict < 0) return NULL;
}
JSONDecoderState state = {
.strict = strict,
.dec_hook = dec_hook,
.float_hook = NULL,
.scratch = NULL,
.scratch_capacity = 0,
.scratch_len = 0
};
/* Allocate Any & Struct type nodes (simple, common cases) on the stack,
* everything else on the heap */
TypeNode typenode_any = {MS_TYPE_ANY};
TypeNodeSimple typenode_struct;
if (type == NULL || type == mod->typing_any) {
state.type = &typenode_any;
}
else if (Py_TYPE(type) == &StructMetaType) {
PyObject *info = StructInfo_Convert(type);
if (info == NULL) return NULL;
bool array_like = ((StructMetaObject *)type)->array_like == OPT_TRUE;
typenode_struct.types = array_like ? MS_TYPE_STRUCT_ARRAY : MS_TYPE_STRUCT;
typenode_struct.details[0].pointer = info;
state.type = (TypeNode *)(&typenode_struct);
}
else {
state.type = TypeNode_Convert(type);
if (state.type == NULL) return NULL;
}
Py_buffer buffer;
buffer.buf = NULL;
if (ms_get_buffer(buf, &buffer) >= 0) {
state.buffer_obj = buf;
state.input_start = buffer.buf;
state.input_pos = buffer.buf;
state.input_end = state.input_pos + buffer.len;
res = json_decode(&state, state.type, NULL);
if (res != NULL && json_has_trailing_characters(&state)) {
Py_CLEAR(res);
}
ms_release_buffer(&buffer);
}
PyMem_Free(state.scratch);
if (state.type == (TypeNode *)&typenode_struct) {
Py_DECREF(typenode_struct.details[0].pointer);
}
else if (state.type != &typenode_any) {
TypeNode_Free(state.type);
}
return res;
}
/*************************************************************************
* to_builtins *
*************************************************************************/
#define MS_BUILTIN_BYTES (1ull << 0)
#define MS_BUILTIN_BYTEARRAY (1ull << 1)
#define MS_BUILTIN_MEMORYVIEW (1ull << 2)
#define MS_BUILTIN_DATETIME (1ull << 3)
#define MS_BUILTIN_DATE (1ull << 4)
#define MS_BUILTIN_TIME (1ull << 5)
#define MS_BUILTIN_UUID (1ull << 6)
#define MS_BUILTIN_DECIMAL (1ull << 7)
#define MS_BUILTIN_TIMEDELTA (1ull << 8)
typedef struct {
MsgspecState *mod;
PyObject *enc_hook;
bool str_keys;
enum order_mode order;
uint32_t builtin_types;
PyObject *builtin_types_seq;
} ToBuiltinsState;
static PyObject * to_builtins(ToBuiltinsState *, PyObject *, bool);
static PyObject *
to_builtins_enum(ToBuiltinsState *self, PyObject *obj)
{
return PyObject_GetAttr(obj, self->mod->str__value_);
}
static PyObject *
to_builtins_binary(ToBuiltinsState *self, const char *buf, Py_ssize_t size) {
Py_ssize_t output_size = ms_encode_base64_size(self->mod, size);
if (output_size < 0) return NULL;
PyObject *out = PyUnicode_New(output_size, 127);
if (out == NULL) return NULL;
ms_encode_base64(buf, size, ascii_get_buffer(out));
return out;
}
static PyObject *
to_builtins_datetime(ToBuiltinsState *self, PyObject *obj) {
char buf[32];
int size = ms_encode_datetime(self->mod, obj, buf);
if (size < 0) return NULL;
PyObject *out = PyUnicode_New(size, 127);
memcpy(ascii_get_buffer(out), buf, size);
return out;
}
static PyObject *
to_builtins_date(ToBuiltinsState *self, PyObject *obj) {
PyObject *out = PyUnicode_New(10, 127);
if (out == NULL) return NULL;
ms_encode_date(obj, ascii_get_buffer(out));
return out;
}
static PyObject *
to_builtins_time(ToBuiltinsState *self, PyObject *obj) {
char buf[21];
int size = ms_encode_time(self->mod, obj, buf);
if (size < 0) return NULL;
PyObject *out = PyUnicode_New(size, 127);
memcpy(ascii_get_buffer(out), buf, size);
return out;
}
static PyObject *
to_builtins_timedelta(ToBuiltinsState *self, PyObject *obj) {
char buf[26];
int size = ms_encode_timedelta(obj, buf);
PyObject *out = PyUnicode_New(size, 127);
memcpy(ascii_get_buffer(out), buf, size);
return out;
}
static PyObject *
to_builtins_uuid(ToBuiltinsState *self, PyObject *obj) {
PyObject *out = PyUnicode_New(36, 127);
if (out == NULL) return NULL;
if (ms_encode_uuid(self->mod, obj, ascii_get_buffer(out), true) < 0) {
Py_CLEAR(out);
}
return out;
}
static PyObject *
to_builtins_decimal(ToBuiltinsState *self, PyObject *obj) {
return PyObject_Str(obj);
}
static PyObject *
to_builtins_list(ToBuiltinsState *self, PyObject *obj) {
if (Py_EnterRecursiveCall(" while serializing an object")) return NULL;
Py_ssize_t size = PyList_GET_SIZE(obj);
PyObject *out = PyList_New(size);
if (out == NULL) goto cleanup;
for (Py_ssize_t i = 0; i < size; i++) {
PyObject *item = PyList_GET_ITEM(obj, i);
PyObject *new = to_builtins(self, item, false);
if (new == NULL) {
Py_CLEAR(out);
goto cleanup;
}
PyList_SET_ITEM(out, i, new);
}
cleanup:
Py_LeaveRecursiveCall();
return out;
}
static PyObject *
to_builtins_tuple(ToBuiltinsState *self, PyObject *obj, bool is_key) {
if (Py_EnterRecursiveCall(" while serializing an object")) return NULL;
Py_ssize_t size = PyTuple_GET_SIZE(obj);
PyObject *out = PyTuple_New(size);
if (out == NULL) goto cleanup;
for (Py_ssize_t i = 0; i < size; i++) {
PyObject *item = PyTuple_GET_ITEM(obj, i);
PyObject *new = to_builtins(self, item, is_key);
if (new == NULL) {
Py_CLEAR(out);
goto cleanup;
}
PyTuple_SET_ITEM(out, i, new);
}
cleanup:
Py_LeaveRecursiveCall();
return out;
}
static PyObject *
to_builtins_set(ToBuiltinsState *self, PyObject *obj, bool is_key) {
PyObject *out = NULL;
if (Py_EnterRecursiveCall(" while serializing an object")) return NULL;
PyObject *list = PySequence_List(obj);
if (list == NULL) goto cleanup;
if (self->order != ORDER_DEFAULT) {
if (PyList_Sort(list) < 0) goto cleanup;
}
Py_ssize_t size = PyList_GET_SIZE(list);
for (Py_ssize_t i = 0; i < size; i++) {
PyObject *orig_item = PyList_GET_ITEM(list, i);
PyObject *new_item = to_builtins(self, orig_item, is_key);
if (new_item == NULL) goto cleanup;
PyList_SET_ITEM(list, i, new_item);
Py_DECREF(orig_item);
}
if (is_key) {
out = PyList_AsTuple(list);
}
else {
Py_INCREF(list);
out = list;
}
cleanup:
Py_LeaveRecursiveCall();
Py_XDECREF(list);
return out;
}
static void
sort_dict_inplace(PyObject **dict) {
PyObject *out = NULL, *new = NULL, *keys = NULL;
new = PyDict_New();
if (new == NULL) goto error;
keys = PyDict_Keys(*dict);
if (keys == NULL) goto error;
if (PyList_Sort(keys) < 0) goto error;
Py_ssize_t size = PyList_GET_SIZE(keys);
for (Py_ssize_t i = 0; i < size; i++) {
PyObject *key = PyList_GET_ITEM(keys, i);
PyObject *val = PyDict_GetItem(*dict, key);
if (val == NULL) goto error;
if (PyDict_SetItem(new, key, val) < 0) goto error;
}
Py_INCREF(new);
out = new;
error:
Py_XDECREF(new);
Py_XDECREF(keys);
Py_XDECREF(*dict);
*dict = out;
}
static PyObject *
to_builtins_dict(ToBuiltinsState *self, PyObject *obj) {
if (Py_EnterRecursiveCall(" while serializing an object")) return NULL;
PyObject *new_key = NULL, *new_val = NULL, *key, *val;
bool ok = false;
PyObject *out = PyDict_New();
if (out == NULL) goto cleanup;
Py_ssize_t pos = 0;
while (PyDict_Next(obj, &pos, &key, &val)) {
new_key = to_builtins(self, key, true);
if (new_key == NULL) goto cleanup;
if (self->str_keys) {
if (PyLong_CheckExact(new_key) || PyFloat_CheckExact(new_key)) {
PyObject *temp = PyObject_Str(new_key);
if (temp == NULL) goto cleanup;
Py_DECREF(new_key);
new_key = temp;
}
else if (!PyUnicode_CheckExact(new_key)) {
PyErr_SetString(
PyExc_TypeError,
"Only dicts with str-like or number-like keys are supported"
);
goto cleanup;
}
}
new_val = to_builtins(self, val, false);
if (new_val == NULL) goto cleanup;
if (PyDict_SetItem(out, new_key, new_val) < 0) goto cleanup;
Py_CLEAR(new_key);
Py_CLEAR(new_val);
}
if (MS_UNLIKELY(self->order != ORDER_DEFAULT)) {
sort_dict_inplace(&out);
}
ok = true;
cleanup:
Py_LeaveRecursiveCall();
if (!ok) {
Py_CLEAR(out);
Py_XDECREF(new_key);
Py_XDECREF(new_val);
}
return out;
}
static PyObject *
to_builtins_struct(ToBuiltinsState *self, PyObject *obj, bool is_key) {
if (Py_EnterRecursiveCall(" while serializing an object")) return NULL;
bool ok = false;
PyObject *out = NULL;
StructMetaObject *struct_type = (StructMetaObject *)Py_TYPE(obj);
PyObject *tag_field = struct_type->struct_tag_field;
PyObject *tag_value = struct_type->struct_tag_value;
PyObject *fields = struct_type->struct_encode_fields;
PyObject *defaults = struct_type->struct_defaults;
Py_ssize_t nfields = PyTuple_GET_SIZE(fields);
Py_ssize_t npos = nfields - PyTuple_GET_SIZE(defaults);
bool omit_defaults = struct_type->omit_defaults == OPT_TRUE;
if (struct_type->array_like == OPT_TRUE) {
Py_ssize_t tagged = (tag_value != NULL);
Py_ssize_t size = nfields + tagged;
if (is_key) {
out = PyTuple_New(size);
}
else {
out = PyList_New(size);
}
if (out == NULL) goto cleanup;
if (tagged) {
Py_INCREF(tag_value);
if (is_key) {
PyTuple_SET_ITEM(out, 0, tag_value);
}
else {
PyList_SET_ITEM(out, 0, tag_value);
}
}
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *val = Struct_get_index(obj, i);
if (val == NULL) goto cleanup;
PyObject *val2 = to_builtins(self, val, is_key);
if (val2 == NULL) goto cleanup;
Py_INCREF(val2);
if (is_key) {
PyTuple_SET_ITEM(out, i + tagged, val2);
}
else {
PyList_SET_ITEM(out, i + tagged, val2);
}
}
}
else {
out = PyDict_New();
if (out == NULL) goto cleanup;
if (tag_value != NULL) {
if (PyDict_SetItem(out, tag_field, tag_value) < 0) goto cleanup;
}
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *key = PyTuple_GET_ITEM(fields, i);
PyObject *val = Struct_get_index(obj, i);
if (MS_UNLIKELY(val == NULL)) goto cleanup;
if (MS_UNLIKELY(val == UNSET)) continue;
if (
!omit_defaults ||
i < npos ||
!is_default(val, PyTuple_GET_ITEM(defaults, i - npos))
) {
PyObject *val2 = to_builtins(self, val, false);
if (val2 == NULL) goto cleanup;
int status = PyDict_SetItem(out, key, val2);
Py_DECREF(val2);
if (status < 0) goto cleanup;
}
}
if (MS_UNLIKELY(self->order == ORDER_SORTED)) {
sort_dict_inplace(&out);
}
}
ok = true;
cleanup:
Py_LeaveRecursiveCall();
if (!ok) {
Py_CLEAR(out);
}
return out;
}
static PyObject *
to_builtins_dataclass(ToBuiltinsState *self, PyObject *obj, PyObject *fields)
{
if (Py_EnterRecursiveCall(" while serializing an object")) return NULL;
bool ok = false;
PyObject *out = NULL;
DataclassIter iter;
if (!dataclass_iter_setup(&iter, obj, fields)) goto cleanup;
out = PyDict_New();
if (out == NULL) goto cleanup;
PyObject *field, *val;
while (dataclass_iter_next(&iter, &field, &val)) {
PyObject *val2 = to_builtins(self, val, false);
int status = (
(val2 == NULL) ? -1 : PyDict_SetItem(out, field, val2)
);
Py_DECREF(val);
Py_XDECREF(val2);
if (status < 0) goto cleanup;
}
if (MS_UNLIKELY(self->order == ORDER_SORTED)) {
sort_dict_inplace(&out);
}
ok = true;
cleanup:
Py_LeaveRecursiveCall();
dataclass_iter_cleanup(&iter);
if (!ok) {
Py_CLEAR(out);
}
return out;
}
static PyObject*
to_builtins_object(ToBuiltinsState *self, PyObject *obj) {
bool ok = false;
PyObject *dict = NULL, *out = NULL;
if (Py_EnterRecursiveCall(" while serializing an object")) return NULL;
out = PyDict_New();
if (out == NULL) goto cleanup;
/* First encode everything in `__dict__` */
dict = PyObject_GenericGetDict(obj, NULL);
if (MS_UNLIKELY(dict == NULL)) {
PyErr_Clear();
}
else {
PyObject *key, *val;
Py_ssize_t pos = 0;
while (PyDict_Next(dict, &pos, &key, &val)) {
if (MS_LIKELY(PyUnicode_CheckExact(key))) {
Py_ssize_t key_len;
if (MS_UNLIKELY(val == UNSET)) continue;
const char* key_buf = unicode_str_and_size(key, &key_len);
if (MS_UNLIKELY(key_buf == NULL)) goto cleanup;
if (MS_UNLIKELY(*key_buf == '_')) continue;
PyObject *val2 = to_builtins(self, val, false);
if (val2 == NULL) goto cleanup;
int status = PyDict_SetItem(out, key, val2);
Py_DECREF(val2);
if (status < 0) goto cleanup;
}
}
}
/* Then encode everything in slots */
PyTypeObject *type = Py_TYPE(obj);
while (type != NULL) {
Py_ssize_t n = Py_SIZE(type);
if (n) {
PyMemberDef *mp = MS_PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
for (Py_ssize_t i = 0; i < n; i++, mp++) {
if (MS_LIKELY(mp->type == T_OBJECT_EX && !(mp->flags & READONLY))) {
char *addr = (char *)obj + mp->offset;
PyObject *val = *(PyObject **)addr;
if (MS_UNLIKELY(val == UNSET)) continue;
if (MS_UNLIKELY(val == NULL)) continue;
if (MS_UNLIKELY(*mp->name == '_')) continue;
PyObject *key = PyUnicode_InternFromString(mp->name);
if (key == NULL) goto cleanup;
int status = -1;
PyObject *val2 = to_builtins(self, val, false);
if (val2 != NULL) {
status = PyDict_SetItem(out, key, val2);
Py_DECREF(val2);
}
Py_DECREF(key);
if (status < 0) goto cleanup;
}
}
}
type = type->tp_base;
}
if (MS_UNLIKELY(self->order == ORDER_SORTED)) {
sort_dict_inplace(&out);
}
ok = true;
cleanup:
Py_XDECREF(dict);
Py_LeaveRecursiveCall();
if (!ok) {
Py_CLEAR(out);
}
return out;
}
static PyObject *
to_builtins(ToBuiltinsState *self, PyObject *obj, bool is_key) {
PyTypeObject *type = Py_TYPE(obj);
if (
obj == Py_None ||
type == &PyBool_Type ||
type == &PyLong_Type ||
type == &PyFloat_Type ||
type == &PyUnicode_Type
) {
goto builtin;
}
else if (type == &PyBytes_Type) {
if (self->builtin_types & MS_BUILTIN_BYTES) goto builtin;
return to_builtins_binary(
self, PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj)
);
}
else if (type == &PyByteArray_Type) {
if (self->builtin_types & MS_BUILTIN_BYTEARRAY) goto builtin;
return to_builtins_binary(
self, PyByteArray_AS_STRING(obj), PyByteArray_GET_SIZE(obj)
);
}
else if (type == &PyMemoryView_Type) {
if (self->builtin_types & MS_BUILTIN_MEMORYVIEW) goto builtin;
PyObject *out;
Py_buffer buffer;
if (PyObject_GetBuffer(obj, &buffer, PyBUF_CONTIG_RO) < 0) return NULL;
out = to_builtins_binary(self, buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
return out;
}
else if (type == PyDateTimeAPI->DateTimeType) {
if (self->builtin_types & MS_BUILTIN_DATETIME) goto builtin;
return to_builtins_datetime(self, obj);
}
else if (type == PyDateTimeAPI->DateType) {
if (self->builtin_types & MS_BUILTIN_DATE) goto builtin;
return to_builtins_date(self, obj);
}
else if (type == PyDateTimeAPI->TimeType) {
if (self->builtin_types & MS_BUILTIN_TIME) goto builtin;
return to_builtins_time(self, obj);
}
else if (type == PyDateTimeAPI->DeltaType) {
if (self->builtin_types & MS_BUILTIN_TIMEDELTA) goto builtin;
return to_builtins_timedelta(self, obj);
}
else if (type == (PyTypeObject *)(self->mod->DecimalType)) {
if (self->builtin_types & MS_BUILTIN_DECIMAL) goto builtin;
return to_builtins_decimal(self, obj);
}
else if (PyList_Check(obj)) {
return to_builtins_list(self, obj);
}
else if (PyTuple_Check(obj)) {
return to_builtins_tuple(self, obj, is_key);
}
else if (PyDict_Check(obj)) {
return to_builtins_dict(self, obj);
}
else if (Py_TYPE(type) == &StructMetaType) {
return to_builtins_struct(self, obj, is_key);
}
else if (Py_TYPE(type) == self->mod->EnumMetaType) {
return to_builtins_enum(self, obj);
}
else if (is_key & PyUnicode_Check(obj)) {
return PyObject_Str(obj);
}
else if (PyType_IsSubtype(type, (PyTypeObject *)(self->mod->UUIDType))) {
if (self->builtin_types & MS_BUILTIN_UUID) goto builtin;
return to_builtins_uuid(self, obj);
}
else if (PyAnySet_Check(obj)) {
return to_builtins_set(self, obj, is_key);
}
else if (!PyType_Check(obj) && type->tp_dict != NULL) {
PyObject *fields = PyObject_GetAttr(obj, self->mod->str___dataclass_fields__);
if (fields != NULL) {
PyObject *out = to_builtins_dataclass(self, obj, fields);
Py_DECREF(fields);
return out;
}
else {
PyErr_Clear();
}
if (PyDict_Contains(type->tp_dict, self->mod->str___attrs_attrs__)) {
return to_builtins_object(self, obj);
}
}
if (self->builtin_types_seq != NULL) {
PyObject **items = PySequence_Fast_ITEMS(self->builtin_types_seq);
Py_ssize_t size = PySequence_Fast_GET_SIZE(self->builtin_types_seq);
for (Py_ssize_t i = 0; i < size; i++) {
if (((PyObject *)type) == *(items + i)) goto builtin;
}
}
if (self->enc_hook != NULL) {
PyObject *out = NULL;
PyObject *temp;
temp = PyObject_CallOneArg(self->enc_hook, obj);
if (temp == NULL) return NULL;
if (!Py_EnterRecursiveCall(" while serializing an object")) {
out = to_builtins(self, temp, is_key);
Py_LeaveRecursiveCall();
}
Py_DECREF(temp);
return out;
}
else {
ms_encode_err_type_unsupported(type);
return NULL;
}
builtin:
Py_INCREF(obj);
return obj;
}
static int
ms_process_builtin_types(
MsgspecState *mod,
PyObject *builtin_types,
uint32_t *mask,
PyObject **custom_types
) {
if (builtin_types == NULL || builtin_types == Py_None) return 0;
bool forward_builtins_seq = false;
const char *invalid_type_err = "builtin_types must be an iterable of types";
PyObject *seq = PySequence_Fast(builtin_types, invalid_type_err);
if (seq == NULL) return -1;
Py_ssize_t size = PySequence_Fast_GET_SIZE(seq);
PyObject **items = PySequence_Fast_ITEMS(seq);
for (Py_ssize_t i = 0; i < size; i++) {
PyObject *type = *(items + i);
if (type == (PyObject *)(&PyBytes_Type)) {
*mask |= MS_BUILTIN_BYTES;
}
else if (type == (PyObject *)(&PyByteArray_Type)) {
*mask |= MS_BUILTIN_BYTEARRAY;
}
else if (type == (PyObject *)(&PyMemoryView_Type)) {
*mask |= MS_BUILTIN_MEMORYVIEW;
}
else if (type == (PyObject *)(PyDateTimeAPI->DateTimeType)) {
*mask |= MS_BUILTIN_DATETIME;
}
else if (type == (PyObject *)(PyDateTimeAPI->DateType)) {
*mask |= MS_BUILTIN_DATE;
}
else if (type == (PyObject *)(PyDateTimeAPI->TimeType)) {
*mask |= MS_BUILTIN_TIME;
}
else if (type == (PyObject *)(PyDateTimeAPI->DeltaType)) {
*mask |= MS_BUILTIN_TIMEDELTA;
}
else if (type == mod->UUIDType) {
*mask |= MS_BUILTIN_UUID;
}
else if (type == mod->DecimalType) {
*mask |= MS_BUILTIN_DECIMAL;
}
else if (!PyType_Check(type)) {
PyErr_SetString(PyExc_TypeError, invalid_type_err);
goto error;
}
else if (custom_types != NULL) {
forward_builtins_seq = true;
}
else {
PyErr_Format(PyExc_TypeError, "Cannot treat %R as a builtin type", type);
goto error;
}
}
if (forward_builtins_seq) {
*custom_types = seq;
}
else {
Py_DECREF(seq);
}
return 0;
error:
Py_DECREF(seq);
return -1;
}
PyDoc_STRVAR(msgspec_to_builtins__doc__,
"to_builtins(obj, *, str_keys=False, builtin_types=None, enc_hook=None, order=None)\n"
"--\n"
"\n"
"Convert a complex object to one composed only of simpler builtin types\n"
"commonly supported by Python serialization libraries.\n"
"\n"
"This is mainly useful for adding msgspec support for other protocols.\n"
"\n"
"Parameters\n"
"----------\n"
"obj: Any\n"
" The object to convert.\n"
"builtin_types: Iterable[type], optional\n"
" An iterable of types to treat as additional builtin types. These types will\n"
" be passed through ``to_builtins`` unchanged. Currently supports `bytes`,\n"
" `bytearray`, `memoryview`, `datetime.datetime`, `datetime.time`,\n"
" `datetime.date`, `datetime.timedelta`, `uuid.UUID`, `decimal.Decimal`,\n"
" and custom types.\n"
"str_keys: bool, optional\n"
" Whether to convert all object keys to strings. Default is False.\n"
"enc_hook : callable, optional\n"
" A callable to call for objects that aren't supported msgspec types. Takes\n"
" the unsupported object and should return a supported object, or raise a\n"
" ``NotImplementedError`` if unsupported.\n"
"order : {None, 'deterministic', 'sorted'}, optional\n"
" The ordering to use when converting unordered compound types.\n"
"\n"
" - ``None``: All objects are converted in the most efficient manner matching\n"
" their in-memory representations. The default.\n"
" - `'deterministic'`: Unordered collections (sets, dicts) are sorted to\n"
" ensure a consistent output between runs. Useful when comparison/hashing\n"
" of the converted output is necessary.\n"
" - `'sorted'`: Like `'deterministic'`, but *all* object-like types (structs,\n"
" dataclasses, ...) are also sorted by field name before encoding. This is\n"
" slower than `'deterministic'`, but may produce more human-readable output.\n"
"\n"
"Returns\n"
"-------\n"
"Any\n"
" The converted object.\n"
"\n"
"Examples\n"
"--------\n"
">>> import msgspec\n"
">>> class Example(msgspec.Struct):\n"
"... x: set[int]\n"
"... y: bytes\n"
">>> msg = Example({1, 2, 3}, b'\\x01\\x02')\n"
"\n"
"Convert the message to a simpler set of builtin types. Note that by default\n"
"all bytes-like objects are base64-encoded and converted to strings.\n"
"\n"
">>> msgspec.to_builtins(msg)\n"
"{'x': [1, 2, 3], 'y': 'AQI='}\n"
"\n"
"If the downstream code supports binary objects natively, you can\n"
"disable conversion by passing in the types to ``builtin_types``.\n"
"\n"
">>> msgspec.to_builtins(msg, builtin_types=(bytes, bytearray, memoryview))\n"
"{'x': [1, 2, 3], 'y': b'\\x01\\x02'}\n"
"\n"
"See Also\n"
"--------\n"
"msgspec.convert\n"
"msgspec.structs.asdict\n"
"msgspec.structs.astuple"
);
static PyObject*
msgspec_to_builtins(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *obj = NULL, *builtin_types = NULL, *enc_hook = NULL, *order = NULL;
int str_keys = 0;
ToBuiltinsState state;
char *kwlist[] = {"obj", "builtin_types", "str_keys", "enc_hook", "order", NULL};
/* Parse arguments */
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "O|$OpOO", kwlist,
&obj, &builtin_types, &str_keys, &enc_hook, &order
)) {
return NULL;
}
state.mod = msgspec_get_state(self);
state.str_keys = str_keys;
state.builtin_types = 0;
state.builtin_types_seq = NULL;
state.order = parse_order_arg(order);
if (state.order == ORDER_INVALID) return NULL;
if (enc_hook == Py_None) {
enc_hook = NULL;
}
else if (enc_hook != NULL && !PyCallable_Check(enc_hook)) {
PyErr_SetString(PyExc_TypeError, "enc_hook must be callable");
return NULL;
}
state.enc_hook = enc_hook;
if (
ms_process_builtin_types(
state.mod,
builtin_types,
&(state.builtin_types),
&(state.builtin_types_seq)
) < 0
) {
return NULL;
}
PyObject *out = to_builtins(&state, obj, false);
Py_XDECREF(state.builtin_types_seq);
return out;
}
/*************************************************************************
* convert *
*************************************************************************/
typedef struct ConvertState {
MsgspecState *mod;
PyObject *dec_hook;
uint32_t builtin_types;
bool str_keys;
bool from_attributes;
bool strict;
} ConvertState;
static PyObject * convert(ConvertState *, PyObject *, TypeNode *, PathNode *);
static PyObject *
convert_int_uncommon(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (!self->strict) {
uint64_t ux;
bool neg, overflow;
overflow = fast_long_extract_parts(obj, &neg, &ux);
if ((type->types & MS_TYPE_BOOL) && !overflow && !neg) {
if (ux == 0) {
Py_RETURN_FALSE;
}
else if (ux == 1) {
Py_RETURN_TRUE;
}
}
if (type->types & (MS_TYPE_DATETIME | MS_TYPE_TIMEDELTA)) {
int64_t seconds;
if (overflow || ux > LLONG_MAX) {
seconds = LLONG_MAX;
}
else {
seconds = ux;
if (neg) {
seconds *= -1;
}
}
if (type->types & MS_TYPE_DATETIME) {
return datetime_from_epoch(seconds, 0, type, path);
}
return ms_decode_timedelta_from_int64(seconds, path);
}
}
return ms_validation_error("int", type, path);
}
static PyObject *
convert_int(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (MS_LIKELY(type->types & MS_TYPE_INT)) {
return ms_decode_pyint(obj, type, path);
}
else if (type->types & (MS_TYPE_INTENUM | MS_TYPE_INTLITERAL)) {
return ms_decode_int_enum_or_literal_pyint(obj, type, path);
}
else if (type->types & MS_TYPE_FLOAT) {
return ms_decode_float(PyLong_AsDouble(obj), type, path);
}
else if (
type->types & MS_TYPE_DECIMAL
&& !(self->builtin_types & MS_BUILTIN_DECIMAL)
) {
return ms_decode_decimal_from_pyobj(obj, path, self->mod);
}
return convert_int_uncommon(self, obj, type, path);
}
static PyObject *
convert_float(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & MS_TYPE_FLOAT) {
Py_INCREF(obj);
return ms_check_float_constraints(obj, type, path);
}
else if (
type->types & MS_TYPE_DECIMAL
&& !(self->builtin_types & MS_BUILTIN_DECIMAL)
) {
return ms_decode_decimal_from_float(
PyFloat_AS_DOUBLE(obj), path, self->mod
);
}
else if (!self->strict) {
double val = PyFloat_AS_DOUBLE(obj);
if (type->types & MS_TYPE_INT) {
int64_t out;
if (double_as_int64(val, &out)) {
return ms_post_decode_int64(out, type, path, self->strict, false);
}
}
if (type->types & MS_TYPE_DATETIME) {
return ms_decode_datetime_from_float(val, type, path);
}
else if (type->types & MS_TYPE_TIMEDELTA) {
return ms_decode_timedelta_from_float(val, path);
}
}
return ms_validation_error("float", type, path);
}
static PyObject *
convert_bool(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & MS_TYPE_BOOL) {
Py_INCREF(obj);
return obj;
}
return ms_validation_error("bool", type, path);
}
static PyObject *
convert_none(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & MS_TYPE_NONE) {
Py_INCREF(obj);
return obj;
}
return ms_validation_error("null", type, path);
}
static PyObject *
convert_str_uncommon(
ConvertState *self, PyObject *obj, const char *view, Py_ssize_t size,
bool is_key, TypeNode *type, PathNode *path
) {
if (is_key && self->str_keys && (
type->types & (
MS_TYPE_INT | MS_TYPE_INTENUM | MS_TYPE_INTLITERAL |
MS_TYPE_FLOAT | MS_TYPE_DECIMAL |
((!self->strict) * (MS_TYPE_DATETIME | MS_TYPE_TIMEDELTA))
)
)
) {
PyObject *out;
if (maybe_parse_number(view, size, type, path, self->strict, &out)) {
return out;
}
}
if (type->types & (MS_TYPE_ENUM | MS_TYPE_STRLITERAL)) {
return ms_decode_str_enum_or_literal(view, size, type, path);
}
else if (
(type->types & MS_TYPE_DATETIME)
&& !(self->builtin_types & MS_BUILTIN_DATETIME)
) {
return ms_decode_datetime_from_str(view, size, type, path);
}
else if (
(type->types & MS_TYPE_DATE)
&& !(self->builtin_types & MS_BUILTIN_DATE)
) {
return ms_decode_date(view, size, path);
}
else if (
(type->types & MS_TYPE_TIME)
&& !(self->builtin_types & MS_BUILTIN_TIME)
) {
return ms_decode_time(view, size, type, path);
}
else if (
(type->types & MS_TYPE_TIMEDELTA)
&& !(self->builtin_types & MS_BUILTIN_TIMEDELTA)
) {
return ms_decode_timedelta(view, size, type, path);
}
else if (
(type->types & MS_TYPE_UUID)
&& !(self->builtin_types & MS_BUILTIN_UUID)
) {
return ms_decode_uuid_from_str(view, size, path);
}
else if (
(type->types & MS_TYPE_DECIMAL)
&& !(self->builtin_types & MS_BUILTIN_DECIMAL)
) {
return ms_decode_decimal_from_pystr(obj, path, self->mod);
}
else if (
(type->types & MS_TYPE_BYTES)
&& !(self->builtin_types & MS_BUILTIN_BYTES)
) {
return json_decode_binary(view, size, type, path);
}
else if (
(type->types & MS_TYPE_BYTEARRAY)
&& !(self->builtin_types & MS_BUILTIN_BYTEARRAY)
) {
return json_decode_binary(view, size, type, path);
}
else if (
(type->types & MS_TYPE_MEMORYVIEW)
&& !(self->builtin_types & MS_BUILTIN_MEMORYVIEW)
) {
return json_decode_binary(view, size, type, path);
}
return ms_validation_error("str", type, path);
}
static PyObject *
convert_str(
ConvertState *self, PyObject *obj,
bool is_key, TypeNode *type, PathNode *path
) {
if (type->types & (MS_TYPE_ANY | MS_TYPE_STR)) {
Py_INCREF(obj);
return ms_check_str_constraints(obj, type, path);
}
Py_ssize_t size;
const char* view = unicode_str_and_size(obj, &size);
if (view == NULL) return NULL;
if (MS_UNLIKELY(!self->strict)) {
bool invalid = false;
PyObject *out = ms_decode_str_lax(view, size, type, path, &invalid);
if (!invalid) return out;
}
return convert_str_uncommon(self, obj, view, size, is_key, type, path);
}
static PyObject *
convert_bytes(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & (MS_TYPE_BYTES | MS_TYPE_BYTEARRAY | MS_TYPE_MEMORYVIEW)) {
if (!ms_passes_bytes_constraints(PyBytes_GET_SIZE(obj), type, path)) {
return NULL;
}
if (type->types & MS_TYPE_BYTES) {
return PyBytes_FromObject(obj);
}
else if (type->types & MS_TYPE_BYTEARRAY) {
return PyByteArray_FromObject(obj);
}
else {
return PyMemoryView_FromObject(obj);
}
}
if (
(type->types & MS_TYPE_UUID) &&
!(self->builtin_types & MS_BUILTIN_UUID)
) {
return ms_decode_uuid_from_bytes(
PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj), path
);
}
return ms_validation_error("bytes", type, path);
}
static PyObject *
convert_bytearray(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & (MS_TYPE_BYTES | MS_TYPE_BYTEARRAY | MS_TYPE_MEMORYVIEW)) {
if (!ms_passes_bytes_constraints(PyByteArray_GET_SIZE(obj), type, path)) {
return NULL;
}
if (type->types & MS_TYPE_BYTEARRAY) {
Py_INCREF(obj);
return obj;
}
else if (type->types & MS_TYPE_BYTES) {
return PyBytes_FromObject(obj);
}
else {
return PyMemoryView_FromObject(obj);
}
}
if (
(type->types & MS_TYPE_UUID) &&
!(self->builtin_types & MS_BUILTIN_UUID)
) {
return ms_decode_uuid_from_bytes(
PyByteArray_AS_STRING(obj), PyByteArray_GET_SIZE(obj), path
);
}
return ms_validation_error("bytes", type, path);
}
static PyObject *
convert_memoryview(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & (MS_TYPE_BYTES | MS_TYPE_BYTEARRAY | MS_TYPE_MEMORYVIEW)) {
Py_ssize_t len = PyMemoryView_GET_BUFFER(obj)->len;
if (!ms_passes_bytes_constraints(len, type, path)) return NULL;
if (type->types & MS_TYPE_MEMORYVIEW) {
Py_INCREF(obj);
return obj;
}
else if (type->types & MS_TYPE_BYTES) {
return PyBytes_FromObject(obj);
}
else {
return PyByteArray_FromObject(obj);
}
}
if (
(type->types & MS_TYPE_UUID) &&
!(self->builtin_types & MS_BUILTIN_UUID)
) {
Py_buffer buffer;
if (PyObject_GetBuffer(obj, &buffer, PyBUF_CONTIG_RO) < 0) return NULL;
PyObject *out = ms_decode_uuid_from_bytes(
buffer.buf, buffer.len, path
);
PyBuffer_Release(&buffer);
return out;
}
return ms_validation_error("bytes", type, path);
}
static PyObject *
convert_datetime(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & MS_TYPE_DATETIME) {
PyObject *tz = MS_DATE_GET_TZINFO(obj);
if (!ms_passes_tz_constraint(tz, type, path)) return NULL;
Py_INCREF(obj);
return obj;
}
return ms_validation_error("datetime", type, path);
}
static PyObject *
convert_time(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & MS_TYPE_TIME) {
PyObject *tz = MS_TIME_GET_TZINFO(obj);
if (!ms_passes_tz_constraint(tz, type, path)) return NULL;
Py_INCREF(obj);
return obj;
}
return ms_validation_error("time", type, path);
}
static PyObject *
convert_enum(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & MS_TYPE_ENUM) {
StrLookup *lookup = TypeNode_get_str_enum_or_literal(type);
/* Check that the type matches. Note that enums that are also int or
* str subclasses will be handled by `convert_int`/`convert_str`, not
* here */
if (lookup->common.cls != NULL && Py_TYPE(obj) == (PyTypeObject *)(lookup->common.cls)) {
Py_INCREF(obj);
return obj;
}
}
return ms_validation_error(Py_TYPE(obj)->tp_name, type, path);
}
static PyObject *
convert_decimal(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & MS_TYPE_DECIMAL) {
Py_INCREF(obj);
return obj;
}
else if (type->types & MS_TYPE_FLOAT) {
PyObject *temp = PyNumber_Float(obj);
if (temp == NULL) return NULL;
PyObject *out = convert_float(self, temp, type, path);
Py_DECREF(temp);
return out;
}
return ms_validation_error("decimal", type, path);
}
static PyObject *
convert_immutable(
ConvertState *self, uint64_t mask, const char *expected,
PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & mask) {
Py_INCREF(obj);
return obj;
}
return ms_validation_error(expected, type, path);
}
static PyObject *
convert_raw(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types == 0) {
Py_INCREF(obj);
return obj;
}
return ms_validation_error("raw", type, path);
}
static PyObject *
convert_seq_to_list(
ConvertState *self, PyObject **items, Py_ssize_t size,
TypeNode *item_type, PathNode *path
) {
PyObject *out = PyList_New(size);
if (out == NULL) return NULL;
if (size == 0) return out;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
for (Py_ssize_t i = 0; i < size; i++) {
PathNode item_path = {path, i};
PyObject *val = convert(self, items[i], item_type, &item_path);
if (val == NULL) {
Py_CLEAR(out);
break;
}
PyList_SET_ITEM(out, i, val);
}
Py_LeaveRecursiveCall();
return out;
}
static PyObject *
convert_seq_to_set(
ConvertState *self, PyObject **items, Py_ssize_t size,
bool mutable, TypeNode *item_type, PathNode *path
) {
PyObject *out = mutable ? PySet_New(NULL) : PyFrozenSet_New(NULL);
if (out == NULL) return NULL;
if (size == 0) return out;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
for (Py_ssize_t i = 0; i < size; i++) {
PathNode item_path = {path, i};
PyObject *val = convert(self, items[i], item_type, &item_path);
if (MS_UNLIKELY(val == NULL || PySet_Add(out, val) < 0)) {
Py_XDECREF(val);
Py_CLEAR(out);
break;
}
Py_DECREF(val);
}
Py_LeaveRecursiveCall();
return out;
}
static PyObject *
convert_seq_to_vartuple(
ConvertState *self, PyObject **items, Py_ssize_t size,
TypeNode *item_type, PathNode *path
) {
PyObject *out = PyTuple_New(size);
if (out == NULL) return NULL;
if (size == 0) return out;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
for (Py_ssize_t i = 0; i < size; i++) {
PathNode item_path = {path, i};
PyObject *val = convert(self, items[i], item_type, &item_path);
if (val == NULL) {
Py_CLEAR(out);
break;
}
PyTuple_SET_ITEM(out, i, val);
}
Py_LeaveRecursiveCall();
return out;
}
static PyObject *
convert_seq_to_fixtuple(
ConvertState *self, PyObject **items, Py_ssize_t size,
TypeNode *type, PathNode *path
) {
Py_ssize_t fixtuple_size, offset;
TypeNode_get_fixtuple(type, &offset, &fixtuple_size);
if (size != fixtuple_size) {
/* tuple is the incorrect size, raise and return */
ms_raise_validation_error(
path,
"Expected `array` of length %zd, got %zd%U",
fixtuple_size,
size
);
return NULL;
}
PyObject *out = PyTuple_New(size);
if (out == NULL) return NULL;
if (size == 0) return out;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
for (Py_ssize_t i = 0; i < fixtuple_size; i++) {
PathNode item_path = {path, i};
PyObject *val = convert(
self, items[i], type->details[offset + i].pointer, &item_path
);
if (MS_UNLIKELY(val == NULL)) {
Py_CLEAR(out);
break;
}
PyTuple_SET_ITEM(out, i, val);
}
Py_LeaveRecursiveCall();
return out;
}
static PyObject *
convert_seq_to_namedtuple(
ConvertState *self, PyObject **items, Py_ssize_t size,
TypeNode *type, PathNode *path
) {
NamedTupleInfo *info = TypeNode_get_namedtuple_info(type);
Py_ssize_t nfields = Py_SIZE(info);
Py_ssize_t ndefaults = info->defaults == NULL ? 0 : PyTuple_GET_SIZE(info->defaults);
Py_ssize_t nrequired = nfields - ndefaults;
if (size < nrequired || nfields < size) {
/* tuple is the incorrect size, raise and return */
if (ndefaults == 0) {
ms_raise_validation_error(
path,
"Expected `array` of length %zd, got %zd%U",
nfields,
size
);
}
else {
ms_raise_validation_error(
path,
"Expected `array` of length %zd to %zd, got %zd%U",
nrequired,
nfields,
size
);
}
return NULL;
}
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
PyTypeObject *nt_type = (PyTypeObject *)(info->class);
PyObject *out = nt_type->tp_alloc(nt_type, nfields);
if (out == NULL) goto error;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyTuple_SET_ITEM(out, i, NULL);
}
for (Py_ssize_t i = 0; i < size; i++) {
PathNode item_path = {path, i};
PyObject *item = convert(self, items[i], info->types[i], &item_path);
if (MS_UNLIKELY(item == NULL)) goto error;
PyTuple_SET_ITEM(out, i, item);
}
for (Py_ssize_t i = size; i < nfields; i++) {
PyObject *item = PyTuple_GET_ITEM(info->defaults, i - nrequired);
Py_INCREF(item);
PyTuple_SET_ITEM(out, i, item);
}
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_DECREF(out);
return NULL;
}
static bool
convert_tag_matches(
ConvertState *self, PyObject *tag, PyObject *expected_tag, PathNode *path
) {
if (PyUnicode_CheckExact(expected_tag)) {
if (!PyUnicode_CheckExact(tag)) goto wrong_type;
}
else if (!PyLong_CheckExact(tag)) {
goto wrong_type;
}
int status = PyObject_RichCompareBool(tag, expected_tag, Py_EQ);
if (status == 1) return true;
if (status == 0) {
ms_raise_validation_error(path, "Invalid value %R%U", tag);
}
return false;
wrong_type:
ms_raise_validation_error(
path,
"Expected `%s`, got `%s`%U",
(PyUnicode_CheckExact(expected_tag) ? "str" : "int"),
Py_TYPE(tag)->tp_name
);
return false;
}
static StructInfo *
convert_lookup_tag(
ConvertState *self, Lookup *lookup, PyObject *tag, PathNode *path
) {
StructInfo *out = NULL;
if (Lookup_IsStrLookup(lookup)) {
if (!PyUnicode_CheckExact(tag)) goto wrong_type;
Py_ssize_t size;
const char *buf = unicode_str_and_size(tag, &size);
if (buf == NULL) return NULL;
out = (StructInfo *)StrLookup_Get((StrLookup *)lookup, buf, size);
}
else {
if (!PyLong_CheckExact(tag)) goto wrong_type;
uint64_t ux;
bool neg, overflow;
overflow = fast_long_extract_parts(tag, &neg, &ux);
if (overflow) goto invalid_value;
if (neg) {
out = (StructInfo *)IntLookup_GetInt64((IntLookup *)lookup, -(int64_t)ux);
}
else {
out = (StructInfo *)IntLookup_GetUInt64((IntLookup *)lookup, ux);
}
}
if (out != NULL) return out;
invalid_value:
ms_raise_validation_error(path, "Invalid value %R%U", tag);
return NULL;
wrong_type:
ms_raise_validation_error(
path,
"Expected `%s`, got `%s`%U",
(Lookup_IsStrLookup(lookup) ? "str" : "int"),
Py_TYPE(tag)->tp_name
);
return NULL;
}
static PyObject *
convert_seq_to_struct_array_inner(
ConvertState *self, PyObject **items, Py_ssize_t size,
bool tag_already_read, StructInfo *info, PathNode *path
) {
StructMetaObject *st_type = info->class;
PathNode item_path = {path, 0};
bool tagged = st_type->struct_tag_value != NULL;
Py_ssize_t nfields = PyTuple_GET_SIZE(st_type->struct_encode_fields);
Py_ssize_t ndefaults = PyTuple_GET_SIZE(st_type->struct_defaults);
Py_ssize_t nrequired = tagged + nfields - st_type->n_trailing_defaults;
Py_ssize_t npos = nfields - ndefaults;
if (size < nrequired) {
ms_raise_validation_error(
path,
"Expected `array` of at least length %zd, got %zd%U",
nrequired,
size
);
return NULL;
}
if (tagged) {
if (!tag_already_read) {
if (
!convert_tag_matches(
self, items[item_path.index], st_type->struct_tag_value, &item_path
)
) {
return NULL;
}
}
size--;
item_path.index++;
}
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
PyObject *out = Struct_alloc((PyTypeObject *)(st_type));
if (out == NULL) goto error;
bool is_gc = MS_TYPE_IS_GC(st_type);
bool should_untrack = is_gc;
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *val;
if (size > 0) {
val = convert(
self, items[item_path.index], info->types[i], &item_path
);
if (MS_UNLIKELY(val == NULL)) goto error;
size--;
item_path.index++;
}
else {
val = get_default(
PyTuple_GET_ITEM(st_type->struct_defaults, i - npos)
);
if (val == NULL) goto error;
}
Struct_set_index(out, i, val);
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(val);
}
}
if (MS_UNLIKELY(size > 0)) {
if (MS_UNLIKELY(st_type->forbid_unknown_fields == OPT_TRUE)) {
ms_raise_validation_error(
path,
"Expected `array` of at most length %zd, got %zd%U",
nfields,
nfields + size
);
goto error;
}
}
if (Struct_decode_post_init(st_type, out, path) < 0) goto error;
Py_LeaveRecursiveCall();
if (is_gc && !should_untrack)
PyObject_GC_Track(out);
return out;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(out);
return NULL;
}
static PyObject *
convert_seq_to_struct_array(
ConvertState *self, PyObject **items, Py_ssize_t size,
TypeNode *type, PathNode *path
) {
return convert_seq_to_struct_array_inner(
self, items, size, false, TypeNode_get_struct_info(type), path
);
}
static PyObject *
convert_seq_to_struct_array_union(
ConvertState *self, PyObject **items, Py_ssize_t size,
TypeNode *type, PathNode *path
) {
Lookup *lookup = TypeNode_get_struct_union(type);
if (size == 0) {
return ms_error_with_path(
"Expected `array` of at least length 1, got 0%U", path
);
}
PathNode tag_path = {path, 0};
StructInfo *info = convert_lookup_tag(self, lookup, items[0], &tag_path);
if (info == NULL) return NULL;
return convert_seq_to_struct_array_inner(self, items, size, true, info, path);
}
static PyObject *
convert_seq(
ConvertState *self, PyObject **items, Py_ssize_t size,
TypeNode *type, PathNode *path
) {
if (!ms_passes_array_constraints(size, type, path)) return NULL;
if (type->types & MS_TYPE_LIST) {
return convert_seq_to_list(
self, items, size, TypeNode_get_array(type), path
);
}
else if (type->types & (MS_TYPE_SET | MS_TYPE_FROZENSET)) {
return convert_seq_to_set(
self, items, size,
(type->types & MS_TYPE_SET), TypeNode_get_array(type), path
);
}
else if (type->types & MS_TYPE_VARTUPLE) {
return convert_seq_to_vartuple(
self, items, size, TypeNode_get_array(type), path
);
}
else if (type->types & MS_TYPE_FIXTUPLE) {
return convert_seq_to_fixtuple(self, items, size, type, path);
}
else if (type->types & MS_TYPE_NAMEDTUPLE) {
return convert_seq_to_namedtuple(self, items, size, type, path);
}
else if (type->types & MS_TYPE_STRUCT_ARRAY) {
return convert_seq_to_struct_array(self, items, size, type, path);
}
else if (type->types & MS_TYPE_STRUCT_ARRAY_UNION) {
return convert_seq_to_struct_array_union(self, items, size, type, path);
}
return ms_validation_error("array", type, path);
}
static PyObject *
convert_any_set(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
PyObject *seq = PySequence_Tuple(obj);
if (seq == NULL) return NULL;
PyObject **items = PySequence_Fast_ITEMS(seq);
Py_ssize_t size = PySequence_Fast_GET_SIZE(seq);
PyObject *out = NULL;
if (!ms_passes_array_constraints(size, type, path)) goto done;
if (type->types & MS_TYPE_LIST) {
out = convert_seq_to_list(
self, items, size, TypeNode_get_array(type), path
);
}
else if (type->types & (MS_TYPE_SET | MS_TYPE_FROZENSET)) {
out = convert_seq_to_set(
self, items, size,
(type->types & MS_TYPE_SET),
TypeNode_get_array(type), path
);
}
else if (type->types & MS_TYPE_VARTUPLE) {
out = convert_seq_to_vartuple(
self, items, size, TypeNode_get_array(type), path
);
}
else {
ms_validation_error("set", type, path);
}
done:
Py_DECREF(seq);
return out;
}
static PyObject *
convert_dict_to_dict(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
Py_ssize_t size = PyDict_GET_SIZE(obj);
if (!ms_passes_map_constraints(size, type, path)) return NULL;
TypeNode *key_type, *val_type;
TypeNode_get_dict(type, &key_type, &val_type);
PathNode key_path = {path, PATH_KEY, NULL};
PathNode val_path = {path, PATH_ELLIPSIS, NULL};
PyObject *out = PyDict_New();
if (out == NULL) return NULL;
if (PyDict_GET_SIZE(obj) == 0) return out;
if (Py_EnterRecursiveCall(" while deserializing an object")) {
Py_DECREF(out);
return NULL; /* cpylint-ignore */
}
PyObject *key_obj = NULL, *val_obj = NULL;
Py_ssize_t pos = 0;
while (PyDict_Next(obj, &pos, &key_obj, &val_obj)) {
PyObject *key;
if (PyUnicode_CheckExact(key_obj)) {
key = convert_str(self, key_obj, true, key_type, &key_path);
}
else {
key = convert(self, key_obj, key_type, &key_path);
}
if (MS_UNLIKELY(key == NULL)) goto error;
PyObject *val = convert(self, val_obj, val_type, &val_path);
if (MS_UNLIKELY(val == NULL)) {
Py_DECREF(key);
goto error;
}
int status = PyDict_SetItem(out, key, val);
Py_DECREF(key);
Py_DECREF(val);
if (status < 0) goto error;
}
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_DECREF(out);
return NULL;
}
static PyObject *
convert_mapping_to_dict(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
PyObject *out = NULL;
PyObject *temp = PyDict_New();
if (temp == NULL) return NULL;
if (PyDict_Merge(temp, obj, 1) == 0) {
out = convert_dict_to_dict(self, temp, type, path);
}
Py_DECREF(temp);
return out;
}
static bool
convert_is_str_key(PyObject *key, PathNode *path) {
if (PyUnicode_CheckExact(key)) return true;
PathNode key_path = {path, PATH_KEY, NULL};
ms_error_with_path("Expected `str`%U", &key_path);
return false;
}
static PyObject *
convert_dict_to_struct(
ConvertState *self, PyObject *obj, StructInfo *info, PathNode *path,
bool tag_already_read
) {
StructMetaObject *struct_type = info->class;
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
PyObject *out = Struct_alloc((PyTypeObject *)(struct_type));
if (out == NULL) goto error;
Py_ssize_t pos = 0, pos_obj = 0;
PyObject *key_obj, *val_obj;
while (PyDict_Next(obj, &pos_obj, &key_obj, &val_obj)) {
if (!convert_is_str_key(key_obj, path)) goto error;
Py_ssize_t key_size;
const char *key = unicode_str_and_size(key_obj, &key_size);
if (key == NULL) goto error;
Py_ssize_t field_index = StructMeta_get_field_index(struct_type, key, key_size, &pos);
if (field_index < 0) {
if (MS_UNLIKELY(field_index == -2)) {
if (tag_already_read) continue;
PathNode tag_path = {path, PATH_STR, struct_type->struct_tag_field};
if (
!convert_tag_matches(
self, val_obj, struct_type->struct_tag_value, &tag_path
)
) {
goto error;
}
}
else {
/* Unknown field */
if (MS_UNLIKELY(struct_type->forbid_unknown_fields == OPT_TRUE)) {
ms_error_unknown_field(key, key_size, path);
goto error;
}
}
}
else {
PathNode field_path = {path, field_index, (PyObject *)struct_type};
PyObject *val = convert(
self, val_obj, info->types[field_index], &field_path
);
if (val == NULL) goto error;
Struct_set_index(out, field_index, val);
}
}
if (Struct_fill_in_defaults(struct_type, out, path) < 0) goto error;
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(out);
return NULL;
}
static PyObject *
convert_dict_to_struct_union(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
Lookup *lookup = TypeNode_get_struct_union(type);
PyObject *tag_field = Lookup_tag_field(lookup);
PyObject *value = PyDict_GetItem(obj, tag_field);
if (value != NULL) {
PathNode tag_path = {path, PATH_STR, tag_field};
StructInfo *info = convert_lookup_tag(
self, lookup, value, &tag_path
);
if (info == NULL) return NULL;
return convert_dict_to_struct(self, obj, info, path, true);
}
ms_missing_required_field(tag_field, path);
return NULL;
}
static PyObject *
convert_dict_to_typeddict(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
PyObject *out = PyDict_New();
if (out == NULL) goto error;
TypedDictInfo *info = TypeNode_get_typeddict_info(type);
Py_ssize_t nrequired = 0, pos = 0, pos_obj = 0;
PyObject *key_obj, *val_obj;
while (PyDict_Next(obj, &pos_obj, &key_obj, &val_obj)) {
if (!convert_is_str_key(key_obj, path)) goto error;
Py_ssize_t key_size;
const char *key = unicode_str_and_size(key_obj, &key_size);
if (key == NULL) goto error;
TypeNode *field_type;
PyObject *field = TypedDictInfo_lookup_key(
info, key, key_size, &field_type, &pos
);
if (field != NULL) {
if (field_type->types & MS_EXTRA_FLAG) nrequired++;
PathNode field_path = {path, PATH_STR, field};
PyObject *val = convert(self, val_obj, field_type, &field_path);
if (val == NULL) goto error;
int status = PyDict_SetItem(out, field, val);
Py_DECREF(val);
if (status < 0) goto error;
}
}
if (nrequired < info->nrequired) {
/* A required field is missing, determine which one and raise */
TypedDictInfo_error_missing(info, out, path);
goto error;
}
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(out);
return NULL;
}
static PyObject *
convert_dict_to_dataclass(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
DataclassInfo *info = TypeNode_get_dataclass_info(type);
PyTypeObject *dataclass_type = (PyTypeObject *)(info->class);
PyObject *out = dataclass_type->tp_alloc(dataclass_type, 0);
if (out == NULL) goto error;
if (info->pre_init != NULL) {
PyObject *res = PyObject_CallOneArg(info->pre_init, out);
if (res == NULL) goto error;
Py_DECREF(res);
}
Py_ssize_t pos = 0, pos_obj = 0;
PyObject *key_obj = NULL, *val_obj = NULL;
while (PyDict_Next(obj, &pos_obj, &key_obj, &val_obj)) {
if (!convert_is_str_key(key_obj, path)) goto error;
Py_ssize_t key_size;
const char *key = unicode_str_and_size(key_obj, &key_size);
if (MS_UNLIKELY(key == NULL)) goto error;
TypeNode *field_type;
PyObject *field = DataclassInfo_lookup_key(
info, key, key_size, &field_type, &pos
);
if (field != NULL) {
PathNode field_path = {path, PATH_STR, field};
PyObject *val = convert(self, val_obj, field_type, &field_path);
if (val == NULL) goto error;
int status = PyObject_GenericSetAttr(out, field, val);
Py_DECREF(val);
if (status < 0) goto error;
}
}
if (DataclassInfo_post_decode(info, out, path) < 0) goto error;
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(out);
return NULL;
}
static PyObject *
convert_dict(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (type->types & MS_TYPE_DICT) {
return convert_dict_to_dict(self, obj, type, path);
}
else if (type->types & MS_TYPE_STRUCT) {
StructInfo *info = TypeNode_get_struct_info(type);
return convert_dict_to_struct(self, obj, info, path, false);
}
else if (type->types & MS_TYPE_STRUCT_UNION) {
return convert_dict_to_struct_union(self, obj, type, path);
}
else if (type->types & MS_TYPE_TYPEDDICT) {
return convert_dict_to_typeddict(self, obj, type, path);
}
else if (type->types & MS_TYPE_DATACLASS) {
return convert_dict_to_dataclass(self, obj, type, path);
}
return ms_validation_error("object", type, path);
}
static PyObject *
convert_object_to_struct(
ConvertState *self, PyObject *obj, StructInfo *info, PathNode *path,
PyObject* (*getter)(PyObject *, PyObject *), bool tag_already_read
) {
StructMetaObject *struct_type = info->class;
Py_ssize_t nfields = PyTuple_GET_SIZE(struct_type->struct_encode_fields);
Py_ssize_t ndefaults = PyTuple_GET_SIZE(struct_type->struct_defaults);
if (struct_type->struct_tag_value != NULL && !tag_already_read) {
PyObject *attr = getter(obj, struct_type->struct_tag_field);
if (attr != NULL) {
PathNode tag_path = {path, PATH_STR, struct_type->struct_tag_field};
bool ok = convert_tag_matches(
self, attr, struct_type->struct_tag_value, &tag_path
);
Py_DECREF(attr);
if (!ok) return NULL;
}
else {
/* Tag not present, ignore and continue */
PyErr_Clear();
}
}
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
PyObject *out = Struct_alloc((PyTypeObject *)(struct_type));
if (out == NULL) goto error;
bool is_gc = MS_TYPE_IS_GC(struct_type);
bool should_untrack = is_gc;
/* If no fields are renamed we only have one fields tuple to choose from */
PyObject *fields = NULL;
if (struct_type->struct_fields == struct_type->struct_encode_fields) {
fields = struct_type->struct_fields;
}
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *field, *attr, *val;
if (MS_LIKELY(fields != NULL)) {
/* fields tuple already determined, just get the next field name */
field = PyTuple_GET_ITEM(fields, i);
attr = getter(obj, field);
}
else {
/* fields tuple undetermined. Try the attribute name first */
PyObject *encode_field;
field = PyTuple_GET_ITEM(struct_type->struct_fields, i);
encode_field = PyTuple_GET_ITEM(struct_type->struct_encode_fields, i);
attr = getter(obj, field);
if (field != encode_field) {
/* The field _was_ renamed */
if (attr != NULL) {
/* Got a match, lock-in using attribute names */
fields = struct_type->struct_fields;
}
else {
/* No match. Try using the renamed name */
PyErr_Clear();
attr = getter(obj, encode_field);
if (attr != NULL) {
/* Got a match, lock-in using renamed names */
field = encode_field;
fields = struct_type->struct_encode_fields;
}
}
}
}
if (attr != NULL) {
PathNode field_path = {path, PATH_STR, field};
val = convert(self, attr, info->types[i], &field_path);
Py_DECREF(attr);
}
else {
PyErr_Clear();
PyObject *default_val = NULL;
if (MS_LIKELY(i >= (nfields - ndefaults))) {
default_val = PyTuple_GET_ITEM(
struct_type->struct_defaults, i - (nfields - ndefaults)
);
if (MS_UNLIKELY(default_val == NODEFAULT)) {
default_val = NULL;
}
}
if (default_val == NULL) {
ms_missing_required_field(field, path);
goto error;
}
val = get_default(default_val);
}
if (val == NULL) goto error;
Struct_set_index(out, i, val);
if (should_untrack) {
should_untrack = !MS_MAYBE_TRACKED(val);
}
}
if (Struct_decode_post_init(struct_type, out, path) < 0) goto error;
Py_LeaveRecursiveCall();
if (is_gc && !should_untrack)
PyObject_GC_Track(out);
return out;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(out);
return NULL;
}
static PyObject *
convert_object_to_struct_union(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path,
PyObject* (*getter)(PyObject *, PyObject *)
) {
Lookup *lookup = TypeNode_get_struct_union(type);
PyObject *tag_field = Lookup_tag_field(lookup);
PyObject *value = getter(obj, tag_field);
if (value != NULL) {
PathNode tag_path = {path, PATH_STR, tag_field};
StructInfo *info = convert_lookup_tag(
self, lookup, value, &tag_path
);
Py_DECREF(value);
if (info == NULL) return NULL;
return convert_object_to_struct(self, obj, info, path, getter, true);
}
ms_missing_required_field(tag_field, path);
return NULL;
}
static PyObject *
convert_object_to_dataclass(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path,
PyObject* (*getter)(PyObject *, PyObject *)
) {
DataclassInfo *info = TypeNode_get_dataclass_info(type);
Py_ssize_t nfields = Py_SIZE(info);
Py_ssize_t ndefaults = PyTuple_GET_SIZE(info->defaults);
if (Py_EnterRecursiveCall(" while deserializing an object")) return NULL;
PyTypeObject *dataclass_type = (PyTypeObject *)(info->class);
PyObject *out = dataclass_type->tp_alloc(dataclass_type, 0);
if (out == NULL) goto error;
if (info->pre_init != NULL) {
PyObject *res = PyObject_CallOneArg(info->pre_init, out);
if (res == NULL) goto error;
Py_DECREF(res);
}
for (Py_ssize_t i = 0; i < nfields; i++) {
PyObject *field = info->fields[i].key;
PyObject *attr = getter(obj, field);
PyObject *val;
if (attr == NULL) {
PyErr_Clear();
if (MS_LIKELY(i >= (nfields - ndefaults))) {
PyObject *default_val = PyTuple_GET_ITEM(
info->defaults, i - (nfields - ndefaults)
);
bool is_factory = info->fields[i].type->types & MS_EXTRA_FLAG;
if (is_factory) {
val = PyObject_CallNoArgs(default_val);
}
else {
Py_INCREF(default_val);
val = default_val;
}
}
else {
ms_missing_required_field(field, path);
goto error;
}
}
else {
PathNode field_path = {path, PATH_STR, field};
val = convert(self, attr, info->fields[i].type, &field_path);
Py_DECREF(attr);
}
if (val == NULL) goto error;
int status = PyObject_GenericSetAttr(out, field, val);
Py_DECREF(val);
if (status < 0) goto error;
}
if (info->post_init != NULL) {
PyObject *res = PyObject_CallOneArg(info->post_init, out);
if (res == NULL) {
ms_maybe_wrap_validation_error(path);
goto error;
}
Py_DECREF(res);
}
Py_LeaveRecursiveCall();
return out;
error:
Py_LeaveRecursiveCall();
Py_XDECREF(out);
return NULL;
}
static bool
Lookup_union_contains_type(Lookup *lookup, PyTypeObject *cls) {
if (Lookup_IsStrLookup(lookup)) {
StrLookup *lk = (StrLookup *)lookup;
for (Py_ssize_t i = 0; i < Py_SIZE(lk); i++) {
StructInfo *info = (StructInfo *)(lk->table[i].value);
if (info != NULL && ((PyTypeObject *)(info->class) == cls)) {
return true;
}
}
}
else {
if (((IntLookup *)lookup)->compact) {
IntLookupCompact *lk = (IntLookupCompact *)lookup;
for (Py_ssize_t i = 0; i < Py_SIZE(lk); i++) {
StructInfo *info = (StructInfo *)(lk->table[i]);
if (info != NULL && ((PyTypeObject *)(info->class) == cls)) {
return true;
}
}
}
else {
IntLookupHashmap *lk = (IntLookupHashmap *)lookup;
for (Py_ssize_t i = 0; i < Py_SIZE(lk); i++) {
StructInfo *info = (StructInfo *)(lk->table[i].value);
if (info != NULL && ((PyTypeObject *)(info->class) == cls)) {
return true;
}
}
}
}
return false;
}
static PyObject *
getattr_then_getitem(PyObject *obj, PyObject *key) {
PyObject *out = PyObject_GetAttr(obj, key);
if (out == NULL) {
PyErr_Clear();
out = PyObject_GetItem(obj, key);
}
return out;
}
static PyObject *
convert_other(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
PyTypeObject *pytype = Py_TYPE(obj);
/* First check if instance matches requested type for builtin user-defined
* collection types. */
if (type->types & (MS_TYPE_STRUCT | MS_TYPE_STRUCT_ARRAY)) {
StructInfo *info = TypeNode_get_struct_info(type);
if (pytype == (PyTypeObject *)(info->class)) {
Py_INCREF(obj);
return obj;
}
}
else if (type->types & (MS_TYPE_STRUCT_UNION | MS_TYPE_STRUCT_ARRAY_UNION)) {
Lookup *lookup = TypeNode_get_struct_union(type);
if (Lookup_union_contains_type(lookup, pytype)) {
Py_INCREF(obj);
return obj;
}
}
else if (type->types & MS_TYPE_DATACLASS) {
DataclassInfo *info = TypeNode_get_dataclass_info(type);
if (pytype == (PyTypeObject *)(info->class)) {
Py_INCREF(obj);
return obj;
}
}
else if (type->types & MS_TYPE_NAMEDTUPLE) {
NamedTupleInfo *info = TypeNode_get_namedtuple_info(type);
if (pytype == (PyTypeObject *)(info->class)) {
Py_INCREF(obj);
return obj;
}
}
/* No luck. Next check if it's a tuple subclass (standard tuples are
* handled earlier), and if so try converting it as a sequence */
if (PyTuple_Check(obj)) {
return convert_seq(self, TUPLE_ITEMS(obj), PyTuple_GET_SIZE(obj), type, path);
}
/* Next try converting from a mapping or by attribute */
bool is_mapping = PyMapping_Check(obj);
if (is_mapping && type->types & MS_TYPE_DICT) {
return convert_mapping_to_dict(self, obj, type, path);
}
if (is_mapping || self->from_attributes) {
PyObject* (*getter)(PyObject *, PyObject *);
/* We want to exclude array_like structs when converting from a
* mapping, but include them when converting by attribute */
bool matches_struct, matches_struct_union;
if (self->from_attributes) {
getter = (is_mapping) ? getattr_then_getitem : PyObject_GetAttr;
matches_struct = type->types & (MS_TYPE_STRUCT | MS_TYPE_STRUCT_ARRAY);
matches_struct_union = type->types & (MS_TYPE_STRUCT_UNION | MS_TYPE_STRUCT_ARRAY_UNION);
}
else {
getter = getattr_then_getitem;
matches_struct = type->types & MS_TYPE_STRUCT;
matches_struct_union = type->types & MS_TYPE_STRUCT_UNION;
}
if (matches_struct) {
StructInfo *info = TypeNode_get_struct_info(type);
return convert_object_to_struct(self, obj, info, path, getter, false);
}
else if (matches_struct_union) {
return convert_object_to_struct_union(self, obj, type, path, getter);
}
else if (type->types & MS_TYPE_DATACLASS) {
return convert_object_to_dataclass(self, obj, type, path, getter);
}
}
return ms_validation_error(Py_TYPE(obj)->tp_name, type, path);
}
static PyObject *
convert(
ConvertState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
if (MS_UNLIKELY(type->types & (MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC | MS_TYPE_ANY))) {
Py_INCREF(obj);
if (MS_UNLIKELY(type->types & (MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC))) {
return ms_decode_custom(obj, self->dec_hook, type, path);
}
return obj;
}
PyTypeObject *pytype = Py_TYPE(obj);
if (PyUnicode_Check(obj)) {
return convert_str(self, obj, false, type, path);
}
else if (pytype == &PyBool_Type) {
return convert_bool(self, obj, type, path);
}
else if (PyLong_Check(obj)) {
return convert_int(self, obj, type, path);
}
else if (pytype == &PyFloat_Type) {
return convert_float(self, obj, type, path);
}
else if (PyList_Check(obj)) {
return convert_seq(self, LIST_ITEMS(obj), PyList_GET_SIZE(obj), type, path);
}
else if (pytype == &PyTuple_Type) {
/* Tuple subclasses are handled later on */
return convert_seq(self, TUPLE_ITEMS(obj), PyTuple_GET_SIZE(obj), type, path);
}
else if (PyDict_Check(obj)) {
return convert_dict(self, obj, type, path);
}
else if (obj == Py_None) {
return convert_none(self, obj, type, path);
}
else if (PyBytes_Check(obj)) {
return convert_bytes(self, obj, type, path);
}
else if (pytype == &PyByteArray_Type) {
return convert_bytearray(self, obj, type, path);
}
else if (pytype == &PyMemoryView_Type) {
return convert_memoryview(self, obj, type, path);
}
else if (pytype == PyDateTimeAPI->DateTimeType) {
return convert_datetime(self, obj, type, path);
}
else if (pytype == PyDateTimeAPI->TimeType) {
return convert_time(self, obj, type, path);
}
else if (pytype == PyDateTimeAPI->DateType) {
return convert_immutable(self, MS_TYPE_DATE, "date", obj, type, path);
}
else if (pytype == PyDateTimeAPI->DeltaType) {
return convert_immutable(self, MS_TYPE_TIMEDELTA, "duration", obj, type, path);
}
else if (PyType_IsSubtype(pytype, (PyTypeObject *)(self->mod->UUIDType))) {
return convert_immutable(self, MS_TYPE_UUID, "uuid", obj, type, path);
}
else if (pytype == (PyTypeObject *)self->mod->DecimalType) {
return convert_decimal(self, obj, type, path);
}
else if (Py_TYPE(pytype) == self->mod->EnumMetaType) {
return convert_enum(self, obj, type, path);
}
else if (pytype == &Ext_Type) {
return convert_immutable(self, MS_TYPE_EXT, "ext", obj, type, path);
}
else if (pytype == &Raw_Type) {
return convert_raw(self, obj, type, path);
}
else if (PyAnySet_Check(obj)) {
return convert_any_set(self, obj, type, path);
}
else {
return convert_other(self, obj, type, path);
}
}
PyDoc_STRVAR(msgspec_convert__doc__,
"convert(obj, type, *, strict=True, from_attributes=False, dec_hook=None, str_keys=False, builtin_types=None)\n"
"--\n"
"\n"
"Convert the input object to the specified type, or error accordingly.\n"
"\n"
"Parameters\n"
"----------\n"
"obj: Any\n"
" The object to convert.\n"
"type: Type\n"
" A Python type (in type annotation form) to convert the object to.\n"
"strict: bool, optional\n"
" Whether type coercion rules should be strict. Setting to False enables a\n"
" wider set of coercion rules from string to non-string types for all values.\n"
" Setting ``strict=False`` implies ``str_keys=True, builtin_types=None``.\n"
" Default is True.\n"
"from_attributes: bool, optional\n"
" If True, input objects may be coerced to ``Struct``/``dataclass``/``attrs``\n"
" types by extracting attributes from the input matching fields in the output\n"
" type. One use case is converting database query results (ORM or otherwise)\n"
" to msgspec structured types. Default is False.\n"
"dec_hook: callable, optional\n"
" An optional callback for handling decoding custom types. Should have the\n"
" signature ``dec_hook(type: Type, obj: Any) -> Any``, where ``type`` is the\n"
" expected message type, and ``obj`` is the decoded representation composed\n"
" of only basic MessagePack types. This hook should transform ``obj`` into\n"
" type ``type``, or raise a ``NotImplementedError`` if unsupported.\n"
"builtin_types: Iterable[type], optional\n"
" Useful for wrapping other serialization protocols. An iterable of types to\n"
" treat as additional builtin types. Passing a type here indicates that the\n"
" wrapped protocol natively supports that type, disabling any coercion to\n"
" that type provided by `convert`. For example, passing\n"
" ``builtin_types=(datetime,)`` disables the default ``str`` to ``datetime``\n"
" conversion; the wrapped protocol must provide a ``datetime`` object\n"
" directly. Currently supports `bytes`, `bytearray`, `datetime.datetime`,\n"
" `datetime.time`, `datetime.date`, `datetime.timedelta`, `uuid.UUID`, and\n"
" `decimal.Decimal`.\n"
"str_keys: bool, optional\n"
" Useful for wrapping other serialization protocols. Indicates whether the\n"
" wrapped protocol only supports string keys. Setting to True enables a wider\n"
" set of coercion rules from string to non-string types for dict keys.\n"
" Default is False.\n"
"\n"
"Returns\n"
"-------\n"
"Any\n"
" The converted object of the specified ``type``.\n"
"\n"
"Examples\n"
"--------\n"
">>> import msgspec\n"
">>> class Example(msgspec.Struct):\n"
"... x: set[int]\n"
"... y: bytes\n"
">>> msg = {'x': [1, 2, 3], 'y': 'AQI='}\n"
"\n"
"Construct the message from a simpler set of builtin types.\n"
"\n"
">>> msgspec.convert(msg, Example)\n"
"Example({1, 2, 3}, b'\\x01\\x02')\n"
"\n"
"See Also\n"
"--------\n"
"to_builtins"
);
static PyObject*
msgspec_convert(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *obj = NULL, *pytype = NULL, *builtin_types = NULL, *dec_hook = NULL;
int str_keys = false, strict = true, from_attributes = false;
ConvertState state;
char *kwlist[] = {
"obj", "type", "strict", "from_attributes", "dec_hook", "builtin_types",
"str_keys", NULL
};
/* Parse arguments */
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "OO|$ppOOp", kwlist,
&obj, &pytype, &strict, &from_attributes, &dec_hook, &builtin_types, &str_keys
)) {
return NULL;
}
state.mod = msgspec_get_state(self);
state.builtin_types = 0;
state.from_attributes = from_attributes;
state.strict = strict;
if (strict) {
state.str_keys = str_keys;
if (ms_process_builtin_types(state.mod, builtin_types, &(state.builtin_types), NULL) < 0) {
return NULL;
}
}
else {
state.str_keys = true;
}
if (dec_hook == Py_None) {
dec_hook = NULL;
}
else if (dec_hook != NULL && !PyCallable_Check(dec_hook)) {
PyErr_SetString(PyExc_TypeError, "dec_hook must be callable");
return NULL;
}
state.dec_hook = dec_hook;
/* Avoid allocating a new TypeNode for struct types */
if (Py_TYPE(pytype) == &StructMetaType) {
PyObject *info = StructInfo_Convert(pytype);
if (info == NULL) return NULL;
bool array_like = ((StructMetaObject *)pytype)->array_like == OPT_TRUE;
TypeNodeSimple type;
type.types = array_like ? MS_TYPE_STRUCT_ARRAY : MS_TYPE_STRUCT;
type.details[0].pointer = info;
PyObject *out = convert(&state, obj, (TypeNode *)(&type), NULL);
Py_DECREF(info);
return out;
}
TypeNode *type = TypeNode_Convert(pytype);
if (type == NULL) return NULL;
PyObject *out = convert(&state, obj, type, NULL);
TypeNode_Free(type);
return out;
}
/*************************************************************************
* Module Setup *
*************************************************************************/
static struct PyMethodDef msgspec_methods[] = {
{
"replace", (PyCFunction) struct_replace, METH_FASTCALL | METH_KEYWORDS,
struct_replace__doc__,
},
{
"asdict", (PyCFunction) struct_asdict, METH_FASTCALL, struct_asdict__doc__,
},
{
"astuple", (PyCFunction) struct_astuple, METH_FASTCALL, struct_astuple__doc__,
},
{
"defstruct", (PyCFunction) msgspec_defstruct, METH_VARARGS | METH_KEYWORDS,
msgspec_defstruct__doc__,
},
{
"force_setattr", (PyCFunction) struct_force_setattr, METH_FASTCALL,
struct_force_setattr__doc__,
},
{
"msgpack_encode", (PyCFunction) msgspec_msgpack_encode, METH_FASTCALL | METH_KEYWORDS,
msgspec_msgpack_encode__doc__,
},
{
"msgpack_decode", (PyCFunction) msgspec_msgpack_decode, METH_FASTCALL | METH_KEYWORDS,
msgspec_msgpack_decode__doc__,
},
{
"json_encode", (PyCFunction) msgspec_json_encode, METH_FASTCALL | METH_KEYWORDS,
msgspec_json_encode__doc__,
},
{
"json_decode", (PyCFunction) msgspec_json_decode, METH_FASTCALL | METH_KEYWORDS,
msgspec_json_decode__doc__,
},
{
"json_format", (PyCFunction) msgspec_json_format, METH_VARARGS | METH_KEYWORDS,
msgspec_json_format__doc__,
},
{
"to_builtins", (PyCFunction) msgspec_to_builtins, METH_VARARGS | METH_KEYWORDS,
msgspec_to_builtins__doc__,
},
{
"convert", (PyCFunction) msgspec_convert, METH_VARARGS | METH_KEYWORDS,
msgspec_convert__doc__,
},
{NULL, NULL} /* sentinel */
};
static int
msgspec_clear(PyObject *m)
{
MsgspecState *st = msgspec_get_state(m);
Py_CLEAR(st->MsgspecError);
Py_CLEAR(st->EncodeError);
Py_CLEAR(st->DecodeError);
Py_CLEAR(st->StructType);
Py_CLEAR(st->EnumMetaType);
Py_CLEAR(st->struct_lookup_cache);
Py_CLEAR(st->str___weakref__);
Py_CLEAR(st->str___dict__);
Py_CLEAR(st->str___msgspec_cached_hash__);
Py_CLEAR(st->str__value2member_map_);
Py_CLEAR(st->str___msgspec_cache__);
Py_CLEAR(st->str__value_);
Py_CLEAR(st->str__missing_);
Py_CLEAR(st->str_type);
Py_CLEAR(st->str_enc_hook);
Py_CLEAR(st->str_dec_hook);
Py_CLEAR(st->str_ext_hook);
Py_CLEAR(st->str_strict);
Py_CLEAR(st->str_order);
Py_CLEAR(st->str_utcoffset);
Py_CLEAR(st->str___origin__);
Py_CLEAR(st->str___args__);
Py_CLEAR(st->str___metadata__);
Py_CLEAR(st->str___total__);
Py_CLEAR(st->str___required_keys__);
Py_CLEAR(st->str__fields);
Py_CLEAR(st->str__field_defaults);
Py_CLEAR(st->str___post_init__);
Py_CLEAR(st->str___dataclass_fields__);
Py_CLEAR(st->str___attrs_attrs__);
Py_CLEAR(st->str___supertype__);
#if PY312_PLUS
Py_CLEAR(st->str___value__);
#endif
Py_CLEAR(st->str___bound__);
Py_CLEAR(st->str___constraints__);
Py_CLEAR(st->str_int);
Py_CLEAR(st->str_is_safe);
Py_CLEAR(st->UUIDType);
Py_CLEAR(st->uuid_safeuuid_unknown);
Py_CLEAR(st->DecimalType);
Py_CLEAR(st->typing_union);
Py_CLEAR(st->typing_any);
Py_CLEAR(st->typing_literal);
Py_CLEAR(st->typing_classvar);
Py_CLEAR(st->typing_typevar);
Py_CLEAR(st->typing_final);
Py_CLEAR(st->typing_generic);
Py_CLEAR(st->typing_generic_alias);
Py_CLEAR(st->typing_annotated_alias);
Py_CLEAR(st->concrete_types);
Py_CLEAR(st->get_type_hints);
Py_CLEAR(st->get_class_annotations);
Py_CLEAR(st->get_typeddict_info);
Py_CLEAR(st->get_dataclass_info);
Py_CLEAR(st->rebuild);
#if PY310_PLUS
Py_CLEAR(st->types_uniontype);
#endif
#if PY312_PLUS
Py_CLEAR(st->typing_typealiastype);
#endif
Py_CLEAR(st->astimezone);
Py_CLEAR(st->re_compile);
return 0;
}
static void
msgspec_free(PyObject *m)
{
msgspec_clear(m);
}
static int
msgspec_traverse(PyObject *m, visitproc visit, void *arg)
{
MsgspecState *st = msgspec_get_state(m);
/* Clear the string cache every 10 major GC passes.
*
* The string cache can help improve performance in 2 different situations:
*
* - Calling untyped `json.decode` on a large message, where many keys are
* repeated within the same message.
* - Calling untyped `json.decode` in a hot loop on many messages that
* share the same structure.
*
* In both cases, the string cache helps because common keys are more
* likely to remain in cache. We do want to periodically clear the cache so
* the allocator can free up old pages and reduce fragmentation, but we
* want to do so as infrequently as possible. I've arbitrarily picked 10
* major GC passes here as a heuristic.
*
* With the current configuration, the string cache may consume up to 20
* KiB at a time, but that's with 100% of slots filled (unlikely due to
* collisions). 50% filled is more likely, so 12 KiB max is a reasonable
* estimate.
*/
st->gc_cycle++;
if (st->gc_cycle == 10) {
st->gc_cycle = 0;
string_cache_clear();
timezone_cache_clear();
}
Py_VISIT(st->MsgspecError);
Py_VISIT(st->EncodeError);
Py_VISIT(st->DecodeError);
Py_VISIT(st->StructType);
Py_VISIT(st->EnumMetaType);
Py_VISIT(st->struct_lookup_cache);
Py_VISIT(st->typing_union);
Py_VISIT(st->typing_any);
Py_VISIT(st->typing_literal);
Py_VISIT(st->typing_classvar);
Py_VISIT(st->typing_typevar);
Py_VISIT(st->typing_final);
Py_VISIT(st->typing_generic);
Py_VISIT(st->typing_generic_alias);
Py_VISIT(st->typing_annotated_alias);
Py_VISIT(st->concrete_types);
Py_VISIT(st->get_type_hints);
Py_VISIT(st->get_class_annotations);
Py_VISIT(st->get_typeddict_info);
Py_VISIT(st->get_dataclass_info);
Py_VISIT(st->rebuild);
#if PY310_PLUS
Py_VISIT(st->types_uniontype);
#endif
#if PY312_PLUS
Py_VISIT(st->typing_typealiastype);
#endif
Py_VISIT(st->astimezone);
Py_VISIT(st->re_compile);
return 0;
}
static struct PyModuleDef msgspecmodule = {
PyModuleDef_HEAD_INIT,
.m_name = "msgspec._core",
.m_size = sizeof(MsgspecState),
.m_methods = msgspec_methods,
.m_traverse = msgspec_traverse,
.m_clear = msgspec_clear,
.m_free =(freefunc)msgspec_free
};
PyMODINIT_FUNC
PyInit__core(void)
{
PyObject *m, *temp_module, *temp_obj;
MsgspecState *st;
PyDateTime_IMPORT;
m = PyState_FindModule(&msgspecmodule);
if (m) {
Py_INCREF(m);
return m;
}
StructMetaType.tp_base = &PyType_Type;
if (PyType_Ready(&NoDefault_Type) < 0)
return NULL;
if (PyType_Ready(&Unset_Type) < 0)
return NULL;
if (PyType_Ready(&Factory_Type) < 0)
return NULL;
if (PyType_Ready(&Field_Type) < 0)
return NULL;
if (PyType_Ready(&IntLookup_Type) < 0)
return NULL;
if (PyType_Ready(&StrLookup_Type) < 0)
return NULL;
if (PyType_Ready(&LiteralInfo_Type) < 0)
return NULL;
if (PyType_Ready(&TypedDictInfo_Type) < 0)
return NULL;
if (PyType_Ready(&DataclassInfo_Type) < 0)
return NULL;
if (PyType_Ready(&NamedTupleInfo_Type) < 0)
return NULL;
if (PyType_Ready(&StructInfo_Type) < 0)
return NULL;
if (PyType_Ready(&Meta_Type) < 0)
return NULL;
if (PyType_Ready(&StructMetaType) < 0)
return NULL;
if (PyType_Ready(&StructMixinType) < 0)
return NULL;
if (PyType_Ready(&StructConfig_Type) < 0)
return NULL;
if (PyType_Ready(&Encoder_Type) < 0)
return NULL;
if (PyType_Ready(&Decoder_Type) < 0)
return NULL;
if (PyType_Ready(&Ext_Type) < 0)
return NULL;
if (PyType_Ready(&Raw_Type) < 0)
return NULL;
if (PyType_Ready(&JSONEncoder_Type) < 0)
return NULL;
if (PyType_Ready(&JSONDecoder_Type) < 0)
return NULL;
/* Create the module */
m = PyModule_Create(&msgspecmodule);
if (m == NULL)
return NULL;
/* Add types */
Py_INCREF(&Factory_Type);
if (PyModule_AddObject(m, "Factory", (PyObject *)&Factory_Type) < 0)
return NULL;
if (PyModule_AddObject(m, "Field", (PyObject *)&Field_Type) < 0)
return NULL;
Py_INCREF(&Meta_Type);
if (PyModule_AddObject(m, "Meta", (PyObject *)&Meta_Type) < 0)
return NULL;
Py_INCREF(&StructConfig_Type);
if (PyModule_AddObject(m, "StructConfig", (PyObject *)&StructConfig_Type) < 0)
return NULL;
Py_INCREF(&Ext_Type);
if (PyModule_AddObject(m, "Ext", (PyObject *)&Ext_Type) < 0)
return NULL;
Py_INCREF(&Raw_Type);
if (PyModule_AddObject(m, "Raw", (PyObject *)&Raw_Type) < 0)
return NULL;
Py_INCREF(&Encoder_Type);
if (PyModule_AddObject(m, "MsgpackEncoder", (PyObject *)&Encoder_Type) < 0)
return NULL;
Py_INCREF(&Decoder_Type);
if (PyModule_AddObject(m, "MsgpackDecoder", (PyObject *)&Decoder_Type) < 0)
return NULL;
Py_INCREF(&JSONEncoder_Type);
if (PyModule_AddObject(m, "JSONEncoder", (PyObject *)&JSONEncoder_Type) < 0)
return NULL;
Py_INCREF(&JSONDecoder_Type);
if (PyModule_AddObject(m, "JSONDecoder", (PyObject *)&JSONDecoder_Type) < 0)
return NULL;
Py_INCREF(&Unset_Type);
if (PyModule_AddObject(m, "UnsetType", (PyObject *)&Unset_Type) < 0)
return NULL;
st = msgspec_get_state(m);
/* Initialize GC counter */
st->gc_cycle = 0;
/* Add NODEFAULT singleton */
Py_INCREF(NODEFAULT);
if (PyModule_AddObject(m, "NODEFAULT", NODEFAULT) < 0)
return NULL;
/* Add UNSET singleton */
Py_INCREF(UNSET);
if (PyModule_AddObject(m, "UNSET", UNSET) < 0)
return NULL;
/* Initialize the exceptions. */
st->MsgspecError = PyErr_NewExceptionWithDoc(
"msgspec.MsgspecError",
"Base class for all Msgspec exceptions",
NULL, NULL
);
if (st->MsgspecError == NULL)
return NULL;
st->EncodeError = PyErr_NewExceptionWithDoc(
"msgspec.EncodeError",
"An error occurred while encoding an object",
st->MsgspecError, NULL
);
if (st->EncodeError == NULL)
return NULL;
st->DecodeError = PyErr_NewExceptionWithDoc(
"msgspec.DecodeError",
"An error occurred while decoding an object",
st->MsgspecError, NULL
);
if (st->DecodeError == NULL)
return NULL;
st->ValidationError = PyErr_NewExceptionWithDoc(
"msgspec.ValidationError",
"The message didn't match the expected schema",
st->DecodeError, NULL
);
if (st->ValidationError == NULL)
return NULL;
Py_INCREF(st->MsgspecError);
if (PyModule_AddObject(m, "MsgspecError", st->MsgspecError) < 0)
return NULL;
Py_INCREF(st->EncodeError);
if (PyModule_AddObject(m, "EncodeError", st->EncodeError) < 0)
return NULL;
Py_INCREF(st->DecodeError);
if (PyModule_AddObject(m, "DecodeError", st->DecodeError) < 0)
return NULL;
Py_INCREF(st->ValidationError);
if (PyModule_AddObject(m, "ValidationError", st->ValidationError) < 0)
return NULL;
/* Initialize the struct_lookup_cache */
st->struct_lookup_cache = PyDict_New();
if (st->struct_lookup_cache == NULL) return NULL;
Py_INCREF(st->struct_lookup_cache);
if (PyModule_AddObject(m, "_struct_lookup_cache", st->struct_lookup_cache) < 0)
return NULL;
#define SET_REF(attr, name) \
do { \
st->attr = PyObject_GetAttrString(temp_module, name); \
if (st->attr == NULL) return NULL; \
} while (0)
/* Get all imports from the typing module */
temp_module = PyImport_ImportModule("typing");
if (temp_module == NULL) return NULL;
SET_REF(typing_union, "Union");
SET_REF(typing_any, "Any");
SET_REF(typing_literal, "Literal");
SET_REF(typing_classvar, "ClassVar");
SET_REF(typing_typevar, "TypeVar");
SET_REF(typing_final, "Final");
SET_REF(typing_generic, "Generic");
SET_REF(typing_generic_alias, "_GenericAlias");
#if PY312_PLUS
SET_REF(typing_typealiastype, "TypeAliasType");
#endif
Py_DECREF(temp_module);
temp_module = PyImport_ImportModule("msgspec._utils");
if (temp_module == NULL) return NULL;
SET_REF(concrete_types, "_CONCRETE_TYPES");
SET_REF(get_type_hints, "get_type_hints");
SET_REF(get_class_annotations, "get_class_annotations");
SET_REF(get_typeddict_info, "get_typeddict_info");
SET_REF(get_dataclass_info, "get_dataclass_info");
SET_REF(typing_annotated_alias, "_AnnotatedAlias");
SET_REF(rebuild, "rebuild");
Py_DECREF(temp_module);
#if PY310_PLUS
temp_module = PyImport_ImportModule("types");
if (temp_module == NULL) return NULL;
SET_REF(types_uniontype, "UnionType");
Py_DECREF(temp_module);
#endif
/* Get the EnumMeta type */
temp_module = PyImport_ImportModule("enum");
if (temp_module == NULL)
return NULL;
temp_obj = PyObject_GetAttrString(temp_module, "EnumMeta");
Py_DECREF(temp_module);
if (temp_obj == NULL)
return NULL;
if (!PyType_Check(temp_obj)) {
Py_DECREF(temp_obj);
PyErr_SetString(PyExc_TypeError, "enum.EnumMeta should be a type");
return NULL;
}
st->EnumMetaType = (PyTypeObject *)temp_obj;
/* Get the datetime.datetime.astimezone method */
temp_module = PyImport_ImportModule("datetime");
if (temp_module == NULL) return NULL;
temp_obj = PyObject_GetAttrString(temp_module, "datetime");
Py_DECREF(temp_module);
if (temp_obj == NULL) return NULL;
st->astimezone = PyObject_GetAttrString(temp_obj, "astimezone");
Py_DECREF(temp_obj);
if (st->astimezone == NULL) return NULL;
/* uuid module imports */
temp_module = PyImport_ImportModule("uuid");
if (temp_module == NULL) return NULL;
st->UUIDType = PyObject_GetAttrString(temp_module, "UUID");
if (st->UUIDType == NULL) return NULL;
temp_obj = PyObject_GetAttrString(temp_module, "SafeUUID");
if (temp_obj == NULL) return NULL;
st->uuid_safeuuid_unknown = PyObject_GetAttrString(temp_obj, "unknown");
Py_DECREF(temp_obj);
if (st->uuid_safeuuid_unknown == NULL) return NULL;
/* decimal module imports */
temp_module = PyImport_ImportModule("decimal");
if (temp_module == NULL) return NULL;
st->DecimalType = PyObject_GetAttrString(temp_module, "Decimal");
if (st->DecimalType == NULL) return NULL;
/* Get the re.compile function */
temp_module = PyImport_ImportModule("re");
if (temp_module == NULL) return NULL;
st->re_compile = PyObject_GetAttrString(temp_module, "compile");
Py_DECREF(temp_module);
if (st->re_compile == NULL) return NULL;
/* Initialize cached constant strings */
#define CACHED_STRING(attr, str) \
if ((st->attr = PyUnicode_InternFromString(str)) == NULL) return NULL
CACHED_STRING(str___weakref__, "__weakref__");
CACHED_STRING(str___dict__, "__dict__");
CACHED_STRING(str___msgspec_cached_hash__, "__msgspec_cached_hash__");
CACHED_STRING(str__value2member_map_, "_value2member_map_");
CACHED_STRING(str___msgspec_cache__, "__msgspec_cache__");
CACHED_STRING(str__value_, "_value_");
CACHED_STRING(str__missing_, "_missing_");
CACHED_STRING(str_type, "type");
CACHED_STRING(str_enc_hook, "enc_hook");
CACHED_STRING(str_dec_hook, "dec_hook");
CACHED_STRING(str_ext_hook, "ext_hook");
CACHED_STRING(str_strict, "strict");
CACHED_STRING(str_order, "order");
CACHED_STRING(str_utcoffset, "utcoffset");
CACHED_STRING(str___origin__, "__origin__");
CACHED_STRING(str___args__, "__args__");
CACHED_STRING(str___metadata__, "__metadata__");
CACHED_STRING(str___total__, "__total__");
CACHED_STRING(str___required_keys__, "__required_keys__");
CACHED_STRING(str__fields, "_fields");
CACHED_STRING(str__field_defaults, "_field_defaults");
CACHED_STRING(str___post_init__, "__post_init__");
CACHED_STRING(str___dataclass_fields__, "__dataclass_fields__");
CACHED_STRING(str___attrs_attrs__, "__attrs_attrs__");
CACHED_STRING(str___supertype__, "__supertype__");
#if PY312_PLUS
CACHED_STRING(str___value__, "__value__");
#endif
CACHED_STRING(str___bound__, "__bound__");
CACHED_STRING(str___constraints__, "__constraints__");
CACHED_STRING(str_int, "int");
CACHED_STRING(str_is_safe, "is_safe");
/* Initialize the Struct Type */
PyState_AddModule(m, &msgspecmodule);
st->StructType = PyObject_CallFunction(
(PyObject *)&StructMetaType, "s(O){ssss}", "Struct", &StructMixinType,
"__module__", "msgspec", "__doc__", Struct__doc__
);
if (st->StructType == NULL) return NULL;
Py_INCREF(st->StructType);
if (PyModule_AddObject(m, "Struct", st->StructType) < 0) return NULL;
return m;
}
|