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
|
// Copyright (c) Faye Amacker. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
package cbor
import (
"encoding"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"math"
"math/big"
"reflect"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/x448/float16"
)
// Unmarshal parses the CBOR-encoded data into the value pointed to by v
// using default decoding options. If v is nil, not a pointer, or
// a nil pointer, Unmarshal returns an error.
//
// To unmarshal CBOR into a value implementing the Unmarshaler interface,
// Unmarshal calls that value's UnmarshalCBOR method with a valid
// CBOR value.
//
// To unmarshal CBOR byte string into a value implementing the
// encoding.BinaryUnmarshaler interface, Unmarshal calls that value's
// UnmarshalBinary method with decoded CBOR byte string.
//
// To unmarshal CBOR into a pointer, Unmarshal sets the pointer to nil
// if CBOR data is null (0xf6) or undefined (0xf7). Otherwise, Unmarshal
// unmarshals CBOR into the value pointed to by the pointer. If the
// pointer is nil, Unmarshal creates a new value for it to point to.
//
// To unmarshal CBOR into an empty interface value, Unmarshal uses the
// following rules:
//
// CBOR booleans decode to bool.
// CBOR positive integers decode to uint64.
// CBOR negative integers decode to int64 (big.Int if value overflows).
// CBOR floating points decode to float64.
// CBOR byte strings decode to []byte.
// CBOR text strings decode to string.
// CBOR arrays decode to []interface{}.
// CBOR maps decode to map[interface{}]interface{}.
// CBOR null and undefined values decode to nil.
// CBOR times (tag 0 and 1) decode to time.Time.
// CBOR bignums (tag 2 and 3) decode to big.Int.
// CBOR tags with an unrecognized number decode to cbor.Tag
//
// To unmarshal a CBOR array into a slice, Unmarshal allocates a new slice
// if the CBOR array is empty or slice capacity is less than CBOR array length.
// Otherwise Unmarshal overwrites existing elements, and sets slice length
// to CBOR array length.
//
// To unmarshal a CBOR array into a Go array, Unmarshal decodes CBOR array
// elements into Go array elements. If the Go array is smaller than the
// CBOR array, the extra CBOR array elements are discarded. If the CBOR
// array is smaller than the Go array, the extra Go array elements are
// set to zero values.
//
// To unmarshal a CBOR array into a struct, struct must have a special field "_"
// with struct tag `cbor:",toarray"`. Go array elements are decoded into struct
// fields. Any "omitempty" struct field tag option is ignored in this case.
//
// To unmarshal a CBOR map into a map, Unmarshal allocates a new map only if the
// map is nil. Otherwise Unmarshal reuses the existing map and keeps existing
// entries. Unmarshal stores key-value pairs from the CBOR map into Go map.
// See DecOptions.DupMapKey to enable duplicate map key detection.
//
// To unmarshal a CBOR map into a struct, Unmarshal matches CBOR map keys to the
// keys in the following priority:
//
// 1. "cbor" key in struct field tag,
// 2. "json" key in struct field tag,
// 3. struct field name.
//
// Unmarshal tries an exact match for field name, then a case-insensitive match.
// Map key-value pairs without corresponding struct fields are ignored. See
// DecOptions.ExtraReturnErrors to return error at unknown field.
//
// To unmarshal a CBOR text string into a time.Time value, Unmarshal parses text
// string formatted in RFC3339. To unmarshal a CBOR integer/float into a
// time.Time value, Unmarshal creates an unix time with integer/float as seconds
// and fractional seconds since January 1, 1970 UTC. As a special case, Infinite
// and NaN float values decode to time.Time's zero value.
//
// To unmarshal CBOR null (0xf6) and undefined (0xf7) values into a
// slice/map/pointer, Unmarshal sets Go value to nil. Because null is often
// used to mean "not present", unmarshalling CBOR null and undefined value
// into any other Go type has no effect and returns no error.
//
// Unmarshal supports CBOR tag 55799 (self-describe CBOR), tag 0 and 1 (time),
// and tag 2 and 3 (bignum).
//
// Unmarshal returns ExtraneousDataError error (without decoding into v)
// if there are any remaining bytes following the first valid CBOR data item.
// See UnmarshalFirst, if you want to unmarshal only the first
// CBOR data item without ExtraneousDataError caused by remaining bytes.
func Unmarshal(data []byte, v any) error {
return defaultDecMode.Unmarshal(data, v)
}
// UnmarshalFirst parses the first CBOR data item into the value pointed to by v
// using default decoding options. Any remaining bytes are returned in rest.
//
// If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error.
//
// See the documentation for Unmarshal for details.
func UnmarshalFirst(data []byte, v any) (rest []byte, err error) {
return defaultDecMode.UnmarshalFirst(data, v)
}
// Valid checks whether data is a well-formed encoded CBOR data item and
// that it complies with default restrictions such as MaxNestedLevels,
// MaxArrayElements, MaxMapPairs, etc.
//
// If there are any remaining bytes after the CBOR data item,
// an ExtraneousDataError is returned.
//
// WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity)
// and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed".
//
// Deprecated: Valid is kept for compatibility and should not be used.
// Use Wellformed instead because it has a more appropriate name.
func Valid(data []byte) error {
return defaultDecMode.Valid(data)
}
// Wellformed checks whether data is a well-formed encoded CBOR data item and
// that it complies with default restrictions such as MaxNestedLevels,
// MaxArrayElements, MaxMapPairs, etc.
//
// If there are any remaining bytes after the CBOR data item,
// an ExtraneousDataError is returned.
func Wellformed(data []byte) error {
return defaultDecMode.Wellformed(data)
}
// Unmarshaler is the interface implemented by types that wish to unmarshal
// CBOR data themselves. The input is a valid CBOR value. UnmarshalCBOR
// must copy the CBOR data if it needs to use it after returning.
type Unmarshaler interface {
UnmarshalCBOR([]byte) error
}
type unmarshaler interface {
unmarshalCBOR([]byte) error
}
// InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
type InvalidUnmarshalError struct {
s string
}
func (e *InvalidUnmarshalError) Error() string {
return e.s
}
// UnmarshalTypeError describes a CBOR value that can't be decoded to a Go type.
type UnmarshalTypeError struct {
CBORType string // type of CBOR value
GoType string // type of Go value it could not be decoded into
StructFieldName string // name of the struct field holding the Go value (optional)
errorMsg string // additional error message (optional)
}
func (e *UnmarshalTypeError) Error() string {
var s string
if e.StructFieldName != "" {
s = "cbor: cannot unmarshal " + e.CBORType + " into Go struct field " + e.StructFieldName + " of type " + e.GoType
} else {
s = "cbor: cannot unmarshal " + e.CBORType + " into Go value of type " + e.GoType
}
if e.errorMsg != "" {
s += " (" + e.errorMsg + ")"
}
return s
}
// InvalidMapKeyTypeError describes invalid Go map key type when decoding CBOR map.
// For example, Go doesn't allow slice as map key.
type InvalidMapKeyTypeError struct {
GoType string
}
func (e *InvalidMapKeyTypeError) Error() string {
return "cbor: invalid map key type: " + e.GoType
}
// DupMapKeyError describes detected duplicate map key in CBOR map.
type DupMapKeyError struct {
Key any
Index int
}
func (e *DupMapKeyError) Error() string {
return fmt.Sprintf("cbor: found duplicate map key \"%v\" at map element index %d", e.Key, e.Index)
}
// UnknownFieldError describes detected unknown field in CBOR map when decoding to Go struct.
type UnknownFieldError struct {
Index int
}
func (e *UnknownFieldError) Error() string {
return fmt.Sprintf("cbor: found unknown field at map element index %d", e.Index)
}
// UnacceptableDataItemError is returned when unmarshaling a CBOR input that contains a data item
// that is not acceptable to a specific CBOR-based application protocol ("invalid or unexpected" as
// described in RFC 8949 Section 5 Paragraph 3).
type UnacceptableDataItemError struct {
CBORType string
Message string
}
func (e UnacceptableDataItemError) Error() string {
return fmt.Sprintf("cbor: data item of cbor type %s is not accepted by protocol: %s", e.CBORType, e.Message)
}
// ByteStringExpectedFormatError is returned when unmarshaling CBOR byte string fails when
// using non-default ByteStringExpectedFormat decoding option that makes decoder expect
// a specified format such as base64, hex, etc.
type ByteStringExpectedFormatError struct {
expectedFormatOption ByteStringExpectedFormatMode
err error
}
func newByteStringExpectedFormatError(expectedFormatOption ByteStringExpectedFormatMode, err error) *ByteStringExpectedFormatError {
return &ByteStringExpectedFormatError{expectedFormatOption, err}
}
func (e *ByteStringExpectedFormatError) Error() string {
switch e.expectedFormatOption {
case ByteStringExpectedBase64URL:
return fmt.Sprintf("cbor: failed to decode base64url from byte string: %s", e.err)
case ByteStringExpectedBase64:
return fmt.Sprintf("cbor: failed to decode base64 from byte string: %s", e.err)
case ByteStringExpectedBase16:
return fmt.Sprintf("cbor: failed to decode hex from byte string: %s", e.err)
default:
return fmt.Sprintf("cbor: failed to decode byte string in expected format %d: %s", e.expectedFormatOption, e.err)
}
}
func (e *ByteStringExpectedFormatError) Unwrap() error {
return e.err
}
// InadmissibleTagContentTypeError is returned when unmarshaling built-in CBOR tags
// fails because of inadmissible type for tag content. Currently, the built-in
// CBOR tags in this codec are tags 0-3 and 21-23.
// See "Tag validity" in RFC 8949 Section 5.3.2.
type InadmissibleTagContentTypeError struct {
s string
tagNum int
expectedTagContentType string
gotTagContentType string
}
func newInadmissibleTagContentTypeError(
tagNum int,
expectedTagContentType string,
gotTagContentType string,
) *InadmissibleTagContentTypeError {
return &InadmissibleTagContentTypeError{
tagNum: tagNum,
expectedTagContentType: expectedTagContentType,
gotTagContentType: gotTagContentType,
}
}
func newInadmissibleTagContentTypeErrorf(s string) *InadmissibleTagContentTypeError {
return &InadmissibleTagContentTypeError{s: "cbor: " + s} //nolint:goconst // ignore "cbor"
}
func (e *InadmissibleTagContentTypeError) Error() string {
if e.s == "" {
return fmt.Sprintf(
"cbor: tag number %d must be followed by %s, got %s",
e.tagNum,
e.expectedTagContentType,
e.gotTagContentType,
)
}
return e.s
}
// DupMapKeyMode specifies how to enforce duplicate map key. Two map keys are considered duplicates if:
// 1. When decoding into a struct, both keys match the same struct field. The keys are also
// considered duplicates if neither matches any field and decoding to interface{} would produce
// equal (==) values for both keys.
// 2. When decoding into a map, both keys are equal (==) when decoded into values of the
// destination map's key type.
type DupMapKeyMode int
const (
// DupMapKeyQuiet doesn't enforce duplicate map key. Decoder quietly (no error)
// uses faster of "keep first" or "keep last" depending on Go data type and other factors.
DupMapKeyQuiet DupMapKeyMode = iota
// DupMapKeyEnforcedAPF enforces detection and rejection of duplicate map keys.
// APF means "Allow Partial Fill" and the destination map or struct can be partially filled.
// If a duplicate map key is detected, DupMapKeyError is returned without further decoding
// of the map. It's the caller's responsibility to respond to DupMapKeyError by
// discarding the partially filled result if their protocol requires it.
// WARNING: using DupMapKeyEnforcedAPF will decrease performance and increase memory use.
DupMapKeyEnforcedAPF
maxDupMapKeyMode
)
func (dmkm DupMapKeyMode) valid() bool {
return dmkm >= 0 && dmkm < maxDupMapKeyMode
}
// IndefLengthMode specifies whether to allow indefinite length items.
type IndefLengthMode int
const (
// IndefLengthAllowed allows indefinite length items.
IndefLengthAllowed IndefLengthMode = iota
// IndefLengthForbidden disallows indefinite length items.
IndefLengthForbidden
maxIndefLengthMode
)
func (m IndefLengthMode) valid() bool {
return m >= 0 && m < maxIndefLengthMode
}
// TagsMode specifies whether to allow CBOR tags.
type TagsMode int
const (
// TagsAllowed allows CBOR tags.
TagsAllowed TagsMode = iota
// TagsForbidden disallows CBOR tags.
TagsForbidden
maxTagsMode
)
func (tm TagsMode) valid() bool {
return tm >= 0 && tm < maxTagsMode
}
// IntDecMode specifies which Go type (int64, uint64, or big.Int) should
// be used when decoding CBOR integers (major type 0 and 1) to Go interface{}.
type IntDecMode int
const (
// IntDecConvertNone affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
// It decodes CBOR unsigned integer (major type 0) to:
// - uint64
// It decodes CBOR negative integer (major type 1) to:
// - int64 if value fits
// - big.Int or *big.Int (see BigIntDecMode) if value doesn't fit into int64
IntDecConvertNone IntDecMode = iota
// IntDecConvertSigned affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
// It decodes CBOR integers (major type 0 and 1) to:
// - int64 if value fits
// - big.Int or *big.Int (see BigIntDecMode) if value < math.MinInt64
// - return UnmarshalTypeError if value > math.MaxInt64
// Deprecated: IntDecConvertSigned should not be used.
// Please use other options, such as IntDecConvertSignedOrError, IntDecConvertSignedOrBigInt, IntDecConvertNone.
IntDecConvertSigned
// IntDecConvertSignedOrFail affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
// It decodes CBOR integers (major type 0 and 1) to:
// - int64 if value fits
// - return UnmarshalTypeError if value doesn't fit into int64
IntDecConvertSignedOrFail
// IntDecConvertSigned affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
// It makes CBOR integers (major type 0 and 1) decode to:
// - int64 if value fits
// - big.Int or *big.Int (see BigIntDecMode) if value doesn't fit into int64
IntDecConvertSignedOrBigInt
maxIntDec
)
func (idm IntDecMode) valid() bool {
return idm >= 0 && idm < maxIntDec
}
// MapKeyByteStringMode specifies how to decode CBOR byte string (major type 2)
// as Go map key when decoding CBOR map key into an empty Go interface value.
// Specifically, this option applies when decoding CBOR map into
// - Go empty interface, or
// - Go map with empty interface as key type.
// The CBOR map key types handled by this option are
// - byte string
// - tagged byte string
// - nested tagged byte string
type MapKeyByteStringMode int
const (
// MapKeyByteStringAllowed allows CBOR byte string to be decoded as Go map key.
// Since Go doesn't allow []byte as map key, CBOR byte string is decoded to
// ByteString which has underlying string type.
// This is the default setting.
MapKeyByteStringAllowed MapKeyByteStringMode = iota
// MapKeyByteStringForbidden forbids CBOR byte string being decoded as Go map key.
// Attempting to decode CBOR byte string as map key into empty interface value
// returns a decoding error.
MapKeyByteStringForbidden
maxMapKeyByteStringMode
)
func (mkbsm MapKeyByteStringMode) valid() bool {
return mkbsm >= 0 && mkbsm < maxMapKeyByteStringMode
}
// ExtraDecErrorCond specifies extra conditions that should be treated as errors.
type ExtraDecErrorCond uint
// ExtraDecErrorNone indicates no extra error condition.
const ExtraDecErrorNone ExtraDecErrorCond = 0
const (
// ExtraDecErrorUnknownField indicates error condition when destination
// Go struct doesn't have a field matching a CBOR map key.
ExtraDecErrorUnknownField ExtraDecErrorCond = 1 << iota
maxExtraDecError
)
func (ec ExtraDecErrorCond) valid() bool {
return ec < maxExtraDecError
}
// UTF8Mode option specifies if decoder should
// decode CBOR Text containing invalid UTF-8 string.
type UTF8Mode int
const (
// UTF8RejectInvalid rejects CBOR Text containing
// invalid UTF-8 string.
UTF8RejectInvalid UTF8Mode = iota
// UTF8DecodeInvalid allows decoding CBOR Text containing
// invalid UTF-8 string.
UTF8DecodeInvalid
maxUTF8Mode
)
func (um UTF8Mode) valid() bool {
return um >= 0 && um < maxUTF8Mode
}
// FieldNameMatchingMode specifies how string keys in CBOR maps are matched to Go struct field names.
type FieldNameMatchingMode int
const (
// FieldNameMatchingPreferCaseSensitive prefers to decode map items into struct fields whose names (or tag
// names) exactly match the item's key. If there is no such field, a map item will be decoded into a field whose
// name is a case-insensitive match for the item's key.
FieldNameMatchingPreferCaseSensitive FieldNameMatchingMode = iota
// FieldNameMatchingCaseSensitive decodes map items only into a struct field whose name (or tag name) is an
// exact match for the item's key.
FieldNameMatchingCaseSensitive
maxFieldNameMatchingMode
)
func (fnmm FieldNameMatchingMode) valid() bool {
return fnmm >= 0 && fnmm < maxFieldNameMatchingMode
}
// BigIntDecMode specifies how to decode CBOR bignum to Go interface{}.
type BigIntDecMode int
const (
// BigIntDecodeValue makes CBOR bignum decode to big.Int (instead of *big.Int)
// when unmarshalling into a Go interface{}.
BigIntDecodeValue BigIntDecMode = iota
// BigIntDecodePointer makes CBOR bignum decode to *big.Int when
// unmarshalling into a Go interface{}.
BigIntDecodePointer
maxBigIntDecMode
)
func (bidm BigIntDecMode) valid() bool {
return bidm >= 0 && bidm < maxBigIntDecMode
}
// ByteStringToStringMode specifies the behavior when decoding a CBOR byte string into a Go string.
type ByteStringToStringMode int
const (
// ByteStringToStringForbidden generates an error on an attempt to decode a CBOR byte string into a Go string.
ByteStringToStringForbidden ByteStringToStringMode = iota
// ByteStringToStringAllowed permits decoding a CBOR byte string into a Go string.
ByteStringToStringAllowed
// ByteStringToStringAllowedWithExpectedLaterEncoding permits decoding a CBOR byte string
// into a Go string. Also, if the byte string is enclosed (directly or indirectly) by one of
// the "expected later encoding" tags (numbers 21 through 23), the destination string will
// be populated by applying the designated text encoding to the contents of the input byte
// string.
ByteStringToStringAllowedWithExpectedLaterEncoding
maxByteStringToStringMode
)
func (bstsm ByteStringToStringMode) valid() bool {
return bstsm >= 0 && bstsm < maxByteStringToStringMode
}
// FieldNameByteStringMode specifies the behavior when decoding a CBOR byte string map key as a Go struct field name.
type FieldNameByteStringMode int
const (
// FieldNameByteStringForbidden generates an error on an attempt to decode a CBOR byte string map key as a Go struct field name.
FieldNameByteStringForbidden FieldNameByteStringMode = iota
// FieldNameByteStringAllowed permits CBOR byte string map keys to be recognized as Go struct field names.
FieldNameByteStringAllowed
maxFieldNameByteStringMode
)
func (fnbsm FieldNameByteStringMode) valid() bool {
return fnbsm >= 0 && fnbsm < maxFieldNameByteStringMode
}
// UnrecognizedTagToAnyMode specifies how to decode unrecognized CBOR tag into an empty interface (any).
// Currently, recognized CBOR tag numbers are 0, 1, 2, 3, or registered by TagSet.
type UnrecognizedTagToAnyMode int
const (
// UnrecognizedTagNumAndContentToAny decodes CBOR tag number and tag content to cbor.Tag
// when decoding unrecognized CBOR tag into an empty interface.
UnrecognizedTagNumAndContentToAny UnrecognizedTagToAnyMode = iota
// UnrecognizedTagContentToAny decodes only CBOR tag content (into its default type)
// when decoding unrecognized CBOR tag into an empty interface.
UnrecognizedTagContentToAny
maxUnrecognizedTagToAny
)
func (uttam UnrecognizedTagToAnyMode) valid() bool {
return uttam >= 0 && uttam < maxUnrecognizedTagToAny
}
// TimeTagToAnyMode specifies how to decode CBOR tag 0 and 1 into an empty interface (any).
// Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.
type TimeTagToAnyMode int
const (
// TimeTagToTime decodes CBOR tag 0 and 1 into a time.Time value
// when decoding tag 0 or 1 into an empty interface.
TimeTagToTime TimeTagToAnyMode = iota
// TimeTagToRFC3339 decodes CBOR tag 0 and 1 into a time string in RFC3339 format
// when decoding tag 0 or 1 into an empty interface.
TimeTagToRFC3339
// TimeTagToRFC3339Nano decodes CBOR tag 0 and 1 into a time string in RFC3339Nano format
// when decoding tag 0 or 1 into an empty interface.
TimeTagToRFC3339Nano
maxTimeTagToAnyMode
)
func (tttam TimeTagToAnyMode) valid() bool {
return tttam >= 0 && tttam < maxTimeTagToAnyMode
}
// SimpleValueRegistry is a registry of unmarshaling behaviors for each possible CBOR simple value
// number (0...23 and 32...255).
type SimpleValueRegistry struct {
rejected [256]bool
}
// WithRejectedSimpleValue registers the given simple value as rejected. If the simple value is
// encountered in a CBOR input during unmarshaling, an UnacceptableDataItemError is returned.
func WithRejectedSimpleValue(sv SimpleValue) func(*SimpleValueRegistry) error {
return func(r *SimpleValueRegistry) error {
if sv >= 24 && sv <= 31 {
return fmt.Errorf("cbor: cannot set analog for reserved simple value %d", sv)
}
r.rejected[sv] = true
return nil
}
}
// Creates a new SimpleValueRegistry. The registry state is initialized by executing the provided
// functions in order against a registry that is pre-populated with the defaults for all well-formed
// simple value numbers.
func NewSimpleValueRegistryFromDefaults(fns ...func(*SimpleValueRegistry) error) (*SimpleValueRegistry, error) {
var r SimpleValueRegistry
for _, fn := range fns {
if err := fn(&r); err != nil {
return nil, err
}
}
return &r, nil
}
// NaNMode specifies how to decode floating-point values (major type 7, additional information 25
// through 27) representing NaN (not-a-number).
type NaNMode int
const (
// NaNDecodeAllowed will decode NaN values to Go float32 or float64.
NaNDecodeAllowed NaNMode = iota
// NaNDecodeForbidden will return an UnacceptableDataItemError on an attempt to decode a NaN value.
NaNDecodeForbidden
maxNaNDecode
)
func (ndm NaNMode) valid() bool {
return ndm >= 0 && ndm < maxNaNDecode
}
// InfMode specifies how to decode floating-point values (major type 7, additional information 25
// through 27) representing positive or negative infinity.
type InfMode int
const (
// InfDecodeAllowed will decode infinite values to Go float32 or float64.
InfDecodeAllowed InfMode = iota
// InfDecodeForbidden will return an UnacceptableDataItemError on an attempt to decode an
// infinite value.
InfDecodeForbidden
maxInfDecode
)
func (idm InfMode) valid() bool {
return idm >= 0 && idm < maxInfDecode
}
// ByteStringToTimeMode specifies the behavior when decoding a CBOR byte string into a Go time.Time.
type ByteStringToTimeMode int
const (
// ByteStringToTimeForbidden generates an error on an attempt to decode a CBOR byte string into a Go time.Time.
ByteStringToTimeForbidden ByteStringToTimeMode = iota
// ByteStringToTimeAllowed permits decoding a CBOR byte string into a Go time.Time.
ByteStringToTimeAllowed
maxByteStringToTimeMode
)
func (bttm ByteStringToTimeMode) valid() bool {
return bttm >= 0 && bttm < maxByteStringToTimeMode
}
// ByteStringExpectedFormatMode specifies how to decode CBOR byte string into Go byte slice
// when the byte string is NOT enclosed in CBOR tag 21, 22, or 23. An error is returned if
// the CBOR byte string does not contain the expected format (e.g. base64) specified.
// For tags 21-23, see "Expected Later Encoding for CBOR-to-JSON Converters"
// in RFC 8949 Section 3.4.5.2.
type ByteStringExpectedFormatMode int
const (
// ByteStringExpectedFormatNone copies the unmodified CBOR byte string into Go byte slice
// if the byte string is not tagged by CBOR tag 21-23.
ByteStringExpectedFormatNone ByteStringExpectedFormatMode = iota
// ByteStringExpectedBase64URL expects CBOR byte strings to contain base64url-encoded bytes
// if the byte string is not tagged by CBOR tag 21-23. The decoder will attempt to decode
// the base64url-encoded bytes into Go slice.
ByteStringExpectedBase64URL
// ByteStringExpectedBase64 expects CBOR byte strings to contain base64-encoded bytes
// if the byte string is not tagged by CBOR tag 21-23. The decoder will attempt to decode
// the base64-encoded bytes into Go slice.
ByteStringExpectedBase64
// ByteStringExpectedBase16 expects CBOR byte strings to contain base16-encoded bytes
// if the byte string is not tagged by CBOR tag 21-23. The decoder will attempt to decode
// the base16-encoded bytes into Go slice.
ByteStringExpectedBase16
maxByteStringExpectedFormatMode
)
func (bsefm ByteStringExpectedFormatMode) valid() bool {
return bsefm >= 0 && bsefm < maxByteStringExpectedFormatMode
}
// BignumTagMode specifies whether or not the "bignum" tags 2 and 3 (RFC 8949 Section 3.4.3) can be
// decoded.
type BignumTagMode int
const (
// BignumTagAllowed allows bignum tags to be decoded.
BignumTagAllowed BignumTagMode = iota
// BignumTagForbidden produces an UnacceptableDataItemError during Unmarshal if a bignum tag
// is encountered in the input.
BignumTagForbidden
maxBignumTag
)
func (btm BignumTagMode) valid() bool {
return btm >= 0 && btm < maxBignumTag
}
// BinaryUnmarshalerMode specifies how to decode into types that implement
// encoding.BinaryUnmarshaler.
type BinaryUnmarshalerMode int
const (
// BinaryUnmarshalerByteString will invoke UnmarshalBinary on the contents of a CBOR byte
// string when decoding into a value that implements BinaryUnmarshaler.
BinaryUnmarshalerByteString BinaryUnmarshalerMode = iota
// BinaryUnmarshalerNone does not recognize BinaryUnmarshaler implementations during decode.
BinaryUnmarshalerNone
maxBinaryUnmarshalerMode
)
func (bum BinaryUnmarshalerMode) valid() bool {
return bum >= 0 && bum < maxBinaryUnmarshalerMode
}
// DecOptions specifies decoding options.
type DecOptions struct {
// DupMapKey specifies whether to enforce duplicate map key.
DupMapKey DupMapKeyMode
// TimeTag specifies whether or not untagged data items, or tags other
// than tag 0 and tag 1, can be decoded to time.Time. If tag 0 or tag 1
// appears in an input, the type of its content is always validated as
// specified in RFC 8949. That behavior is not controlled by this
// option. The behavior of the supported modes are:
//
// DecTagIgnored (default): Untagged text strings and text strings
// enclosed in tags other than 0 and 1 are decoded as though enclosed
// in tag 0. Untagged unsigned integers, negative integers, and
// floating-point numbers (or those enclosed in tags other than 0 and
// 1) are decoded as though enclosed in tag 1. Decoding a tag other
// than 0 or 1 enclosing simple values null or undefined into a
// time.Time does not modify the destination value.
//
// DecTagOptional: Untagged text strings are decoded as though
// enclosed in tag 0. Untagged unsigned integers, negative integers,
// and floating-point numbers are decoded as though enclosed in tag
// 1. Tags other than 0 and 1 will produce an error on attempts to
// decode them into a time.Time.
//
// DecTagRequired: Only tags 0 and 1 can be decoded to time.Time. Any
// other input will produce an error.
TimeTag DecTagMode
// MaxNestedLevels specifies the max nested levels allowed for any combination of CBOR array, maps, and tags.
// Default is 32 levels and it can be set to [4, 65535]. Note that higher maximum levels of nesting can
// require larger amounts of stack to deserialize. Don't increase this higher than you require.
MaxNestedLevels int
// MaxArrayElements specifies the max number of elements for CBOR arrays.
// Default is 128*1024=131072 and it can be set to [16, 2147483647]
MaxArrayElements int64
// MaxMapPairs specifies the max number of key-value pairs for CBOR maps.
// Default is 128*1024=131072 and it can be set to [16, 2147483647]
MaxMapPairs int64
// IndefLength specifies whether to allow indefinite length CBOR items.
IndefLength IndefLengthMode
// TagsMd specifies whether to allow CBOR tags (major type 6).
TagsMd TagsMode
// IntDec specifies which Go integer type (int64 or uint64) to use
// when decoding CBOR int (major type 0 and 1) to Go interface{}.
IntDec IntDecMode
// MapKeyByteString specifies how to decode CBOR byte string as map key
// when decoding CBOR map with byte string key into an empty interface value.
// By default, an error is returned when attempting to decode CBOR byte string
// as map key because Go doesn't allow []byte as map key.
MapKeyByteString MapKeyByteStringMode
// ExtraReturnErrors specifies extra conditions that should be treated as errors.
ExtraReturnErrors ExtraDecErrorCond
// DefaultMapType specifies Go map type to create and decode to
// when unmarshalling CBOR into an empty interface value.
// By default, unmarshal uses map[interface{}]interface{}.
DefaultMapType reflect.Type
// UTF8 specifies if decoder should decode CBOR Text containing invalid UTF-8.
// By default, unmarshal rejects CBOR text containing invalid UTF-8.
UTF8 UTF8Mode
// FieldNameMatching specifies how string keys in CBOR maps are matched to Go struct field names.
FieldNameMatching FieldNameMatchingMode
// BigIntDec specifies how to decode CBOR bignum to Go interface{}.
BigIntDec BigIntDecMode
// DefaultByteStringType is the Go type that should be produced when decoding a CBOR byte
// string into an empty interface value. Types to which a []byte is convertible are valid
// for this option, except for array and pointer-to-array types. If nil, the default is
// []byte.
DefaultByteStringType reflect.Type
// ByteStringToString specifies the behavior when decoding a CBOR byte string into a Go string.
ByteStringToString ByteStringToStringMode
// FieldNameByteString specifies the behavior when decoding a CBOR byte string map key as a
// Go struct field name.
FieldNameByteString FieldNameByteStringMode
// UnrecognizedTagToAny specifies how to decode unrecognized CBOR tag into an empty interface.
// Currently, recognized CBOR tag numbers are 0, 1, 2, 3, or registered by TagSet.
UnrecognizedTagToAny UnrecognizedTagToAnyMode
// TimeTagToAny specifies how to decode CBOR tag 0 and 1 into an empty interface (any).
// Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.
TimeTagToAny TimeTagToAnyMode
// SimpleValues is an immutable mapping from each CBOR simple value to a corresponding
// unmarshal behavior. If nil, the simple values false, true, null, and undefined are mapped
// to the Go analog values false, true, nil, and nil, respectively, and all other simple
// values N (except the reserved simple values 24 through 31) are mapped to
// cbor.SimpleValue(N). In other words, all well-formed simple values can be decoded.
//
// Users may provide a custom SimpleValueRegistry constructed via
// NewSimpleValueRegistryFromDefaults.
SimpleValues *SimpleValueRegistry
// NaN specifies how to decode floating-point values (major type 7, additional information
// 25 through 27) representing NaN (not-a-number).
NaN NaNMode
// Inf specifies how to decode floating-point values (major type 7, additional information
// 25 through 27) representing positive or negative infinity.
Inf InfMode
// ByteStringToTime specifies how to decode CBOR byte string into Go time.Time.
ByteStringToTime ByteStringToTimeMode
// ByteStringExpectedFormat specifies how to decode CBOR byte string into Go byte slice
// when the byte string is NOT enclosed in CBOR tag 21, 22, or 23. An error is returned if
// the CBOR byte string does not contain the expected format (e.g. base64) specified.
// For tags 21-23, see "Expected Later Encoding for CBOR-to-JSON Converters"
// in RFC 8949 Section 3.4.5.2.
ByteStringExpectedFormat ByteStringExpectedFormatMode
// BignumTag specifies whether or not the "bignum" tags 2 and 3 (RFC 8949 Section 3.4.3) can
// be decoded. Unlike BigIntDec, this option applies to all bignum tags encountered in a
// CBOR input, independent of the type of the destination value of a particular Unmarshal
// operation.
BignumTag BignumTagMode
// BinaryUnmarshaler specifies how to decode into types that implement
// encoding.BinaryUnmarshaler.
BinaryUnmarshaler BinaryUnmarshalerMode
}
// DecMode returns DecMode with immutable options and no tags (safe for concurrency).
func (opts DecOptions) DecMode() (DecMode, error) { //nolint:gocritic // ignore hugeParam
return opts.decMode()
}
// validForTags checks that the provided tag set is compatible with these options and returns a
// non-nil error if and only if the provided tag set is incompatible.
func (opts DecOptions) validForTags(tags TagSet) error { //nolint:gocritic // ignore hugeParam
if opts.TagsMd == TagsForbidden {
return errors.New("cbor: cannot create DecMode with TagSet when TagsMd is TagsForbidden")
}
if tags == nil {
return errors.New("cbor: cannot create DecMode with nil value as TagSet")
}
if opts.ByteStringToString == ByteStringToStringAllowedWithExpectedLaterEncoding ||
opts.ByteStringExpectedFormat != ByteStringExpectedFormatNone {
for _, tagNum := range []uint64{
tagNumExpectedLaterEncodingBase64URL,
tagNumExpectedLaterEncodingBase64,
tagNumExpectedLaterEncodingBase16,
} {
if rt := tags.getTypeFromTagNum([]uint64{tagNum}); rt != nil {
return fmt.Errorf("cbor: DecMode with non-default StringExpectedEncoding or ByteSliceExpectedEncoding treats tag %d as built-in and conflicts with the provided TagSet's registration of %v", tagNum, rt)
}
}
}
return nil
}
// DecModeWithTags returns DecMode with options and tags that are both immutable (safe for concurrency).
func (opts DecOptions) DecModeWithTags(tags TagSet) (DecMode, error) { //nolint:gocritic // ignore hugeParam
if err := opts.validForTags(tags); err != nil {
return nil, err
}
dm, err := opts.decMode()
if err != nil {
return nil, err
}
// Copy tags
ts := tagSet(make(map[reflect.Type]*tagItem))
syncTags := tags.(*syncTagSet)
syncTags.RLock()
for contentType, tag := range syncTags.t {
if tag.opts.DecTag != DecTagIgnored {
ts[contentType] = tag
}
}
syncTags.RUnlock()
if len(ts) > 0 {
dm.tags = ts
}
return dm, nil
}
// DecModeWithSharedTags returns DecMode with immutable options and mutable shared tags (safe for concurrency).
func (opts DecOptions) DecModeWithSharedTags(tags TagSet) (DecMode, error) { //nolint:gocritic // ignore hugeParam
if err := opts.validForTags(tags); err != nil {
return nil, err
}
dm, err := opts.decMode()
if err != nil {
return nil, err
}
dm.tags = tags
return dm, nil
}
const (
defaultMaxArrayElements = 131072
minMaxArrayElements = 16
maxMaxArrayElements = 2147483647
defaultMaxMapPairs = 131072
minMaxMapPairs = 16
maxMaxMapPairs = 2147483647
defaultMaxNestedLevels = 32
minMaxNestedLevels = 4
maxMaxNestedLevels = 65535
)
var defaultSimpleValues = func() *SimpleValueRegistry {
registry, err := NewSimpleValueRegistryFromDefaults()
if err != nil {
panic(err)
}
return registry
}()
//nolint:gocyclo // Each option comes with some manageable boilerplate
func (opts DecOptions) decMode() (*decMode, error) { //nolint:gocritic // ignore hugeParam
if !opts.DupMapKey.valid() {
return nil, errors.New("cbor: invalid DupMapKey " + strconv.Itoa(int(opts.DupMapKey)))
}
if !opts.TimeTag.valid() {
return nil, errors.New("cbor: invalid TimeTag " + strconv.Itoa(int(opts.TimeTag)))
}
if !opts.IndefLength.valid() {
return nil, errors.New("cbor: invalid IndefLength " + strconv.Itoa(int(opts.IndefLength)))
}
if !opts.TagsMd.valid() {
return nil, errors.New("cbor: invalid TagsMd " + strconv.Itoa(int(opts.TagsMd)))
}
if !opts.IntDec.valid() {
return nil, errors.New("cbor: invalid IntDec " + strconv.Itoa(int(opts.IntDec)))
}
if !opts.MapKeyByteString.valid() {
return nil, errors.New("cbor: invalid MapKeyByteString " + strconv.Itoa(int(opts.MapKeyByteString)))
}
if opts.MaxNestedLevels == 0 {
opts.MaxNestedLevels = defaultMaxNestedLevels
} else if opts.MaxNestedLevels < minMaxNestedLevels || opts.MaxNestedLevels > maxMaxNestedLevels {
return nil, errors.New("cbor: invalid MaxNestedLevels " + strconv.Itoa(opts.MaxNestedLevels) +
" (range is [" + strconv.Itoa(minMaxNestedLevels) + ", " + strconv.Itoa(maxMaxNestedLevels) + "])")
}
if opts.MaxArrayElements == 0 {
opts.MaxArrayElements = defaultMaxArrayElements
} else if opts.MaxArrayElements < minMaxArrayElements || opts.MaxArrayElements > maxMaxArrayElements {
return nil, errors.New("cbor: invalid MaxArrayElements " + strconv.FormatInt(opts.MaxArrayElements, 10) +
" (range is [" + strconv.Itoa(minMaxArrayElements) + ", " + strconv.FormatInt(maxMaxArrayElements, 10) + "])")
}
if opts.MaxMapPairs == 0 {
opts.MaxMapPairs = defaultMaxMapPairs
} else if opts.MaxMapPairs < minMaxMapPairs || opts.MaxMapPairs > maxMaxMapPairs {
return nil, errors.New("cbor: invalid MaxMapPairs " + strconv.FormatInt(opts.MaxMapPairs, 10) +
" (range is [" + strconv.Itoa(minMaxMapPairs) + ", " + strconv.FormatInt(opts.MaxMapPairs, 10) + "])")
}
if !opts.ExtraReturnErrors.valid() {
return nil, errors.New("cbor: invalid ExtraReturnErrors " + strconv.Itoa(int(opts.ExtraReturnErrors)))
}
if opts.DefaultMapType != nil && opts.DefaultMapType.Kind() != reflect.Map {
return nil, fmt.Errorf("cbor: invalid DefaultMapType %s", opts.DefaultMapType)
}
if !opts.UTF8.valid() {
return nil, errors.New("cbor: invalid UTF8 " + strconv.Itoa(int(opts.UTF8)))
}
if !opts.FieldNameMatching.valid() {
return nil, errors.New("cbor: invalid FieldNameMatching " + strconv.Itoa(int(opts.FieldNameMatching)))
}
if !opts.BigIntDec.valid() {
return nil, errors.New("cbor: invalid BigIntDec " + strconv.Itoa(int(opts.BigIntDec)))
}
if opts.DefaultByteStringType != nil &&
opts.DefaultByteStringType.Kind() != reflect.String &&
(opts.DefaultByteStringType.Kind() != reflect.Slice || opts.DefaultByteStringType.Elem().Kind() != reflect.Uint8) {
return nil, fmt.Errorf("cbor: invalid DefaultByteStringType: %s is not of kind string or []uint8", opts.DefaultByteStringType)
}
if !opts.ByteStringToString.valid() {
return nil, errors.New("cbor: invalid ByteStringToString " + strconv.Itoa(int(opts.ByteStringToString)))
}
if !opts.FieldNameByteString.valid() {
return nil, errors.New("cbor: invalid FieldNameByteString " + strconv.Itoa(int(opts.FieldNameByteString)))
}
if !opts.UnrecognizedTagToAny.valid() {
return nil, errors.New("cbor: invalid UnrecognizedTagToAnyMode " + strconv.Itoa(int(opts.UnrecognizedTagToAny)))
}
simpleValues := opts.SimpleValues
if simpleValues == nil {
simpleValues = defaultSimpleValues
}
if !opts.TimeTagToAny.valid() {
return nil, errors.New("cbor: invalid TimeTagToAny " + strconv.Itoa(int(opts.TimeTagToAny)))
}
if !opts.NaN.valid() {
return nil, errors.New("cbor: invalid NaNDec " + strconv.Itoa(int(opts.NaN)))
}
if !opts.Inf.valid() {
return nil, errors.New("cbor: invalid InfDec " + strconv.Itoa(int(opts.Inf)))
}
if !opts.ByteStringToTime.valid() {
return nil, errors.New("cbor: invalid ByteStringToTime " + strconv.Itoa(int(opts.ByteStringToTime)))
}
if !opts.ByteStringExpectedFormat.valid() {
return nil, errors.New("cbor: invalid ByteStringExpectedFormat " + strconv.Itoa(int(opts.ByteStringExpectedFormat)))
}
if !opts.BignumTag.valid() {
return nil, errors.New("cbor: invalid BignumTag " + strconv.Itoa(int(opts.BignumTag)))
}
if !opts.BinaryUnmarshaler.valid() {
return nil, errors.New("cbor: invalid BinaryUnmarshaler " + strconv.Itoa(int(opts.BinaryUnmarshaler)))
}
dm := decMode{
dupMapKey: opts.DupMapKey,
timeTag: opts.TimeTag,
maxNestedLevels: opts.MaxNestedLevels,
maxArrayElements: opts.MaxArrayElements,
maxMapPairs: opts.MaxMapPairs,
indefLength: opts.IndefLength,
tagsMd: opts.TagsMd,
intDec: opts.IntDec,
mapKeyByteString: opts.MapKeyByteString,
extraReturnErrors: opts.ExtraReturnErrors,
defaultMapType: opts.DefaultMapType,
utf8: opts.UTF8,
fieldNameMatching: opts.FieldNameMatching,
bigIntDec: opts.BigIntDec,
defaultByteStringType: opts.DefaultByteStringType,
byteStringToString: opts.ByteStringToString,
fieldNameByteString: opts.FieldNameByteString,
unrecognizedTagToAny: opts.UnrecognizedTagToAny,
timeTagToAny: opts.TimeTagToAny,
simpleValues: simpleValues,
nanDec: opts.NaN,
infDec: opts.Inf,
byteStringToTime: opts.ByteStringToTime,
byteStringExpectedFormat: opts.ByteStringExpectedFormat,
bignumTag: opts.BignumTag,
binaryUnmarshaler: opts.BinaryUnmarshaler,
}
return &dm, nil
}
// DecMode is the main interface for CBOR decoding.
type DecMode interface {
// Unmarshal parses the CBOR-encoded data into the value pointed to by v
// using the decoding mode. If v is nil, not a pointer, or a nil pointer,
// Unmarshal returns an error.
//
// See the documentation for Unmarshal for details.
Unmarshal(data []byte, v any) error
// UnmarshalFirst parses the first CBOR data item into the value pointed to by v
// using the decoding mode. Any remaining bytes are returned in rest.
//
// If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error.
//
// See the documentation for Unmarshal for details.
UnmarshalFirst(data []byte, v any) (rest []byte, err error)
// Valid checks whether data is a well-formed encoded CBOR data item and
// that it complies with configurable restrictions such as MaxNestedLevels,
// MaxArrayElements, MaxMapPairs, etc.
//
// If there are any remaining bytes after the CBOR data item,
// an ExtraneousDataError is returned.
//
// WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity)
// and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed".
//
// Deprecated: Valid is kept for compatibility and should not be used.
// Use Wellformed instead because it has a more appropriate name.
Valid(data []byte) error
// Wellformed checks whether data is a well-formed encoded CBOR data item and
// that it complies with configurable restrictions such as MaxNestedLevels,
// MaxArrayElements, MaxMapPairs, etc.
//
// If there are any remaining bytes after the CBOR data item,
// an ExtraneousDataError is returned.
Wellformed(data []byte) error
// NewDecoder returns a new decoder that reads from r using dm DecMode.
NewDecoder(r io.Reader) *Decoder
// DecOptions returns user specified options used to create this DecMode.
DecOptions() DecOptions
}
type decMode struct {
tags tagProvider
dupMapKey DupMapKeyMode
timeTag DecTagMode
maxNestedLevels int
maxArrayElements int64
maxMapPairs int64
indefLength IndefLengthMode
tagsMd TagsMode
intDec IntDecMode
mapKeyByteString MapKeyByteStringMode
extraReturnErrors ExtraDecErrorCond
defaultMapType reflect.Type
utf8 UTF8Mode
fieldNameMatching FieldNameMatchingMode
bigIntDec BigIntDecMode
defaultByteStringType reflect.Type
byteStringToString ByteStringToStringMode
fieldNameByteString FieldNameByteStringMode
unrecognizedTagToAny UnrecognizedTagToAnyMode
timeTagToAny TimeTagToAnyMode
simpleValues *SimpleValueRegistry
nanDec NaNMode
infDec InfMode
byteStringToTime ByteStringToTimeMode
byteStringExpectedFormat ByteStringExpectedFormatMode
bignumTag BignumTagMode
binaryUnmarshaler BinaryUnmarshalerMode
}
var defaultDecMode, _ = DecOptions{}.decMode()
// DecOptions returns user specified options used to create this DecMode.
func (dm *decMode) DecOptions() DecOptions {
simpleValues := dm.simpleValues
if simpleValues == defaultSimpleValues {
// Users can't explicitly set this to defaultSimpleValues. It must have been nil in
// the original DecOptions.
simpleValues = nil
}
return DecOptions{
DupMapKey: dm.dupMapKey,
TimeTag: dm.timeTag,
MaxNestedLevels: dm.maxNestedLevels,
MaxArrayElements: dm.maxArrayElements,
MaxMapPairs: dm.maxMapPairs,
IndefLength: dm.indefLength,
TagsMd: dm.tagsMd,
IntDec: dm.intDec,
MapKeyByteString: dm.mapKeyByteString,
ExtraReturnErrors: dm.extraReturnErrors,
DefaultMapType: dm.defaultMapType,
UTF8: dm.utf8,
FieldNameMatching: dm.fieldNameMatching,
BigIntDec: dm.bigIntDec,
DefaultByteStringType: dm.defaultByteStringType,
ByteStringToString: dm.byteStringToString,
FieldNameByteString: dm.fieldNameByteString,
UnrecognizedTagToAny: dm.unrecognizedTagToAny,
TimeTagToAny: dm.timeTagToAny,
SimpleValues: simpleValues,
NaN: dm.nanDec,
Inf: dm.infDec,
ByteStringToTime: dm.byteStringToTime,
ByteStringExpectedFormat: dm.byteStringExpectedFormat,
BignumTag: dm.bignumTag,
BinaryUnmarshaler: dm.binaryUnmarshaler,
}
}
// Unmarshal parses the CBOR-encoded data into the value pointed to by v
// using dm decoding mode. If v is nil, not a pointer, or a nil pointer,
// Unmarshal returns an error.
//
// See the documentation for Unmarshal for details.
func (dm *decMode) Unmarshal(data []byte, v any) error {
d := decoder{data: data, dm: dm}
// Check well-formedness.
off := d.off // Save offset before data validation
err := d.wellformed(false, false) // don't allow any extra data after valid data item.
d.off = off // Restore offset
if err != nil {
return err
}
return d.value(v)
}
// UnmarshalFirst parses the first CBOR data item into the value pointed to by v
// using dm decoding mode. Any remaining bytes are returned in rest.
//
// If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error.
//
// See the documentation for Unmarshal for details.
func (dm *decMode) UnmarshalFirst(data []byte, v any) (rest []byte, err error) {
d := decoder{data: data, dm: dm}
// check well-formedness.
off := d.off // Save offset before data validation
err = d.wellformed(true, false) // allow extra data after well-formed data item
d.off = off // Restore offset
// If it is well-formed, parse the value. This is structured like this to allow
// better test coverage
if err == nil {
err = d.value(v)
}
// If either wellformed or value returned an error, do not return rest bytes
if err != nil {
return nil, err
}
// Return the rest of the data slice (which might be len 0)
return d.data[d.off:], nil
}
// Valid checks whether data is a well-formed encoded CBOR data item and
// that it complies with configurable restrictions such as MaxNestedLevels,
// MaxArrayElements, MaxMapPairs, etc.
//
// If there are any remaining bytes after the CBOR data item,
// an ExtraneousDataError is returned.
//
// WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity)
// and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed".
//
// Deprecated: Valid is kept for compatibility and should not be used.
// Use Wellformed instead because it has a more appropriate name.
func (dm *decMode) Valid(data []byte) error {
return dm.Wellformed(data)
}
// Wellformed checks whether data is a well-formed encoded CBOR data item and
// that it complies with configurable restrictions such as MaxNestedLevels,
// MaxArrayElements, MaxMapPairs, etc.
//
// If there are any remaining bytes after the CBOR data item,
// an ExtraneousDataError is returned.
func (dm *decMode) Wellformed(data []byte) error {
d := decoder{data: data, dm: dm}
return d.wellformed(false, false)
}
// NewDecoder returns a new decoder that reads from r using dm DecMode.
func (dm *decMode) NewDecoder(r io.Reader) *Decoder {
return &Decoder{r: r, d: decoder{dm: dm}}
}
type decoder struct {
data []byte
off int64 // next read offset in data
dm *decMode
// expectedLaterEncodingTags stores a stack of encountered "Expected Later Encoding" tags,
// if any.
//
// The "Expected Later Encoding" tags (21 to 23) are valid for any data item. When decoding
// byte strings, the effective encoding comes from the tag nearest to the byte string being
// decoded. For example, the effective encoding of the byte string 21(22(h'41')) would be
// controlled by tag 22,and in the data item 23(h'42', 22([21(h'43')])]) the effective
// encoding of the byte strings h'42' and h'43' would be controlled by tag 23 and 21,
// respectively.
expectedLaterEncodingTags []uint64
}
// value decodes CBOR data item into the value pointed to by v.
// If CBOR data item fails to be decoded into v,
// error is returned and offset is moved to the next CBOR data item.
// Precondition: d.data contains at least one well-formed CBOR data item.
func (d *decoder) value(v any) error {
// v can't be nil, non-pointer, or nil pointer value.
if v == nil {
return &InvalidUnmarshalError{"cbor: Unmarshal(nil)"}
}
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer {
return &InvalidUnmarshalError{"cbor: Unmarshal(non-pointer " + rv.Type().String() + ")"}
} else if rv.IsNil() {
return &InvalidUnmarshalError{"cbor: Unmarshal(nil " + rv.Type().String() + ")"}
}
rv = rv.Elem()
return d.parseToValue(rv, getTypeInfo(rv.Type()))
}
// parseToValue decodes CBOR data to value. It assumes data is well-formed,
// and does not perform bounds checking.
func (d *decoder) parseToValue(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo
// Decode CBOR nil or CBOR undefined to pointer value by setting pointer value to nil.
if d.nextCBORNil() && v.Kind() == reflect.Pointer {
d.skip()
v.Set(reflect.Zero(v.Type()))
return nil
}
if tInfo.spclType == specialTypeIface {
if !v.IsNil() {
// Use value type
v = v.Elem()
tInfo = getTypeInfo(v.Type())
} else { //nolint:gocritic
// Create and use registered type if CBOR data is registered tag
if d.dm.tags != nil && d.nextCBORType() == cborTypeTag {
off := d.off
var tagNums []uint64
for d.nextCBORType() == cborTypeTag {
_, _, tagNum := d.getHead()
tagNums = append(tagNums, tagNum)
}
d.off = off
registeredType := d.dm.tags.getTypeFromTagNum(tagNums)
if registeredType != nil {
if registeredType.Implements(tInfo.nonPtrType) ||
reflect.PointerTo(registeredType).Implements(tInfo.nonPtrType) {
v.Set(reflect.New(registeredType))
v = v.Elem()
tInfo = getTypeInfo(registeredType)
}
}
}
}
}
// Create new value for the pointer v to point to.
// At this point, CBOR value is not nil/undefined if v is a pointer.
for v.Kind() == reflect.Pointer {
if v.IsNil() {
if !v.CanSet() {
d.skip()
return errors.New("cbor: cannot set new value for " + v.Type().String())
}
v.Set(reflect.New(v.Type().Elem()))
}
v = v.Elem()
}
// Strip self-described CBOR tag number.
for d.nextCBORType() == cborTypeTag {
off := d.off
_, _, tagNum := d.getHead()
if tagNum != tagNumSelfDescribedCBOR {
d.off = off
break
}
}
// Check validity of supported built-in tags.
off := d.off
for d.nextCBORType() == cborTypeTag {
_, _, tagNum := d.getHead()
if err := validBuiltinTag(tagNum, d.data[d.off]); err != nil {
d.skip()
return err
}
}
d.off = off
if tInfo.spclType != specialTypeNone {
switch tInfo.spclType {
case specialTypeEmptyIface:
iv, err := d.parse(false) // Skipped self-described CBOR tag number already.
if iv != nil {
v.Set(reflect.ValueOf(iv))
}
return err
case specialTypeTag:
return d.parseToTag(v)
case specialTypeTime:
if d.nextCBORNil() {
// Decoding CBOR null and undefined to time.Time is no-op.
d.skip()
return nil
}
tm, ok, err := d.parseToTime()
if err != nil {
return err
}
if ok {
v.Set(reflect.ValueOf(tm))
}
return nil
case specialTypeUnmarshalerIface:
return d.parseToUnmarshaler(v)
case specialTypeUnexportedUnmarshalerIface:
return d.parseToUnexportedUnmarshaler(v)
}
}
// Check registered tag number
if tagItem := d.getRegisteredTagItem(tInfo.nonPtrType); tagItem != nil {
t := d.nextCBORType()
if t != cborTypeTag {
if tagItem.opts.DecTag == DecTagRequired {
d.skip() // Required tag number is absent, skip entire tag
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: tInfo.typ.String(),
errorMsg: "expect CBOR tag value"}
}
} else if err := d.validRegisteredTagNums(tagItem); err != nil {
d.skip() // Skip tag content
return err
}
}
t := d.nextCBORType()
switch t {
case cborTypePositiveInt:
_, _, val := d.getHead()
return fillPositiveInt(t, val, v)
case cborTypeNegativeInt:
_, _, val := d.getHead()
if val > math.MaxInt64 {
// CBOR negative integer overflows int64, use big.Int to store value.
bi := new(big.Int)
bi.SetUint64(val)
bi.Add(bi, big.NewInt(1))
bi.Neg(bi)
if tInfo.nonPtrType == typeBigInt {
v.Set(reflect.ValueOf(*bi))
return nil
}
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: tInfo.nonPtrType.String(),
errorMsg: bi.String() + " overflows Go's int64",
}
}
nValue := int64(-1) ^ int64(val)
return fillNegativeInt(t, nValue, v)
case cborTypeByteString:
b, copied := d.parseByteString()
b, converted, err := d.applyByteStringTextConversion(b, v.Type())
if err != nil {
return err
}
copied = copied || converted
return fillByteString(t, b, !copied, v, d.dm.byteStringToString, d.dm.binaryUnmarshaler)
case cborTypeTextString:
b, err := d.parseTextString()
if err != nil {
return err
}
return fillTextString(t, b, v)
case cborTypePrimitives:
_, ai, val := d.getHead()
switch ai {
case additionalInformationAsFloat16:
f := float64(float16.Frombits(uint16(val)).Float32())
return fillFloat(t, f, v)
case additionalInformationAsFloat32:
f := float64(math.Float32frombits(uint32(val)))
return fillFloat(t, f, v)
case additionalInformationAsFloat64:
f := math.Float64frombits(val)
return fillFloat(t, f, v)
default: // ai <= 24
if d.dm.simpleValues.rejected[SimpleValue(val)] {
return &UnacceptableDataItemError{
CBORType: t.String(),
Message: "simple value " + strconv.FormatInt(int64(val), 10) + " is not recognized",
}
}
switch ai {
case additionalInformationAsFalse,
additionalInformationAsTrue:
return fillBool(t, ai == additionalInformationAsTrue, v)
case additionalInformationAsNull,
additionalInformationAsUndefined:
return fillNil(t, v)
default:
return fillPositiveInt(t, val, v)
}
}
case cborTypeTag:
_, _, tagNum := d.getHead()
switch tagNum {
case tagNumUnsignedBignum:
// Bignum (tag 2) can be decoded to uint, int, float, slice, array, or big.Int.
b, copied := d.parseByteString()
bi := new(big.Int).SetBytes(b)
if tInfo.nonPtrType == typeBigInt {
v.Set(reflect.ValueOf(*bi))
return nil
}
if tInfo.nonPtrKind == reflect.Slice || tInfo.nonPtrKind == reflect.Array {
return fillByteString(t, b, !copied, v, ByteStringToStringForbidden, d.dm.binaryUnmarshaler)
}
if bi.IsUint64() {
return fillPositiveInt(t, bi.Uint64(), v)
}
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: tInfo.nonPtrType.String(),
errorMsg: bi.String() + " overflows " + v.Type().String(),
}
case tagNumNegativeBignum:
// Bignum (tag 3) can be decoded to int, float, slice, array, or big.Int.
b, copied := d.parseByteString()
bi := new(big.Int).SetBytes(b)
bi.Add(bi, big.NewInt(1))
bi.Neg(bi)
if tInfo.nonPtrType == typeBigInt {
v.Set(reflect.ValueOf(*bi))
return nil
}
if tInfo.nonPtrKind == reflect.Slice || tInfo.nonPtrKind == reflect.Array {
return fillByteString(t, b, !copied, v, ByteStringToStringForbidden, d.dm.binaryUnmarshaler)
}
if bi.IsInt64() {
return fillNegativeInt(t, bi.Int64(), v)
}
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: tInfo.nonPtrType.String(),
errorMsg: bi.String() + " overflows " + v.Type().String(),
}
case tagNumExpectedLaterEncodingBase64URL, tagNumExpectedLaterEncodingBase64, tagNumExpectedLaterEncodingBase16:
// If conversion for interoperability with text encodings is not configured,
// treat tags 21-23 as unregistered tags.
if d.dm.byteStringToString == ByteStringToStringAllowedWithExpectedLaterEncoding || d.dm.byteStringExpectedFormat != ByteStringExpectedFormatNone {
d.expectedLaterEncodingTags = append(d.expectedLaterEncodingTags, tagNum)
defer func() {
d.expectedLaterEncodingTags = d.expectedLaterEncodingTags[:len(d.expectedLaterEncodingTags)-1]
}()
}
}
return d.parseToValue(v, tInfo)
case cborTypeArray:
if tInfo.nonPtrKind == reflect.Slice {
return d.parseArrayToSlice(v, tInfo)
} else if tInfo.nonPtrKind == reflect.Array {
return d.parseArrayToArray(v, tInfo)
} else if tInfo.nonPtrKind == reflect.Struct {
return d.parseArrayToStruct(v, tInfo)
}
d.skip()
return &UnmarshalTypeError{CBORType: t.String(), GoType: tInfo.nonPtrType.String()}
case cborTypeMap:
if tInfo.nonPtrKind == reflect.Struct {
return d.parseMapToStruct(v, tInfo)
} else if tInfo.nonPtrKind == reflect.Map {
return d.parseMapToMap(v, tInfo)
}
d.skip()
return &UnmarshalTypeError{CBORType: t.String(), GoType: tInfo.nonPtrType.String()}
}
return nil
}
func (d *decoder) parseToTag(v reflect.Value) error {
if d.nextCBORNil() {
// Decoding CBOR null and undefined to cbor.Tag is no-op.
d.skip()
return nil
}
t := d.nextCBORType()
if t != cborTypeTag {
d.skip()
return &UnmarshalTypeError{CBORType: t.String(), GoType: typeTag.String()}
}
// Unmarshal tag number
_, _, num := d.getHead()
// Unmarshal tag content
content, err := d.parse(false)
if err != nil {
return err
}
v.Set(reflect.ValueOf(Tag{num, content}))
return nil
}
// parseToTime decodes the current data item as a time.Time. The bool return value is false if and
// only if the destination value should remain unmodified.
func (d *decoder) parseToTime() (time.Time, bool, error) {
// Verify that tag number or absence of tag number is acceptable to specified timeTag.
if t := d.nextCBORType(); t == cborTypeTag {
if d.dm.timeTag == DecTagIgnored {
// Skip all enclosing tags
for t == cborTypeTag {
d.getHead()
t = d.nextCBORType()
}
if d.nextCBORNil() {
d.skip()
return time.Time{}, false, nil
}
} else {
// Read tag number
_, _, tagNum := d.getHead()
if tagNum != 0 && tagNum != 1 {
d.skip() // skip tag content
return time.Time{}, false, errors.New("cbor: wrong tag number for time.Time, got " + strconv.Itoa(int(tagNum)) + ", expect 0 or 1")
}
}
} else {
if d.dm.timeTag == DecTagRequired {
d.skip()
return time.Time{}, false, &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String(), errorMsg: "expect CBOR tag value"}
}
}
switch t := d.nextCBORType(); t {
case cborTypeByteString:
if d.dm.byteStringToTime == ByteStringToTimeAllowed {
b, _ := d.parseByteString()
t, err := time.Parse(time.RFC3339, string(b))
if err != nil {
return time.Time{}, false, fmt.Errorf("cbor: cannot set %q for time.Time: %w", string(b), err)
}
return t, true, nil
}
return time.Time{}, false, &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String()}
case cborTypeTextString:
s, err := d.parseTextString()
if err != nil {
return time.Time{}, false, err
}
t, err := time.Parse(time.RFC3339, string(s))
if err != nil {
return time.Time{}, false, errors.New("cbor: cannot set " + string(s) + " for time.Time: " + err.Error())
}
return t, true, nil
case cborTypePositiveInt:
_, _, val := d.getHead()
if val > math.MaxInt64 {
return time.Time{}, false, &UnmarshalTypeError{
CBORType: t.String(),
GoType: typeTime.String(),
errorMsg: fmt.Sprintf("%d overflows Go's int64", val),
}
}
return time.Unix(int64(val), 0), true, nil
case cborTypeNegativeInt:
_, _, val := d.getHead()
if val > math.MaxInt64 {
if val == math.MaxUint64 {
// Maximum absolute value representable by negative integer is 2^64,
// not 2^64-1, so it overflows uint64.
return time.Time{}, false, &UnmarshalTypeError{
CBORType: t.String(),
GoType: typeTime.String(),
errorMsg: "-18446744073709551616 overflows Go's int64",
}
}
return time.Time{}, false, &UnmarshalTypeError{
CBORType: t.String(),
GoType: typeTime.String(),
errorMsg: fmt.Sprintf("-%d overflows Go's int64", val+1),
}
}
return time.Unix(int64(-1)^int64(val), 0), true, nil
case cborTypePrimitives:
_, ai, val := d.getHead()
var f float64
switch ai {
case additionalInformationAsFloat16:
f = float64(float16.Frombits(uint16(val)).Float32())
case additionalInformationAsFloat32:
f = float64(math.Float32frombits(uint32(val)))
case additionalInformationAsFloat64:
f = math.Float64frombits(val)
default:
return time.Time{}, false, &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String()}
}
if math.IsNaN(f) || math.IsInf(f, 0) {
// https://www.rfc-editor.org/rfc/rfc8949.html#section-3.4.2-6
return time.Time{}, true, nil
}
seconds, fractional := math.Modf(f)
return time.Unix(int64(seconds), int64(fractional*1e9)), true, nil
default:
return time.Time{}, false, &UnmarshalTypeError{CBORType: t.String(), GoType: typeTime.String()}
}
}
// parseToUnmarshaler parses CBOR data to value implementing Unmarshaler interface.
// It assumes data is well-formed, and does not perform bounds checking.
func (d *decoder) parseToUnmarshaler(v reflect.Value) error {
if d.nextCBORNil() && v.Kind() == reflect.Pointer && v.IsNil() {
d.skip()
return nil
}
if v.Kind() != reflect.Pointer && v.CanAddr() {
v = v.Addr()
}
if u, ok := v.Interface().(Unmarshaler); ok {
start := d.off
d.skip()
return u.UnmarshalCBOR(d.data[start:d.off])
}
d.skip()
return errors.New("cbor: failed to assert " + v.Type().String() + " as cbor.Unmarshaler")
}
// parseToUnexportedUnmarshaler parses CBOR data to value implementing unmarshaler interface.
// It assumes data is well-formed, and does not perform bounds checking.
func (d *decoder) parseToUnexportedUnmarshaler(v reflect.Value) error {
if d.nextCBORNil() && v.Kind() == reflect.Pointer && v.IsNil() {
d.skip()
return nil
}
if v.Kind() != reflect.Pointer && v.CanAddr() {
v = v.Addr()
}
if u, ok := v.Interface().(unmarshaler); ok {
start := d.off
d.skip()
return u.unmarshalCBOR(d.data[start:d.off])
}
d.skip()
return errors.New("cbor: failed to assert " + v.Type().String() + " as cbor.unmarshaler")
}
// parse parses CBOR data and returns value in default Go type.
// It assumes data is well-formed, and does not perform bounds checking.
func (d *decoder) parse(skipSelfDescribedTag bool) (any, error) { //nolint:gocyclo
// Strip self-described CBOR tag number.
if skipSelfDescribedTag {
for d.nextCBORType() == cborTypeTag {
off := d.off
_, _, tagNum := d.getHead()
if tagNum != tagNumSelfDescribedCBOR {
d.off = off
break
}
}
}
// Check validity of supported built-in tags.
off := d.off
for d.nextCBORType() == cborTypeTag {
_, _, tagNum := d.getHead()
if err := validBuiltinTag(tagNum, d.data[d.off]); err != nil {
d.skip()
return nil, err
}
}
d.off = off
t := d.nextCBORType()
switch t {
case cborTypePositiveInt:
_, _, val := d.getHead()
switch d.dm.intDec {
case IntDecConvertNone:
return val, nil
case IntDecConvertSigned, IntDecConvertSignedOrFail:
if val > math.MaxInt64 {
return nil, &UnmarshalTypeError{
CBORType: t.String(),
GoType: reflect.TypeOf(int64(0)).String(),
errorMsg: strconv.FormatUint(val, 10) + " overflows Go's int64",
}
}
return int64(val), nil
case IntDecConvertSignedOrBigInt:
if val > math.MaxInt64 {
bi := new(big.Int).SetUint64(val)
if d.dm.bigIntDec == BigIntDecodePointer {
return bi, nil
}
return *bi, nil
}
return int64(val), nil
default:
// not reachable
}
case cborTypeNegativeInt:
_, _, val := d.getHead()
if val > math.MaxInt64 {
// CBOR negative integer value overflows Go int64, use big.Int instead.
bi := new(big.Int).SetUint64(val)
bi.Add(bi, big.NewInt(1))
bi.Neg(bi)
if d.dm.intDec == IntDecConvertSignedOrFail {
return nil, &UnmarshalTypeError{
CBORType: t.String(),
GoType: reflect.TypeOf(int64(0)).String(),
errorMsg: bi.String() + " overflows Go's int64",
}
}
if d.dm.bigIntDec == BigIntDecodePointer {
return bi, nil
}
return *bi, nil
}
nValue := int64(-1) ^ int64(val)
return nValue, nil
case cborTypeByteString:
b, copied := d.parseByteString()
var effectiveByteStringType = d.dm.defaultByteStringType
if effectiveByteStringType == nil {
effectiveByteStringType = typeByteSlice
}
b, converted, err := d.applyByteStringTextConversion(b, effectiveByteStringType)
if err != nil {
return nil, err
}
copied = copied || converted
switch effectiveByteStringType {
case typeByteSlice:
if copied {
return b, nil
}
clone := make([]byte, len(b))
copy(clone, b)
return clone, nil
case typeString:
return string(b), nil
default:
if copied || d.dm.defaultByteStringType.Kind() == reflect.String {
// Avoid an unnecessary copy since the conversion to string must
// copy the underlying bytes.
return reflect.ValueOf(b).Convert(d.dm.defaultByteStringType).Interface(), nil
}
clone := make([]byte, len(b))
copy(clone, b)
return reflect.ValueOf(clone).Convert(d.dm.defaultByteStringType).Interface(), nil
}
case cborTypeTextString:
b, err := d.parseTextString()
if err != nil {
return nil, err
}
return string(b), nil
case cborTypeTag:
tagOff := d.off
_, _, tagNum := d.getHead()
contentOff := d.off
switch tagNum {
case tagNumRFC3339Time, tagNumEpochTime:
d.off = tagOff
tm, _, err := d.parseToTime()
if err != nil {
return nil, err
}
switch d.dm.timeTagToAny {
case TimeTagToTime:
return tm, nil
case TimeTagToRFC3339:
if tagNum == 1 {
tm = tm.UTC()
}
// Call time.MarshalText() to format decoded time to RFC3339 format,
// and return error on time value that cannot be represented in
// RFC3339 format. E.g. year cannot exceed 9999, etc.
text, err := tm.Truncate(time.Second).MarshalText()
if err != nil {
return nil, fmt.Errorf("cbor: decoded time cannot be represented in RFC3339 format: %v", err)
}
return string(text), nil
case TimeTagToRFC3339Nano:
if tagNum == 1 {
tm = tm.UTC()
}
// Call time.MarshalText() to format decoded time to RFC3339 format,
// and return error on time value that cannot be represented in
// RFC3339 format with sub-second precision.
text, err := tm.MarshalText()
if err != nil {
return nil, fmt.Errorf("cbor: decoded time cannot be represented in RFC3339 format with sub-second precision: %v", err)
}
return string(text), nil
default:
// not reachable
}
case tagNumUnsignedBignum:
b, _ := d.parseByteString()
bi := new(big.Int).SetBytes(b)
if d.dm.bigIntDec == BigIntDecodePointer {
return bi, nil
}
return *bi, nil
case tagNumNegativeBignum:
b, _ := d.parseByteString()
bi := new(big.Int).SetBytes(b)
bi.Add(bi, big.NewInt(1))
bi.Neg(bi)
if d.dm.bigIntDec == BigIntDecodePointer {
return bi, nil
}
return *bi, nil
case tagNumExpectedLaterEncodingBase64URL, tagNumExpectedLaterEncodingBase64, tagNumExpectedLaterEncodingBase16:
// If conversion for interoperability with text encodings is not configured,
// treat tags 21-23 as unregistered tags.
if d.dm.byteStringToString == ByteStringToStringAllowedWithExpectedLaterEncoding ||
d.dm.byteStringExpectedFormat != ByteStringExpectedFormatNone {
d.expectedLaterEncodingTags = append(d.expectedLaterEncodingTags, tagNum)
defer func() {
d.expectedLaterEncodingTags = d.expectedLaterEncodingTags[:len(d.expectedLaterEncodingTags)-1]
}()
return d.parse(false)
}
}
if d.dm.tags != nil {
// Parse to specified type if tag number is registered.
tagNums := []uint64{tagNum}
for d.nextCBORType() == cborTypeTag {
_, _, num := d.getHead()
tagNums = append(tagNums, num)
}
registeredType := d.dm.tags.getTypeFromTagNum(tagNums)
if registeredType != nil {
d.off = tagOff
rv := reflect.New(registeredType)
if err := d.parseToValue(rv.Elem(), getTypeInfo(registeredType)); err != nil {
return nil, err
}
return rv.Elem().Interface(), nil
}
}
// Parse tag content
d.off = contentOff
content, err := d.parse(false)
if err != nil {
return nil, err
}
if d.dm.unrecognizedTagToAny == UnrecognizedTagContentToAny {
return content, nil
}
return Tag{tagNum, content}, nil
case cborTypePrimitives:
_, ai, val := d.getHead()
if ai <= 24 && d.dm.simpleValues.rejected[SimpleValue(val)] {
return nil, &UnacceptableDataItemError{
CBORType: t.String(),
Message: "simple value " + strconv.FormatInt(int64(val), 10) + " is not recognized",
}
}
if ai < 20 || ai == 24 {
return SimpleValue(val), nil
}
switch ai {
case additionalInformationAsFalse,
additionalInformationAsTrue:
return (ai == additionalInformationAsTrue), nil
case additionalInformationAsNull,
additionalInformationAsUndefined:
return nil, nil
case additionalInformationAsFloat16:
f := float64(float16.Frombits(uint16(val)).Float32())
return f, nil
case additionalInformationAsFloat32:
f := float64(math.Float32frombits(uint32(val)))
return f, nil
case additionalInformationAsFloat64:
f := math.Float64frombits(val)
return f, nil
}
case cborTypeArray:
return d.parseArray()
case cborTypeMap:
if d.dm.defaultMapType != nil {
m := reflect.New(d.dm.defaultMapType)
err := d.parseToValue(m, getTypeInfo(m.Elem().Type()))
if err != nil {
return nil, err
}
return m.Elem().Interface(), nil
}
return d.parseMap()
}
return nil, nil
}
// parseByteString parses a CBOR encoded byte string. The returned byte slice
// may be backed directly by the input. The second return value will be true if
// and only if the slice is backed by a copy of the input. Callers are
// responsible for making a copy if necessary.
func (d *decoder) parseByteString() ([]byte, bool) {
_, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
if !indefiniteLength {
b := d.data[d.off : d.off+int64(val)]
d.off += int64(val)
return b, false
}
// Process indefinite length string chunks.
b := []byte{}
for !d.foundBreak() {
_, _, val = d.getHead()
b = append(b, d.data[d.off:d.off+int64(val)]...)
d.off += int64(val)
}
return b, true
}
// applyByteStringTextConversion converts bytes read from a byte string to or from a configured text
// encoding. If no transformation was performed (because it was not required), the original byte
// slice is returned and the bool return value is false. Otherwise, a new slice containing the
// converted bytes is returned along with the bool value true.
func (d *decoder) applyByteStringTextConversion(
src []byte,
dstType reflect.Type,
) (
dst []byte,
transformed bool,
err error,
) {
switch dstType.Kind() {
case reflect.String:
if d.dm.byteStringToString != ByteStringToStringAllowedWithExpectedLaterEncoding || len(d.expectedLaterEncodingTags) == 0 {
return src, false, nil
}
switch d.expectedLaterEncodingTags[len(d.expectedLaterEncodingTags)-1] {
case tagNumExpectedLaterEncodingBase64URL:
encoded := make([]byte, base64.RawURLEncoding.EncodedLen(len(src)))
base64.RawURLEncoding.Encode(encoded, src)
return encoded, true, nil
case tagNumExpectedLaterEncodingBase64:
encoded := make([]byte, base64.StdEncoding.EncodedLen(len(src)))
base64.StdEncoding.Encode(encoded, src)
return encoded, true, nil
case tagNumExpectedLaterEncodingBase16:
encoded := make([]byte, hex.EncodedLen(len(src)))
hex.Encode(encoded, src)
return encoded, true, nil
default:
// If this happens, there is a bug: the decoder has pushed an invalid
// "expected later encoding" tag to the stack.
panic(fmt.Sprintf("unrecognized expected later encoding tag: %d", d.expectedLaterEncodingTags))
}
case reflect.Slice:
if dstType.Elem().Kind() != reflect.Uint8 || len(d.expectedLaterEncodingTags) > 0 {
// Either the destination is not a slice of bytes, or the encoder that
// produced the input indicated an expected text encoding tag and therefore
// the content of the byte string has NOT been text encoded.
return src, false, nil
}
switch d.dm.byteStringExpectedFormat {
case ByteStringExpectedBase64URL:
decoded := make([]byte, base64.RawURLEncoding.DecodedLen(len(src)))
n, err := base64.RawURLEncoding.Decode(decoded, src)
if err != nil {
return nil, false, newByteStringExpectedFormatError(ByteStringExpectedBase64URL, err)
}
return decoded[:n], true, nil
case ByteStringExpectedBase64:
decoded := make([]byte, base64.StdEncoding.DecodedLen(len(src)))
n, err := base64.StdEncoding.Decode(decoded, src)
if err != nil {
return nil, false, newByteStringExpectedFormatError(ByteStringExpectedBase64, err)
}
return decoded[:n], true, nil
case ByteStringExpectedBase16:
decoded := make([]byte, hex.DecodedLen(len(src)))
n, err := hex.Decode(decoded, src)
if err != nil {
return nil, false, newByteStringExpectedFormatError(ByteStringExpectedBase16, err)
}
return decoded[:n], true, nil
}
}
return src, false, nil
}
// parseTextString parses CBOR encoded text string. It returns a byte slice
// to prevent creating an extra copy of string. Caller should wrap returned
// byte slice as string when needed.
func (d *decoder) parseTextString() ([]byte, error) {
_, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
if !indefiniteLength {
b := d.data[d.off : d.off+int64(val)]
d.off += int64(val)
if d.dm.utf8 == UTF8RejectInvalid && !utf8.Valid(b) {
return nil, &SemanticError{"cbor: invalid UTF-8 string"}
}
return b, nil
}
// Process indefinite length string chunks.
b := []byte{}
for !d.foundBreak() {
_, _, val = d.getHead()
x := d.data[d.off : d.off+int64(val)]
d.off += int64(val)
if d.dm.utf8 == UTF8RejectInvalid && !utf8.Valid(x) {
for !d.foundBreak() {
d.skip() // Skip remaining chunk on error
}
return nil, &SemanticError{"cbor: invalid UTF-8 string"}
}
b = append(b, x...)
}
return b, nil
}
func (d *decoder) parseArray() ([]any, error) {
_, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
hasSize := !indefiniteLength
count := int(val)
if !hasSize {
count = d.numOfItemsUntilBreak() // peek ahead to get array size to preallocate slice for better performance
}
v := make([]any, count)
var e any
var err, lastErr error
for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
if e, lastErr = d.parse(true); lastErr != nil {
if err == nil {
err = lastErr
}
continue
}
v[i] = e
}
return v, err
}
func (d *decoder) parseArrayToSlice(v reflect.Value, tInfo *typeInfo) error {
_, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
hasSize := !indefiniteLength
count := int(val)
if !hasSize {
count = d.numOfItemsUntilBreak() // peek ahead to get array size to preallocate slice for better performance
}
if v.IsNil() || v.Cap() < count || count == 0 {
v.Set(reflect.MakeSlice(tInfo.nonPtrType, count, count))
}
v.SetLen(count)
var err error
for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
if lastErr := d.parseToValue(v.Index(i), tInfo.elemTypeInfo); lastErr != nil {
if err == nil {
err = lastErr
}
}
}
return err
}
func (d *decoder) parseArrayToArray(v reflect.Value, tInfo *typeInfo) error {
_, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
hasSize := !indefiniteLength
count := int(val)
gi := 0
vLen := v.Len()
var err error
for ci := 0; (hasSize && ci < count) || (!hasSize && !d.foundBreak()); ci++ {
if gi < vLen {
// Read CBOR array element and set array element
if lastErr := d.parseToValue(v.Index(gi), tInfo.elemTypeInfo); lastErr != nil {
if err == nil {
err = lastErr
}
}
gi++
} else {
d.skip() // Skip remaining CBOR array element
}
}
// Set remaining Go array elements to zero values.
if gi < vLen {
zeroV := reflect.Zero(tInfo.elemTypeInfo.typ)
for ; gi < vLen; gi++ {
v.Index(gi).Set(zeroV)
}
}
return err
}
func (d *decoder) parseMap() (any, error) {
_, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
hasSize := !indefiniteLength
count := int(val)
m := make(map[any]any)
var k, e any
var err, lastErr error
keyCount := 0
for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
// Parse CBOR map key.
if k, lastErr = d.parse(true); lastErr != nil {
if err == nil {
err = lastErr
}
d.skip()
continue
}
// Detect if CBOR map key can be used as Go map key.
rv := reflect.ValueOf(k)
if !isHashableValue(rv) {
var converted bool
if d.dm.mapKeyByteString == MapKeyByteStringAllowed {
k, converted = convertByteSliceToByteString(k)
}
if !converted {
if err == nil {
err = &InvalidMapKeyTypeError{rv.Type().String()}
}
d.skip()
continue
}
}
// Parse CBOR map value.
if e, lastErr = d.parse(true); lastErr != nil {
if err == nil {
err = lastErr
}
continue
}
// Add key-value pair to Go map.
m[k] = e
// Detect duplicate map key.
if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
newKeyCount := len(m)
if newKeyCount == keyCount {
m[k] = nil
err = &DupMapKeyError{k, i}
i++
// skip the rest of the map
for ; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
d.skip() // Skip map key
d.skip() // Skip map value
}
return m, err
}
keyCount = newKeyCount
}
}
return m, err
}
func (d *decoder) parseMapToMap(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo
_, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
hasSize := !indefiniteLength
count := int(val)
if v.IsNil() {
mapsize := count
if !hasSize {
mapsize = 0
}
v.Set(reflect.MakeMapWithSize(tInfo.nonPtrType, mapsize))
}
keyType, eleType := tInfo.keyTypeInfo.typ, tInfo.elemTypeInfo.typ
reuseKey, reuseEle := isImmutableKind(tInfo.keyTypeInfo.kind), isImmutableKind(tInfo.elemTypeInfo.kind)
var keyValue, eleValue, zeroKeyValue, zeroEleValue reflect.Value
keyIsInterfaceType := keyType == typeIntf // If key type is interface{}, need to check if key value is hashable.
var err, lastErr error
keyCount := v.Len()
var existingKeys map[any]bool // Store existing map keys, used for detecting duplicate map key.
if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
existingKeys = make(map[any]bool, keyCount)
if keyCount > 0 {
vKeys := v.MapKeys()
for i := 0; i < len(vKeys); i++ {
existingKeys[vKeys[i].Interface()] = true
}
}
}
for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
// Parse CBOR map key.
if !keyValue.IsValid() {
keyValue = reflect.New(keyType).Elem()
} else if !reuseKey {
if !zeroKeyValue.IsValid() {
zeroKeyValue = reflect.Zero(keyType)
}
keyValue.Set(zeroKeyValue)
}
if lastErr = d.parseToValue(keyValue, tInfo.keyTypeInfo); lastErr != nil {
if err == nil {
err = lastErr
}
d.skip()
continue
}
// Detect if CBOR map key can be used as Go map key.
if keyIsInterfaceType && keyValue.Elem().IsValid() {
if !isHashableValue(keyValue.Elem()) {
var converted bool
if d.dm.mapKeyByteString == MapKeyByteStringAllowed {
var k any
k, converted = convertByteSliceToByteString(keyValue.Elem().Interface())
if converted {
keyValue.Set(reflect.ValueOf(k))
}
}
if !converted {
if err == nil {
err = &InvalidMapKeyTypeError{keyValue.Elem().Type().String()}
}
d.skip()
continue
}
}
}
// Parse CBOR map value.
if !eleValue.IsValid() {
eleValue = reflect.New(eleType).Elem()
} else if !reuseEle {
if !zeroEleValue.IsValid() {
zeroEleValue = reflect.Zero(eleType)
}
eleValue.Set(zeroEleValue)
}
if lastErr := d.parseToValue(eleValue, tInfo.elemTypeInfo); lastErr != nil {
if err == nil {
err = lastErr
}
continue
}
// Add key-value pair to Go map.
v.SetMapIndex(keyValue, eleValue)
// Detect duplicate map key.
if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
newKeyCount := v.Len()
if newKeyCount == keyCount {
kvi := keyValue.Interface()
if !existingKeys[kvi] {
v.SetMapIndex(keyValue, reflect.New(eleType).Elem())
err = &DupMapKeyError{kvi, i}
i++
// skip the rest of the map
for ; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
d.skip() // skip map key
d.skip() // skip map value
}
return err
}
delete(existingKeys, kvi)
}
keyCount = newKeyCount
}
}
return err
}
func (d *decoder) parseArrayToStruct(v reflect.Value, tInfo *typeInfo) error {
structType := getDecodingStructType(tInfo.nonPtrType)
if structType.err != nil {
return structType.err
}
if !structType.toArray {
t := d.nextCBORType()
d.skip()
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: tInfo.nonPtrType.String(),
errorMsg: "cannot decode CBOR array to struct without toarray option",
}
}
start := d.off
_, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
hasSize := !indefiniteLength
count := int(val)
if !hasSize {
count = d.numOfItemsUntilBreak() // peek ahead to get array size
}
if count != len(structType.fields) {
d.off = start
d.skip()
return &UnmarshalTypeError{
CBORType: cborTypeArray.String(),
GoType: tInfo.typ.String(),
errorMsg: "cannot decode CBOR array to struct with different number of elements",
}
}
var err, lastErr error
for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ {
f := structType.fields[i]
// Get field value by index
var fv reflect.Value
if len(f.idx) == 1 {
fv = v.Field(f.idx[0])
} else {
fv, lastErr = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) {
// Return a new value for embedded field null pointer to point to, or return error.
if !v.CanSet() {
return reflect.Value{}, errors.New("cbor: cannot set embedded pointer to unexported struct: " + v.Type().String())
}
v.Set(reflect.New(v.Type().Elem()))
return v, nil
})
if lastErr != nil && err == nil {
err = lastErr
}
if !fv.IsValid() {
d.skip()
continue
}
}
if lastErr = d.parseToValue(fv, f.typInfo); lastErr != nil {
if err == nil {
if typeError, ok := lastErr.(*UnmarshalTypeError); ok {
typeError.StructFieldName = tInfo.typ.String() + "." + f.name
err = typeError
} else {
err = lastErr
}
}
}
}
return err
}
// parseMapToStruct needs to be fast so gocyclo can be ignored for now.
func (d *decoder) parseMapToStruct(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo
structType := getDecodingStructType(tInfo.nonPtrType)
if structType.err != nil {
return structType.err
}
if structType.toArray {
t := d.nextCBORType()
d.skip()
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: tInfo.nonPtrType.String(),
errorMsg: "cannot decode CBOR map to struct with toarray option",
}
}
var err, lastErr error
// Get CBOR map size
_, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
hasSize := !indefiniteLength
count := int(val)
// Keeps track of matched struct fields
var foundFldIdx []bool
{
const maxStackFields = 128
if nfields := len(structType.fields); nfields <= maxStackFields {
// For structs with typical field counts, expect that this can be
// stack-allocated.
var a [maxStackFields]bool
foundFldIdx = a[:nfields]
} else {
foundFldIdx = make([]bool, len(structType.fields))
}
}
// Keeps track of CBOR map keys to detect duplicate map key
keyCount := 0
var mapKeys map[any]struct{}
errOnUnknownField := (d.dm.extraReturnErrors & ExtraDecErrorUnknownField) > 0
MapEntryLoop:
for j := 0; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
var f *field
// If duplicate field detection is enabled and the key at index j did not match any
// field, k will hold the map key.
var k any
t := d.nextCBORType()
if t == cborTypeTextString || (t == cborTypeByteString && d.dm.fieldNameByteString == FieldNameByteStringAllowed) {
var keyBytes []byte
if t == cborTypeTextString {
keyBytes, lastErr = d.parseTextString()
if lastErr != nil {
if err == nil {
err = lastErr
}
d.skip() // skip value
continue
}
} else { // cborTypeByteString
keyBytes, _ = d.parseByteString()
}
// Check for exact match on field name.
if i, ok := structType.fieldIndicesByName[string(keyBytes)]; ok {
fld := structType.fields[i]
if !foundFldIdx[i] {
f = fld
foundFldIdx[i] = true
} else if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
err = &DupMapKeyError{fld.name, j}
d.skip() // skip value
j++
// skip the rest of the map
for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
d.skip()
d.skip()
}
return err
} else {
// discard repeated match
d.skip()
continue MapEntryLoop
}
}
// Find field with case-insensitive match
if f == nil && d.dm.fieldNameMatching == FieldNameMatchingPreferCaseSensitive {
keyLen := len(keyBytes)
keyString := string(keyBytes)
for i := 0; i < len(structType.fields); i++ {
fld := structType.fields[i]
if len(fld.name) == keyLen && strings.EqualFold(fld.name, keyString) {
if !foundFldIdx[i] {
f = fld
foundFldIdx[i] = true
} else if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
err = &DupMapKeyError{keyString, j}
d.skip() // skip value
j++
// skip the rest of the map
for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
d.skip()
d.skip()
}
return err
} else {
// discard repeated match
d.skip()
continue MapEntryLoop
}
break
}
}
}
if d.dm.dupMapKey == DupMapKeyEnforcedAPF && f == nil {
k = string(keyBytes)
}
} else if t <= cborTypeNegativeInt { // uint/int
var nameAsInt int64
if t == cborTypePositiveInt {
_, _, val := d.getHead()
nameAsInt = int64(val)
} else {
_, _, val := d.getHead()
if val > math.MaxInt64 {
if err == nil {
err = &UnmarshalTypeError{
CBORType: t.String(),
GoType: reflect.TypeOf(int64(0)).String(),
errorMsg: "-1-" + strconv.FormatUint(val, 10) + " overflows Go's int64",
}
}
d.skip() // skip value
continue
}
nameAsInt = int64(-1) ^ int64(val)
}
// Find field
for i := 0; i < len(structType.fields); i++ {
fld := structType.fields[i]
if fld.keyAsInt && fld.nameAsInt == nameAsInt {
if !foundFldIdx[i] {
f = fld
foundFldIdx[i] = true
} else if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
err = &DupMapKeyError{nameAsInt, j}
d.skip() // skip value
j++
// skip the rest of the map
for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
d.skip()
d.skip()
}
return err
} else {
// discard repeated match
d.skip()
continue MapEntryLoop
}
break
}
}
if d.dm.dupMapKey == DupMapKeyEnforcedAPF && f == nil {
k = nameAsInt
}
} else {
if err == nil {
err = &UnmarshalTypeError{
CBORType: t.String(),
GoType: reflect.TypeOf("").String(),
errorMsg: "map key is of type " + t.String() + " and cannot be used to match struct field name",
}
}
if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
// parse key
k, lastErr = d.parse(true)
if lastErr != nil {
d.skip() // skip value
continue
}
// Detect if CBOR map key can be used as Go map key.
if !isHashableValue(reflect.ValueOf(k)) {
d.skip() // skip value
continue
}
} else {
d.skip() // skip key
}
}
if f == nil {
if errOnUnknownField {
err = &UnknownFieldError{j}
d.skip() // Skip value
j++
// skip the rest of the map
for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
d.skip()
d.skip()
}
return err
}
// Two map keys that match the same struct field are immediately considered
// duplicates. This check detects duplicates between two map keys that do
// not match a struct field. If unknown field errors are enabled, then this
// check is never reached.
if d.dm.dupMapKey == DupMapKeyEnforcedAPF {
if mapKeys == nil {
mapKeys = make(map[any]struct{}, 1)
}
mapKeys[k] = struct{}{}
newKeyCount := len(mapKeys)
if newKeyCount == keyCount {
err = &DupMapKeyError{k, j}
d.skip() // skip value
j++
// skip the rest of the map
for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ {
d.skip()
d.skip()
}
return err
}
keyCount = newKeyCount
}
d.skip() // Skip value
continue
}
// Get field value by index
var fv reflect.Value
if len(f.idx) == 1 {
fv = v.Field(f.idx[0])
} else {
fv, lastErr = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) {
// Return a new value for embedded field null pointer to point to, or return error.
if !v.CanSet() {
return reflect.Value{}, errors.New("cbor: cannot set embedded pointer to unexported struct: " + v.Type().String())
}
v.Set(reflect.New(v.Type().Elem()))
return v, nil
})
if lastErr != nil && err == nil {
err = lastErr
}
if !fv.IsValid() {
d.skip()
continue
}
}
if lastErr = d.parseToValue(fv, f.typInfo); lastErr != nil {
if err == nil {
if typeError, ok := lastErr.(*UnmarshalTypeError); ok {
typeError.StructFieldName = tInfo.nonPtrType.String() + "." + f.name
err = typeError
} else {
err = lastErr
}
}
}
}
return err
}
// validRegisteredTagNums verifies that tag numbers match registered tag numbers of type t.
// validRegisteredTagNums assumes next CBOR data type is tag. It scans all tag numbers, and stops at tag content.
func (d *decoder) validRegisteredTagNums(registeredTag *tagItem) error {
// Scan until next cbor data is tag content.
tagNums := make([]uint64, 0, 1)
for d.nextCBORType() == cborTypeTag {
_, _, val := d.getHead()
tagNums = append(tagNums, val)
}
if !registeredTag.equalTagNum(tagNums) {
return &WrongTagError{registeredTag.contentType, registeredTag.num, tagNums}
}
return nil
}
func (d *decoder) getRegisteredTagItem(vt reflect.Type) *tagItem {
if d.dm.tags != nil {
return d.dm.tags.getTagItemFromType(vt)
}
return nil
}
// skip moves data offset to the next item. skip assumes data is well-formed,
// and does not perform bounds checking.
func (d *decoder) skip() {
t, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag()
if indefiniteLength {
switch t {
case cborTypeByteString, cborTypeTextString, cborTypeArray, cborTypeMap:
for {
if isBreakFlag(d.data[d.off]) {
d.off++
return
}
d.skip()
}
}
}
switch t {
case cborTypeByteString, cborTypeTextString:
d.off += int64(val)
case cborTypeArray:
for i := 0; i < int(val); i++ {
d.skip()
}
case cborTypeMap:
for i := 0; i < int(val)*2; i++ {
d.skip()
}
case cborTypeTag:
d.skip()
}
}
func (d *decoder) getHeadWithIndefiniteLengthFlag() (
t cborType,
ai byte,
val uint64,
indefiniteLength bool,
) {
t, ai, val = d.getHead()
indefiniteLength = additionalInformation(ai).isIndefiniteLength()
return
}
// getHead assumes data is well-formed, and does not perform bounds checking.
func (d *decoder) getHead() (t cborType, ai byte, val uint64) {
t, ai = parseInitialByte(d.data[d.off])
val = uint64(ai)
d.off++
if ai <= maxAdditionalInformationWithoutArgument {
return
}
if ai == additionalInformationWith1ByteArgument {
val = uint64(d.data[d.off])
d.off++
return
}
if ai == additionalInformationWith2ByteArgument {
const argumentSize = 2
val = uint64(binary.BigEndian.Uint16(d.data[d.off : d.off+argumentSize]))
d.off += argumentSize
return
}
if ai == additionalInformationWith4ByteArgument {
const argumentSize = 4
val = uint64(binary.BigEndian.Uint32(d.data[d.off : d.off+argumentSize]))
d.off += argumentSize
return
}
if ai == additionalInformationWith8ByteArgument {
const argumentSize = 8
val = binary.BigEndian.Uint64(d.data[d.off : d.off+argumentSize])
d.off += argumentSize
return
}
return
}
func (d *decoder) numOfItemsUntilBreak() int {
savedOff := d.off
i := 0
for !d.foundBreak() {
d.skip()
i++
}
d.off = savedOff
return i
}
// foundBreak returns true if next byte is CBOR break code and moves cursor by 1,
// otherwise it returns false.
// foundBreak assumes data is well-formed, and does not perform bounds checking.
func (d *decoder) foundBreak() bool {
if isBreakFlag(d.data[d.off]) {
d.off++
return true
}
return false
}
func (d *decoder) reset(data []byte) {
d.data = data
d.off = 0
d.expectedLaterEncodingTags = d.expectedLaterEncodingTags[:0]
}
func (d *decoder) nextCBORType() cborType {
return getType(d.data[d.off])
}
func (d *decoder) nextCBORNil() bool {
return d.data[d.off] == 0xf6 || d.data[d.off] == 0xf7
}
var (
typeIntf = reflect.TypeOf([]any(nil)).Elem()
typeTime = reflect.TypeOf(time.Time{})
typeBigInt = reflect.TypeOf(big.Int{})
typeUnmarshaler = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
typeUnexportedUnmarshaler = reflect.TypeOf((*unmarshaler)(nil)).Elem()
typeBinaryUnmarshaler = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
typeString = reflect.TypeOf("")
typeByteSlice = reflect.TypeOf([]byte(nil))
)
func fillNil(_ cborType, v reflect.Value) error {
switch v.Kind() {
case reflect.Slice, reflect.Map, reflect.Interface, reflect.Pointer:
v.Set(reflect.Zero(v.Type()))
return nil
}
return nil
}
func fillPositiveInt(t cborType, val uint64, v reflect.Value) error {
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if val > math.MaxInt64 {
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: v.Type().String(),
errorMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String(),
}
}
if v.OverflowInt(int64(val)) {
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: v.Type().String(),
errorMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String(),
}
}
v.SetInt(int64(val))
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if v.OverflowUint(val) {
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: v.Type().String(),
errorMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String(),
}
}
v.SetUint(val)
return nil
case reflect.Float32, reflect.Float64:
f := float64(val)
v.SetFloat(f)
return nil
}
if v.Type() == typeBigInt {
i := new(big.Int).SetUint64(val)
v.Set(reflect.ValueOf(*i))
return nil
}
return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
}
func fillNegativeInt(t cborType, val int64, v reflect.Value) error {
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if v.OverflowInt(val) {
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: v.Type().String(),
errorMsg: strconv.FormatInt(val, 10) + " overflows " + v.Type().String(),
}
}
v.SetInt(val)
return nil
case reflect.Float32, reflect.Float64:
f := float64(val)
v.SetFloat(f)
return nil
}
if v.Type() == typeBigInt {
i := new(big.Int).SetInt64(val)
v.Set(reflect.ValueOf(*i))
return nil
}
return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
}
func fillBool(t cborType, val bool, v reflect.Value) error {
if v.Kind() == reflect.Bool {
v.SetBool(val)
return nil
}
return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
}
func fillFloat(t cborType, val float64, v reflect.Value) error {
switch v.Kind() {
case reflect.Float32, reflect.Float64:
if v.OverflowFloat(val) {
return &UnmarshalTypeError{
CBORType: t.String(),
GoType: v.Type().String(),
errorMsg: strconv.FormatFloat(val, 'E', -1, 64) + " overflows " + v.Type().String(),
}
}
v.SetFloat(val)
return nil
}
return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
}
func fillByteString(t cborType, val []byte, shared bool, v reflect.Value, bsts ByteStringToStringMode, bum BinaryUnmarshalerMode) error {
if bum == BinaryUnmarshalerByteString && reflect.PointerTo(v.Type()).Implements(typeBinaryUnmarshaler) {
if v.CanAddr() {
v = v.Addr()
if u, ok := v.Interface().(encoding.BinaryUnmarshaler); ok {
// The contract of BinaryUnmarshaler forbids
// retaining the input bytes, so no copying is
// required even if val is shared.
return u.UnmarshalBinary(val)
}
}
return errors.New("cbor: cannot set new value for " + v.Type().String())
}
if bsts != ByteStringToStringForbidden && v.Kind() == reflect.String {
v.SetString(string(val))
return nil
}
if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 {
src := val
if shared {
// SetBytes shares the underlying bytes of the source slice.
src = make([]byte, len(val))
copy(src, val)
}
v.SetBytes(src)
return nil
}
if v.Kind() == reflect.Array && v.Type().Elem().Kind() == reflect.Uint8 {
vLen := v.Len()
i := 0
for ; i < vLen && i < len(val); i++ {
v.Index(i).SetUint(uint64(val[i]))
}
// Set remaining Go array elements to zero values.
if i < vLen {
zeroV := reflect.Zero(reflect.TypeOf(byte(0)))
for ; i < vLen; i++ {
v.Index(i).Set(zeroV)
}
}
return nil
}
return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
}
func fillTextString(t cborType, val []byte, v reflect.Value) error {
if v.Kind() == reflect.String {
v.SetString(string(val))
return nil
}
return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
}
func isImmutableKind(k reflect.Kind) bool {
switch k {
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64,
reflect.String:
return true
default:
return false
}
}
func isHashableValue(rv reflect.Value) bool {
switch rv.Kind() {
case reflect.Slice, reflect.Map, reflect.Func:
return false
case reflect.Struct:
switch rv.Type() {
case typeTag:
tag := rv.Interface().(Tag)
return isHashableValue(reflect.ValueOf(tag.Content))
case typeBigInt:
return false
}
}
return true
}
// convertByteSliceToByteString converts []byte to ByteString if
// - v is []byte type, or
// - v is Tag type and tag content type is []byte
// This function also handles nested tags.
// CBOR data is already verified to be well-formed before this function is used,
// so the recursion won't exceed max nested levels.
func convertByteSliceToByteString(v any) (any, bool) {
switch v := v.(type) {
case []byte:
return ByteString(v), true
case Tag:
content, converted := convertByteSliceToByteString(v.Content)
if converted {
return Tag{Number: v.Number, Content: content}, true
}
}
return v, false
}
|