serde_with/lib.rs
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
#![doc(test(attr(
allow(
unknown_lints,
// Problematic handling for foreign From<T> impls in tests
// https://github.com/rust-lang/rust/issues/121621
non_local_definitions,
// Some tests use foo as name
clippy::disallowed_names,
),
deny(
missing_debug_implementations,
rust_2018_idioms,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
warnings,
),
forbid(unsafe_code),
)))]
// Not needed for 2018 edition and conflicts with `rust_2018_idioms`
#![doc(test(no_crate_inject))]
#![doc(html_root_url = "https://docs.rs/serde_with/3.11.0/")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![no_std]
//! [![crates.io badge](https://img.shields.io/crates/v/serde_with.svg)](https://crates.io/crates/serde_with/)
//! [![Build Status](https://github.com/jonasbb/serde_with/workflows/Rust%20CI/badge.svg)](https://github.com/jonasbb/serde_with)
//! [![codecov](https://codecov.io/gh/jonasbb/serde_with/branch/master/graph/badge.svg)](https://codecov.io/gh/jonasbb/serde_with)
//! [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/4322/badge)](https://bestpractices.coreinfrastructure.org/projects/4322)
//! [![Rustexplorer](https://img.shields.io/badge/Try%20on-rustexplorer-lightgrey?logo=rust&logoColor=orange)](https://www.rustexplorer.com/b/py7ida)
//!
//! ---
//!
//! This crate provides custom de/serialization helpers to use in combination with [serde's `with` annotation][with-annotation] and with the improved [`serde_as`][as-annotation]-annotation.
//! Some common use cases are:
//!
//! * De/Serializing a type using the `Display` and `FromStr` traits, e.g., for `u8`, `url::Url`, or `mime::Mime`.
//! Check [`DisplayFromStr`] for details.
//! * Support for arrays larger than 32 elements or using const generics.
//! With `serde_as` large arrays are supported, even if they are nested in other types.
//! `[bool; 64]`, `Option<[u8; M]>`, and `Box<[[u8; 64]; N]>` are all supported, as [this examples shows](#large-and-const-generic-arrays).
//! * Skip serializing all empty `Option` types with [`#[skip_serializing_none]`][skip_serializing_none].
//! * Apply a prefix to each field name of a struct, without changing the de/serialize implementations of the struct using [`with_prefix!`][].
//! * Deserialize a comma separated list like `#hash,#tags,#are,#great` into a `Vec<String>`.
//! Check the documentation for [`serde_with::StringWithSeparator::<CommaSeparator, T>`][StringWithSeparator].
//!
//! ## Getting Help
//!
//! **Check out the [user guide][user guide] to find out more tips and tricks about this crate.**
//!
//! For further help using this crate you can [open a new discussion](https://github.com/jonasbb/serde_with/discussions/new) or ask on [users.rust-lang.org](https://users.rust-lang.org/).
//! For bugs, please open a [new issue](https://github.com/jonasbb/serde_with/issues/new) on GitHub.
//!
//! # Use `serde_with` in your Project
//!
//! ```bash
//! # Add the current version to your Cargo.toml
//! cargo add serde_with
//! ```
//!
//! The crate contains different features for integration with other common crates.
//! Check the [feature flags][] section for information about all available features.
//!
//! # Examples
//!
//! Annotate your struct or enum to enable the custom de/serializer.
//! The `#[serde_as]` attribute must be placed *before* the `#[derive]`.
//!
//! The `as` is analogous to the `with` attribute of serde.
//! You mirror the type structure of the field you want to de/serialize.
//! You can specify converters for the inner types of a field, e.g., `Vec<DisplayFromStr>`.
//! The default de/serialization behavior can be restored by using `_` as a placeholder, e.g., `BTreeMap<_, DisplayFromStr>`.
//!
//! ## `DisplayFromStr`
//!
//! [![Rustexplorer](https://img.shields.io/badge/Try%20on-rustexplorer-lightgrey?logo=rust&logoColor=orange)](https://www.rustexplorer.com/b/py7ida)
//! ```rust
//! # #[cfg(all(feature = "macros", feature = "json"))] {
//! # use serde::{Deserialize, Serialize};
//! # use serde_with::{serde_as, DisplayFromStr};
//! #[serde_as]
//! # #[derive(Debug, Eq, PartialEq)]
//! #[derive(Deserialize, Serialize)]
//! struct Foo {
//! // Serialize with Display, deserialize with FromStr
//! #[serde_as(as = "DisplayFromStr")]
//! bar: u8,
//! }
//!
//! // This will serialize
//! # let foo =
//! Foo {bar: 12}
//! # ;
//!
//! // into this JSON
//! # let json = r#"
//! {"bar": "12"}
//! # "#;
//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
//! # }
//! ```
//!
//! ## Large and const-generic arrays
//!
//! serde does not support arrays with more than 32 elements or using const-generics.
//! The `serde_as` attribute allows circumventing this restriction, even for nested types and nested arrays.
//!
//! On top of it, `[u8; N]` (aka, bytes) can use the specialized `"Bytes"` for efficiency much like the `serde_bytes` crate.
//!
//! [![Rustexplorer](https://img.shields.io/badge/Try%20on-rustexplorer-lightgrey?logo=rust&logoColor=orange)](https://www.rustexplorer.com/b/um0xyi)
//! ```rust
//! # #[cfg(all(feature = "macros", feature = "json"))] {
//! # use serde::{Deserialize, Serialize};
//! # use serde_with::{serde_as, Bytes};
//! #[serde_as]
//! # #[derive(Debug, Eq, PartialEq)]
//! #[derive(Deserialize, Serialize)]
//! struct Arrays<const N: usize, const M: usize> {
//! #[serde_as(as = "[_; N]")]
//! constgeneric: [bool; N],
//!
//! #[serde_as(as = "Box<[[_; 64]; N]>")]
//! nested: Box<[[u8; 64]; N]>,
//!
//! #[serde_as(as = "Option<[_; M]>")]
//! optional: Option<[u8; M]>,
//!
//! #[serde_as(as = "Bytes")]
//! bytes: [u8; M],
//! }
//!
//! // This allows us to serialize a struct like this
//! let arrays: Arrays<100, 128> = Arrays {
//! constgeneric: [true; 100],
//! nested: Box::new([[111; 64]; 100]),
//! optional: Some([222; 128]),
//! bytes: [0x42; 128],
//! };
//! assert!(serde_json::to_string(&arrays).is_ok());
//! # }
//! ```
//!
//! ## `skip_serializing_none`
//!
//! This situation often occurs with JSON, but other formats also support optional fields.
//! If many fields are optional, putting the annotations on the structs can become tedious.
//! The `#[skip_serializing_none]` attribute must be placed *before* the `#[derive]`.
//!
//! [![Rustexplorer](https://img.shields.io/badge/Try%20on-rustexplorer-lightgrey?logo=rust&logoColor=orange)](https://www.rustexplorer.com/b/xr1tm0)
//! ```rust
//! # #[cfg(all(feature = "macros", feature = "json"))] {
//! # use serde::{Deserialize, Serialize};
//! # use serde_with::skip_serializing_none;
//! #[skip_serializing_none]
//! # #[derive(Debug, Eq, PartialEq)]
//! #[derive(Deserialize, Serialize)]
//! struct Foo {
//! a: Option<usize>,
//! b: Option<usize>,
//! c: Option<usize>,
//! d: Option<usize>,
//! e: Option<usize>,
//! f: Option<usize>,
//! g: Option<usize>,
//! }
//!
//! // This will serialize
//! # let foo =
//! Foo {a: None, b: None, c: None, d: Some(4), e: None, f: None, g: Some(7)}
//! # ;
//!
//! // into this JSON
//! # let json = r#"
//! {"d": 4, "g": 7}
//! # "#;
//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
//! # }
//! ```
//!
//! ## Advanced `serde_as` usage
//!
//! This example is mainly supposed to highlight the flexibility of the `serde_as` annotation compared to [serde's `with` annotation][with-annotation].
//! More details about `serde_as` can be found in the [user guide].
//!
//! ```rust
//! # #[cfg(all(feature = "macros", feature = "hex"))]
//! # use {
//! # serde::{Deserialize, Serialize},
//! # serde_with::{serde_as, DisplayFromStr, DurationSeconds, hex::Hex, Map},
//! # };
//! # #[cfg(all(feature = "macros", feature = "hex"))]
//! use std::time::Duration;
//!
//! # #[cfg(all(feature = "macros", feature = "hex"))]
//! #[serde_as]
//! # #[derive(Debug, Eq, PartialEq)]
//! #[derive(Deserialize, Serialize)]
//! enum Foo {
//! Durations(
//! // Serialize them into a list of number as seconds
//! #[serde_as(as = "Vec<DurationSeconds>")]
//! Vec<Duration>,
//! ),
//! Bytes {
//! // We can treat a Vec like a map with duplicates.
//! // JSON only allows string keys, so convert i32 to strings
//! // The bytes will be hex encoded
//! #[serde_as(as = "Map<DisplayFromStr, Hex>")]
//! bytes: Vec<(i32, Vec<u8>)>,
//! }
//! }
//!
//! # #[cfg(all(feature = "macros", feature = "json", feature = "hex"))] {
//! // This will serialize
//! # let foo =
//! Foo::Durations(
//! vec![Duration::new(5, 0), Duration::new(3600, 0), Duration::new(0, 0)]
//! )
//! # ;
//! // into this JSON
//! # let json = r#"
//! {
//! "Durations": [5, 3600, 0]
//! }
//! # "#;
//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
//!
//! // and serializes
//! # let foo =
//! Foo::Bytes {
//! bytes: vec![
//! (1, vec![0, 1, 2]),
//! (-100, vec![100, 200, 255]),
//! (1, vec![0, 111, 222]),
//! ],
//! }
//! # ;
//! // into this JSON
//! # let json = r#"
//! {
//! "Bytes": {
//! "bytes": {
//! "1": "000102",
//! "-100": "64c8ff",
//! "1": "006fde"
//! }
//! }
//! }
//! # "#;
//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
//! # }
//! ```
//!
//! [`DisplayFromStr`]: https://docs.rs/serde_with/3.11.0/serde_with/struct.DisplayFromStr.html
//! [`with_prefix!`]: https://docs.rs/serde_with/3.11.0/serde_with/macro.with_prefix.html
//! [feature flags]: https://docs.rs/serde_with/3.11.0/serde_with/guide/feature_flags/index.html
//! [skip_serializing_none]: https://docs.rs/serde_with/3.11.0/serde_with/attr.skip_serializing_none.html
//! [StringWithSeparator]: https://docs.rs/serde_with/3.11.0/serde_with/struct.StringWithSeparator.html
//! [user guide]: https://docs.rs/serde_with/3.11.0/serde_with/guide/index.html
//! [with-annotation]: https://serde.rs/field-attrs.html#with
//! [as-annotation]: https://docs.rs/serde_with/3.11.0/serde_with/guide/serde_as/index.html
#[cfg(feature = "alloc")]
extern crate alloc;
#[doc(hidden)]
pub extern crate core;
#[doc(hidden)]
pub extern crate serde;
#[doc(hidden)]
pub extern crate serde_derive;
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "base64")]
#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
pub mod base64;
#[cfg(feature = "chrono_0_4")]
#[cfg_attr(docsrs, doc(cfg(feature = "chrono_0_4")))]
pub mod chrono_0_4;
/// Legacy export of the [`chrono_0_4`] module.
#[cfg(feature = "chrono")]
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
pub mod chrono {
pub use chrono_0_4::*;
}
#[cfg(feature = "alloc")]
mod content;
pub mod de;
#[cfg(feature = "alloc")]
mod duplicate_key_impls;
#[cfg(feature = "alloc")]
mod enum_map;
#[cfg(feature = "std")]
mod flatten_maybe;
pub mod formats;
#[cfg(feature = "hex")]
#[cfg_attr(docsrs, doc(cfg(feature = "hex")))]
pub mod hex;
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
pub mod json;
#[cfg(feature = "alloc")]
mod key_value_map;
pub mod rust;
#[cfg(feature = "schemars_0_8")]
#[cfg_attr(docsrs, doc(cfg(feature = "schemars_0_8")))]
pub mod schemars_0_8;
pub mod ser;
#[cfg(feature = "std")]
mod serde_conv;
#[cfg(feature = "time_0_3")]
#[cfg_attr(docsrs, doc(cfg(feature = "time_0_3")))]
pub mod time_0_3;
mod utils;
#[cfg(feature = "std")]
#[doc(hidden)]
pub mod with_prefix;
// Taken from shepmaster/snafu
// Originally licensed as MIT+Apache 2
// https://github.com/shepmaster/snafu/blob/fd37d79d4531ed1d3eebffad0d658928eb860cfe/src/lib.rs#L121-L165
#[cfg(feature = "guide")]
#[allow(unused_macro_rules)]
macro_rules! generate_guide {
(pub mod $name:ident; $($rest:tt)*) => {
generate_guide!(@gen ".", pub mod $name { } $($rest)*);
};
(pub mod $name:ident { $($children:tt)* } $($rest:tt)*) => {
generate_guide!(@gen ".", pub mod $name { $($children)* } $($rest)*);
};
(@gen $prefix:expr, ) => {};
(@gen $prefix:expr, pub mod $name:ident; $($rest:tt)*) => {
generate_guide!(@gen $prefix, pub mod $name { } $($rest)*);
};
(@gen $prefix:expr, @code pub mod $name:ident; $($rest:tt)*) => {
pub mod $name;
generate_guide!(@gen $prefix, $($rest)*);
};
(@gen $prefix:expr, pub mod $name:ident { $($children:tt)* } $($rest:tt)*) => {
doc_comment::doc_comment! {
include_str!(concat!($prefix, "/", stringify!($name), ".md")),
pub mod $name {
generate_guide!(@gen concat!($prefix, "/", stringify!($name)), $($children)*);
}
}
generate_guide!(@gen $prefix, $($rest)*);
};
}
#[cfg(feature = "guide")]
generate_guide! {
pub mod guide {
@code pub mod feature_flags;
pub mod serde_as;
pub mod serde_as_transformations;
}
}
pub(crate) mod prelude {
#![allow(unused_imports)]
pub(crate) use crate::utils::duration::{DurationSigned, Sign};
pub use crate::{de::*, ser::*, *};
#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
pub use alloc::sync::{Arc, Weak as ArcWeak};
#[cfg(feature = "alloc")]
pub use alloc::{
borrow::{Cow, ToOwned},
boxed::Box,
collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque},
rc::{Rc, Weak as RcWeak},
string::{String, ToString},
vec::Vec,
};
pub use core::{
cell::{Cell, RefCell},
convert::{TryFrom, TryInto},
fmt::{self, Display},
hash::{BuildHasher, Hash},
marker::PhantomData,
ops::Bound,
option::Option,
pin::Pin,
result::Result,
str::FromStr,
time::Duration,
};
pub use serde::{
de::{
Deserialize, DeserializeOwned, DeserializeSeed, Deserializer, EnumAccess,
Error as DeError, Expected, IgnoredAny, IntoDeserializer, MapAccess, SeqAccess,
Unexpected, VariantAccess, Visitor,
},
forward_to_deserialize_any,
ser::{
Error as SerError, Impossible, Serialize, SerializeMap, SerializeSeq, SerializeStruct,
SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant,
Serializer,
},
};
#[cfg(feature = "std")]
pub use std::{
collections::{HashMap, HashSet},
sync::{Mutex, RwLock},
time::SystemTime,
};
}
/// This module is not part of the public API
///
/// Do not rely on any exports.
#[doc(hidden)]
pub mod __private__ {
pub use crate::prelude::*;
}
#[cfg(feature = "alloc")]
#[doc(inline)]
pub use crate::enum_map::EnumMap;
#[cfg(feature = "alloc")]
#[doc(inline)]
pub use crate::key_value_map::KeyValueMap;
#[doc(inline)]
pub use crate::{de::DeserializeAs, ser::SerializeAs};
use core::marker::PhantomData;
// Re-Export all proc_macros, as these should be seen as part of the serde_with crate
#[cfg(feature = "macros")]
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
#[doc(inline)]
pub use serde_with_macros::*;
/// Adapter to convert from `serde_as` to the serde traits.
///
/// The `As` type adapter allows using types which implement [`DeserializeAs`] or [`SerializeAs`] in place of serde's `with` annotation.
/// The `with` annotation allows running custom code when de/serializing, however it is quite inflexible.
/// The traits [`DeserializeAs`]/[`SerializeAs`] are more flexible, as they allow composition and nesting of types to create more complex de/serialization behavior.
/// However, they are not directly compatible with serde, as they are not provided by serde.
/// The `As` type adapter makes them compatible, by forwarding the function calls to `serialize`/`deserialize` to the corresponding functions `serialize_as` and `deserialize_as`.
///
/// It is not required to use this type directly.
/// Instead, it is highly encouraged to use the [`#[serde_as]`][serde_as] attribute since it includes further usability improvements.
/// If the use of the use of the proc-macro is not acceptable, then `As` can be used directly with serde.
///
/// ```rust
/// # #[cfg(feature = "alloc")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_with::{As, DisplayFromStr};
/// #
/// # #[allow(dead_code)]
/// #[derive(Deserialize, Serialize)]
/// # struct S {
/// // Serialize numbers as sequence of strings, using Display and FromStr
/// #[serde(with = "As::<Vec<DisplayFromStr>>")]
/// field: Vec<u8>,
/// # }
/// # }
/// ```
/// If the normal `Deserialize`/`Serialize` traits should be used, the placeholder type [`Same`] can be used.
/// It implements [`DeserializeAs`][]/[`SerializeAs`][], when the underlying type implements `Deserialize`/`Serialize`.
///
/// ```rust
/// # #[cfg(feature = "alloc")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_with::{As, DisplayFromStr, Same};
/// # use std::collections::BTreeMap;
/// #
/// # #[allow(dead_code)]
/// #[derive(Deserialize, Serialize)]
/// # struct S {
/// // Serialize map, turn keys into strings but keep type of value
/// #[serde(with = "As::<BTreeMap<DisplayFromStr, Same>>")]
/// field: BTreeMap<u8, i32>,
/// # }
/// # }
/// ```
///
/// [serde_as]: https://docs.rs/serde_with/3.11.0/serde_with/attr.serde_as.html
pub struct As<T: ?Sized>(PhantomData<T>);
/// Adapter to convert from `serde_as` to the serde traits.
///
/// This is the counter-type to [`As`][].
/// It can be used whenever a type implementing [`DeserializeAs`]/[`SerializeAs`] is required but the normal [`Deserialize`](::serde::Deserialize)/[`Serialize`](::serde::Serialize) traits should be used.
/// Check [`As`] for an example.
pub struct Same;
/// De/Serialize using [`Display`] and [`FromStr`] implementation
///
/// This allows deserializing a string as a number.
/// It can be very useful for serialization formats like JSON, which do not support integer
/// numbers and have to resort to strings to represent them.
///
/// Another use case is types with [`Display`] and [`FromStr`] implementations, but without serde
/// support, which can be found in some crates.
///
/// If you control the type you want to de/serialize, you can instead use the two derive macros, [`SerializeDisplay`] and [`DeserializeFromStr`].
/// They properly implement the traits [`serde::Serialize`] and [`serde::Deserialize`] such that user of the type no longer have to use the `serde_as` system.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, DisplayFromStr};
/// #
/// #[serde_as]
/// #[derive(Deserialize, Serialize)]
/// struct A {
/// #[serde_as(as = "DisplayFromStr")]
/// mime: mime::Mime,
/// #[serde_as(as = "DisplayFromStr")]
/// number: u32,
/// }
///
/// let v: A = serde_json::from_value(json!({
/// "mime": "text/plain",
/// "number": "159",
/// })).unwrap();
/// assert_eq!(mime::TEXT_PLAIN, v.mime);
/// assert_eq!(159, v.number);
///
/// let x = A {
/// mime: mime::STAR_STAR,
/// number: 777,
/// };
/// assert_eq!(json!({ "mime": "*/*", "number": "777" }), serde_json::to_value(x).unwrap());
/// # }
/// ```
///
/// [`Display`]: std::fmt::Display
/// [`FromStr`]: std::str::FromStr
pub struct DisplayFromStr;
/// Use the first format if [`De/Serializer::is_human_readable`], otherwise use the second
///
/// If the second format is not specified, the normal
/// [`Deserialize`](::serde::Deserialize)/[`Serialize`](::serde::Serialize) traits are used.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, DisplayFromStr, IfIsHumanReadable, DurationMilliSeconds, DurationSeconds};
/// use std::time::Duration;
///
/// #[serde_as]
/// #[derive(Deserialize, Serialize)]
/// struct A {
/// #[serde_as(as = "IfIsHumanReadable<DisplayFromStr>")]
/// number: u32,
/// }
/// let x = A {
/// number: 777,
/// };
/// assert_eq!(json!({ "number": "777" }), serde_json::to_value(&x).unwrap());
/// assert_eq!(vec![145, 205, 3, 9], rmp_serde::to_vec(&x).unwrap());
///
/// #[serde_as]
/// #[derive(Deserialize, Serialize)]
/// struct B {
/// #[serde_as(as = "IfIsHumanReadable<DurationMilliSeconds, DurationSeconds>")]
/// duration: Duration,
/// }
/// let x = B {
/// duration: Duration::from_millis(1500),
/// };
/// assert_eq!(json!({ "duration": 1500 }), serde_json::to_value(&x).unwrap());
/// assert_eq!(vec![145, 2], rmp_serde::to_vec(&x).unwrap());
/// # }
/// ```
/// [`De/Serializer::is_human_readable`]: serde::Serializer::is_human_readable
/// [`is_human_readable`]: serde::Serializer::is_human_readable
pub struct IfIsHumanReadable<H, F = Same>(PhantomData<H>, PhantomData<F>);
/// De/Serialize a [`Option<String>`] type while transforming the empty string to [`None`]
///
/// Convert an [`Option<T>`] from/to string using [`FromStr`] and [`Display`](::core::fmt::Display) implementations.
/// An empty string is deserialized as [`None`] and a [`None`] vice versa.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, NoneAsEmptyString};
/// #
/// #[serde_as]
/// #[derive(Deserialize, Serialize)]
/// struct A {
/// #[serde_as(as = "NoneAsEmptyString")]
/// tags: Option<String>,
/// }
///
/// let v: A = serde_json::from_value(json!({ "tags": "" })).unwrap();
/// assert_eq!(None, v.tags);
///
/// let v: A = serde_json::from_value(json!({ "tags": "Hi" })).unwrap();
/// assert_eq!(Some("Hi".to_string()), v.tags);
///
/// let x = A {
/// tags: Some("This is text".to_string()),
/// };
/// assert_eq!(json!({ "tags": "This is text" }), serde_json::to_value(x).unwrap());
///
/// let x = A {
/// tags: None,
/// };
/// assert_eq!(json!({ "tags": "" }), serde_json::to_value(x).unwrap());
/// # }
/// ```
///
/// [`FromStr`]: std::str::FromStr
pub struct NoneAsEmptyString;
/// Deserialize value and return [`Default`] on error
///
/// The main use case is ignoring error while deserializing.
/// Instead of erroring, it simply deserializes the [`Default`] variant of the type.
/// It is not possible to find the error location, i.e., which field had a deserialization error, with this method.
/// During serialization this wrapper does nothing.
/// The serialization behavior of the underlying type is preserved.
/// The type must implement [`Default`] for this conversion to work.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "macros")] {
/// # use serde::Deserialize;
/// # use serde_with::{serde_as, DefaultOnError};
/// #
/// #[serde_as]
/// #[derive(Deserialize, Debug)]
/// struct A {
/// #[serde_as(deserialize_as = "DefaultOnError")]
/// value: u32,
/// }
///
/// let a: A = serde_json::from_str(r#"{"value": 123}"#).unwrap();
/// assert_eq!(123, a.value);
///
/// // null is of invalid type
/// let a: A = serde_json::from_str(r#"{"value": null}"#).unwrap();
/// assert_eq!(0, a.value);
///
/// // String is of invalid type
/// let a: A = serde_json::from_str(r#"{"value": "123"}"#).unwrap();
/// assert_eq!(0, a.value);
///
/// // Map is of invalid type
/// let a: A = dbg!(serde_json::from_str(r#"{"value": {}}"#)).unwrap();
/// assert_eq!(0, a.value);
///
/// // Missing entries still cause errors
/// assert!(serde_json::from_str::<A>(r#"{ }"#).is_err());
/// # }
/// ```
///
/// Deserializing missing values can be supported by adding the `default` field attribute:
///
/// ```
/// # #[cfg(feature = "macros")] {
/// # use serde::Deserialize;
/// # use serde_with::{serde_as, DefaultOnError};
/// #
/// #[serde_as]
/// #[derive(Deserialize)]
/// struct B {
/// #[serde_as(deserialize_as = "DefaultOnError")]
/// #[serde(default)]
/// value: u32,
/// }
///
/// let b: B = serde_json::from_str(r#"{ }"#).unwrap();
/// assert_eq!(0, b.value);
/// # }
/// ```
///
/// `DefaultOnError` can be combined with other conversion methods.
/// In this example, we deserialize a `Vec`, each element is deserialized from a string.
/// If the string does not parse as a number, then we get the default value of 0.
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, DefaultOnError, DisplayFromStr};
/// #
/// #[serde_as]
/// #[derive(Serialize, Deserialize)]
/// struct C {
/// #[serde_as(as = "Vec<DefaultOnError<DisplayFromStr>>")]
/// value: Vec<u32>,
/// }
///
/// let c: C = serde_json::from_value(json!({
/// "value": ["1", "2", "a3", "", {}, "6"]
/// })).unwrap();
/// assert_eq!(vec![1, 2, 0, 0, 0, 6], c.value);
/// # }
/// ```
#[cfg(feature = "alloc")]
pub struct DefaultOnError<T = Same>(PhantomData<T>);
/// Deserialize [`Default`] from `null` values
///
/// Instead of erroring on `null` values, it simply deserializes the [`Default`] variant of the type.
/// During serialization this wrapper does nothing.
/// The serialization behavior of the underlying type is preserved.
/// The type must implement [`Default`] for this conversion to work.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "macros")] {
/// # use serde::Deserialize;
/// # use serde_with::{serde_as, DefaultOnNull};
/// #
/// #[serde_as]
/// #[derive(Deserialize, Debug)]
/// struct A {
/// #[serde_as(deserialize_as = "DefaultOnNull")]
/// value: u32,
/// }
///
/// let a: A = serde_json::from_str(r#"{"value": 123}"#).unwrap();
/// assert_eq!(123, a.value);
///
/// // null values are deserialized into the default, here 0
/// let a: A = serde_json::from_str(r#"{"value": null}"#).unwrap();
/// assert_eq!(0, a.value);
/// # }
/// ```
///
/// `DefaultOnNull` can be combined with other conversion methods.
/// In this example, we deserialize a `Vec`, each element is deserialized from a string.
/// If we encounter null, then we get the default value of 0.
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, DefaultOnNull, DisplayFromStr};
/// #
/// #[serde_as]
/// #[derive(Serialize, Deserialize)]
/// struct C {
/// #[serde_as(as = "Vec<DefaultOnNull<DisplayFromStr>>")]
/// value: Vec<u32>,
/// }
///
/// let c: C = serde_json::from_value(json!({
/// "value": ["1", "2", null, null, "5"]
/// })).unwrap();
/// assert_eq!(vec![1, 2, 0, 0, 5], c.value);
/// # }
/// ```
pub struct DefaultOnNull<T = Same>(PhantomData<T>);
/// Deserialize from bytes or string
///
/// Any Rust [`String`] can be converted into bytes, i.e., `Vec<u8>`.
/// Accepting both as formats while deserializing can be helpful while interacting with language
/// which have a looser definition of string than Rust.
///
/// # Example
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, BytesOrString};
/// #
/// #[serde_as]
/// #[derive(Deserialize, Serialize)]
/// struct A {
/// #[serde_as(as = "BytesOrString")]
/// bytes_or_string: Vec<u8>,
/// }
///
/// // Here we deserialize from a byte array ...
/// let j = json!({
/// "bytes_or_string": [
/// 0,
/// 1,
/// 2,
/// 3
/// ]
/// });
///
/// let a: A = serde_json::from_value(j.clone()).unwrap();
/// assert_eq!(vec![0, 1, 2, 3], a.bytes_or_string);
///
/// // and serialization works too.
/// assert_eq!(j, serde_json::to_value(&a).unwrap());
///
/// // But we also support deserializing from a String
/// let j = json!({
/// "bytes_or_string": "✨Works!"
/// });
///
/// let a: A = serde_json::from_value(j).unwrap();
/// assert_eq!("✨Works!".as_bytes(), &*a.bytes_or_string);
/// # }
/// ```
/// [`String`]: std::string::String
#[cfg(feature = "alloc")]
pub struct BytesOrString;
/// De/Serialize Durations as number of seconds.
///
/// De/serialize durations as number of seconds with sub-second precision.
/// Sub-second precision is *only* supported for [`DurationSecondsWithFrac`], but not for [`DurationSeconds`].
/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
///
/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `u64` deserialization from a `f64` will error.
/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct duration and allows deserialization from any type.
/// For example, deserializing `DurationSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
/// Serialization of integers will round the duration to the nearest value.
///
/// This type also supports [`chrono::Duration`] with the `chrono_0_4`-[feature flag].
/// This type also supports [`time::Duration`][::time_0_3::Duration] with the `time_0_3`-[feature flag].
///
/// This table lists the available `FORMAT`s for the different duration types.
/// The `FORMAT` specifier defaults to `u64`/`f64`.
///
/// | Duration Type | Converter | Available `FORMAT`s |
/// | --------------------- | ------------------------- | ------------------------ |
/// | `std::time::Duration` | `DurationSeconds` | *`u64`*, `f64`, `String` |
/// | `std::time::Duration` | `DurationSecondsWithFrac` | *`f64`*, `String` |
/// | `chrono::Duration` | `DurationSeconds` | `i64`, `f64`, `String` |
/// | `chrono::Duration` | `DurationSecondsWithFrac` | *`f64`*, `String` |
/// | `time::Duration` | `DurationSeconds` | `i64`, `f64`, `String` |
/// | `time::Duration` | `DurationSecondsWithFrac` | *`f64`*, `String` |
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, DurationSeconds};
/// use std::time::Duration;
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Durations {
/// #[serde_as(as = "DurationSeconds<u64>")]
/// d_u64: Duration,
/// #[serde_as(as = "DurationSeconds<f64>")]
/// d_f64: Duration,
/// #[serde_as(as = "DurationSeconds<String>")]
/// d_string: Duration,
/// }
///
/// // Serialization
/// // See how the values get rounded, since subsecond precision is not allowed.
///
/// let d = Durations {
/// d_u64: Duration::new(12345, 0), // Create from seconds and nanoseconds
/// d_f64: Duration::new(12345, 500_000_000),
/// d_string: Duration::new(12345, 999_999_999),
/// };
/// // Observe the different data types
/// let expected = json!({
/// "d_u64": 12345,
/// "d_f64": 12346.0,
/// "d_string": "12346",
/// });
/// assert_eq!(expected, serde_json::to_value(d).unwrap());
///
/// // Deserialization works too
/// // Subsecond precision in numbers will be rounded away
///
/// let json = json!({
/// "d_u64": 12345,
/// "d_f64": 12345.5,
/// "d_string": "12346",
/// });
/// let expected = Durations {
/// d_u64: Duration::new(12345, 0), // Create from seconds and nanoseconds
/// d_f64: Duration::new(12346, 0),
/// d_string: Duration::new(12346, 0),
/// };
/// assert_eq!(expected, serde_json::from_value(json).unwrap());
/// # }
/// ```
///
/// [`chrono::Duration`] is also supported when using the `chrono_0_4` feature.
/// It is a signed duration, thus can be de/serialized as an `i64` instead of a `u64`.
///
/// ```rust
/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, DurationSeconds};
/// # use chrono_0_4::Duration;
/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
/// use chrono::Duration;
/// # */
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Durations {
/// #[serde_as(as = "DurationSeconds<i64>")]
/// d_i64: Duration,
/// #[serde_as(as = "DurationSeconds<f64>")]
/// d_f64: Duration,
/// #[serde_as(as = "DurationSeconds<String>")]
/// d_string: Duration,
/// }
///
/// // Serialization
/// // See how the values get rounded, since subsecond precision is not allowed.
///
/// let d = Durations {
/// d_i64: Duration::seconds(-12345),
/// d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
/// d_string: Duration::seconds(12345) + Duration::nanoseconds(999_999_999),
/// };
/// // Observe the different data types
/// let expected = json!({
/// "d_i64": -12345,
/// "d_f64": -12345.0,
/// "d_string": "12346",
/// });
/// assert_eq!(expected, serde_json::to_value(d).unwrap());
///
/// // Deserialization works too
/// // Subsecond precision in numbers will be rounded away
///
/// let json = json!({
/// "d_i64": -12345,
/// "d_f64": -12345.5,
/// "d_string": "12346",
/// });
/// let expected = Durations {
/// d_i64: Duration::seconds(-12345),
/// d_f64: Duration::seconds(-12346),
/// d_string: Duration::seconds(12346),
/// };
/// assert_eq!(expected, serde_json::from_value(json).unwrap());
/// # }
/// ```
///
/// [`chrono::Duration`]: ::chrono_0_4::Duration
/// [feature flag]: https://docs.rs/serde_with/3.11.0/serde_with/guide/feature_flags/index.html
pub struct DurationSeconds<
FORMAT: formats::Format = u64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// De/Serialize Durations as number of seconds.
///
/// De/serialize durations as number of seconds with subsecond precision.
/// Subsecond precision is *only* supported for [`DurationSecondsWithFrac`], but not for [`DurationSeconds`].
/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
/// Serialization of integers will round the duration to the nearest value.
///
/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `u64` deserialization from a `f64` will error.
/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct duration and allows deserialization from any type.
/// For example, deserializing `DurationSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
///
/// This type also supports [`chrono::Duration`] with the `chrono`-[feature flag].
/// This type also supports [`time::Duration`][::time_0_3::Duration] with the `time_0_3`-[feature flag].
///
/// This table lists the available `FORMAT`s for the different duration types.
/// The `FORMAT` specifier defaults to `u64`/`f64`.
///
/// | Duration Type | Converter | Available `FORMAT`s |
/// | --------------------- | ------------------------- | ------------------------ |
/// | `std::time::Duration` | `DurationSeconds` | *`u64`*, `f64`, `String` |
/// | `std::time::Duration` | `DurationSecondsWithFrac` | *`f64`*, `String` |
/// | `chrono::Duration` | `DurationSeconds` | `i64`, `f64`, `String` |
/// | `chrono::Duration` | `DurationSecondsWithFrac` | *`f64`*, `String` |
/// | `time::Duration` | `DurationSeconds` | `i64`, `f64`, `String` |
/// | `time::Duration` | `DurationSecondsWithFrac` | *`f64`*, `String` |
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, DurationSecondsWithFrac};
/// use std::time::Duration;
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Durations {
/// #[serde_as(as = "DurationSecondsWithFrac<f64>")]
/// d_f64: Duration,
/// #[serde_as(as = "DurationSecondsWithFrac<String>")]
/// d_string: Duration,
/// }
///
/// // Serialization
/// // See how the values get rounded, since subsecond precision is not allowed.
///
/// let d = Durations {
/// d_f64: Duration::new(12345, 500_000_000), // Create from seconds and nanoseconds
/// d_string: Duration::new(12345, 999_999_000),
/// };
/// // Observe the different data types
/// let expected = json!({
/// "d_f64": 12345.5,
/// "d_string": "12345.999999",
/// });
/// assert_eq!(expected, serde_json::to_value(d).unwrap());
///
/// // Deserialization works too
/// // Subsecond precision in numbers will be rounded away
///
/// let json = json!({
/// "d_f64": 12345.5,
/// "d_string": "12345.987654",
/// });
/// let expected = Durations {
/// d_f64: Duration::new(12345, 500_000_000), // Create from seconds and nanoseconds
/// d_string: Duration::new(12345, 987_654_000),
/// };
/// assert_eq!(expected, serde_json::from_value(json).unwrap());
/// # }
/// ```
///
/// [`chrono::Duration`] is also supported when using the `chrono_0_4` feature.
/// It is a signed duration, thus can be de/serialized as an `i64` instead of a `u64`.
///
/// ```rust
/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, DurationSecondsWithFrac};
/// # use chrono_0_4::Duration;
/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
/// use chrono::Duration;
/// # */
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Durations {
/// #[serde_as(as = "DurationSecondsWithFrac<f64>")]
/// d_f64: Duration,
/// #[serde_as(as = "DurationSecondsWithFrac<String>")]
/// d_string: Duration,
/// }
///
/// // Serialization
///
/// let d = Durations {
/// d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
/// d_string: Duration::seconds(12345) + Duration::nanoseconds(999_999_000),
/// };
/// // Observe the different data types
/// let expected = json!({
/// "d_f64": -12344.5,
/// "d_string": "12345.999999",
/// });
/// assert_eq!(expected, serde_json::to_value(d).unwrap());
///
/// // Deserialization works too
///
/// let json = json!({
/// "d_f64": -12344.5,
/// "d_string": "12345.987",
/// });
/// let expected = Durations {
/// d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
/// d_string: Duration::seconds(12345) + Duration::milliseconds(987),
/// };
/// assert_eq!(expected, serde_json::from_value(json).unwrap());
/// # }
/// ```
///
/// [`chrono::Duration`]: ::chrono_0_4::Duration
/// [feature flag]: https://docs.rs/serde_with/3.11.0/serde_with/guide/feature_flags/index.html
pub struct DurationSecondsWithFrac<
FORMAT: formats::Format = f64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`DurationSeconds`] with milli-seconds as base unit.
///
/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 milli-second instead of 1 second for [`DurationSeconds`].
pub struct DurationMilliSeconds<
FORMAT: formats::Format = u64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`DurationSecondsWithFrac`] with milli-seconds as base unit.
///
/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 milli-second instead of 1 second for [`DurationSecondsWithFrac`].
pub struct DurationMilliSecondsWithFrac<
FORMAT: formats::Format = f64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`DurationSeconds`] with micro-seconds as base unit.
///
/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 micro-second instead of 1 second for [`DurationSeconds`].
pub struct DurationMicroSeconds<
FORMAT: formats::Format = u64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`DurationSecondsWithFrac`] with micro-seconds as base unit.
///
/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 micro-second instead of 1 second for [`DurationSecondsWithFrac`].
pub struct DurationMicroSecondsWithFrac<
FORMAT: formats::Format = f64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`DurationSeconds`] with nano-seconds as base unit.
///
/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 nano-second instead of 1 second for [`DurationSeconds`].
pub struct DurationNanoSeconds<
FORMAT: formats::Format = u64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`DurationSecondsWithFrac`] with nano-seconds as base unit.
///
/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 nano-second instead of 1 second for [`DurationSecondsWithFrac`].
pub struct DurationNanoSecondsWithFrac<
FORMAT: formats::Format = f64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// De/Serialize timestamps as seconds since the UNIX epoch
///
/// De/serialize timestamps as seconds since the UNIX epoch.
/// Subsecond precision is *only* supported for [`TimestampSecondsWithFrac`], but not for [`TimestampSeconds`].
/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
/// Serialization of integers will round the timestamp to the nearest value.
///
/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `i64` deserialization from a `f64` will error.
/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct timestamp and allows deserialization from any type.
/// For example, deserializing `TimestampSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
///
/// This type also supports [`chrono::DateTime`] with the `chrono_0_4`-[feature flag].
/// This type also supports [`time::OffsetDateTime`][::time_0_3::OffsetDateTime] and [`time::PrimitiveDateTime`][::time_0_3::PrimitiveDateTime] with the `time_0_3`-[feature flag].
///
/// This table lists the available `FORMAT`s for the different timestamp types.
/// The `FORMAT` specifier defaults to `i64` or `f64`.
///
/// | Timestamp Type | Converter | Available `FORMAT`s |
/// | ------------------------- | -------------------------- | ------------------------ |
/// | `std::time::SystemTime` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `std::time::SystemTime` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
/// | `chrono::DateTime<Utc>` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `chrono::DateTime<Utc>` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
/// | `chrono::DateTime<Local>` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `chrono::DateTime<Local>` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
/// | `chrono::NaiveDateTime` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `chrono::NaiveDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
/// | `time::OffsetDateTime` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `time::OffsetDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
/// | `time::PrimitiveDateTime` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `time::PrimitiveDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, TimestampSeconds};
/// use std::time::{Duration, SystemTime};
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Timestamps {
/// #[serde_as(as = "TimestampSeconds<i64>")]
/// st_i64: SystemTime,
/// #[serde_as(as = "TimestampSeconds<f64>")]
/// st_f64: SystemTime,
/// #[serde_as(as = "TimestampSeconds<String>")]
/// st_string: SystemTime,
/// }
///
/// // Serialization
/// // See how the values get rounded, since subsecond precision is not allowed.
///
/// let ts = Timestamps {
/// st_i64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 0)).unwrap(),
/// st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
/// st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 999_999_999)).unwrap(),
/// };
/// // Observe the different data types
/// let expected = json!({
/// "st_i64": 12345,
/// "st_f64": 12346.0,
/// "st_string": "12346",
/// });
/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
///
/// // Deserialization works too
/// // Subsecond precision in numbers will be rounded away
///
/// let json = json!({
/// "st_i64": 12345,
/// "st_f64": 12345.5,
/// "st_string": "12346",
/// });
/// let expected = Timestamps {
/// st_i64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 0)).unwrap(),
/// st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12346, 0)).unwrap(),
/// st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12346, 0)).unwrap(),
/// };
/// assert_eq!(expected, serde_json::from_value(json).unwrap());
/// # }
/// ```
///
/// [`chrono::DateTime<Utc>`] and [`chrono::DateTime<Local>`] are also supported when using the `chrono` feature.
/// Like [`SystemTime`], it is a signed timestamp, thus can be de/serialized as an `i64`.
///
/// ```rust
/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, TimestampSeconds};
/// # use chrono_0_4::{DateTime, Local, TimeZone, Utc};
/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
/// use chrono::{DateTime, Local, TimeZone, Utc};
/// # */
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Timestamps {
/// #[serde_as(as = "TimestampSeconds<i64>")]
/// dt_i64: DateTime<Utc>,
/// #[serde_as(as = "TimestampSeconds<f64>")]
/// dt_f64: DateTime<Local>,
/// #[serde_as(as = "TimestampSeconds<String>")]
/// dt_string: DateTime<Utc>,
/// }
///
/// // Serialization
/// // See how the values get rounded, since subsecond precision is not allowed.
///
/// let ts = Timestamps {
/// dt_i64: Utc.timestamp_opt(-12345, 0).unwrap(),
/// dt_f64: Local.timestamp_opt(-12345, 500_000_000).unwrap(),
/// dt_string: Utc.timestamp_opt(12345, 999_999_999).unwrap(),
/// };
/// // Observe the different data types
/// let expected = json!({
/// "dt_i64": -12345,
/// "dt_f64": -12345.0,
/// "dt_string": "12346",
/// });
/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
///
/// // Deserialization works too
/// // Subsecond precision in numbers will be rounded away
///
/// let json = json!({
/// "dt_i64": -12345,
/// "dt_f64": -12345.5,
/// "dt_string": "12346",
/// });
/// let expected = Timestamps {
/// dt_i64: Utc.timestamp_opt(-12345, 0).unwrap(),
/// dt_f64: Local.timestamp_opt(-12346, 0).unwrap(),
/// dt_string: Utc.timestamp_opt(12346, 0).unwrap(),
/// };
/// assert_eq!(expected, serde_json::from_value(json).unwrap());
/// # }
/// ```
///
/// [`SystemTime`]: std::time::SystemTime
/// [`chrono::DateTime<Local>`]: ::chrono_0_4::DateTime
/// [`chrono::DateTime<Utc>`]: ::chrono_0_4::DateTime
/// [feature flag]: https://docs.rs/serde_with/3.11.0/serde_with/guide/feature_flags/index.html
pub struct TimestampSeconds<
FORMAT: formats::Format = i64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// De/Serialize timestamps as seconds since the UNIX epoch
///
/// De/serialize timestamps as seconds since the UNIX epoch.
/// Subsecond precision is *only* supported for [`TimestampSecondsWithFrac`], but not for [`TimestampSeconds`].
/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
/// Serialization of integers will round the timestamp to the nearest value.
///
/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `i64` deserialization from a `f64` will error.
/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct timestamp and allows deserialization from any type.
/// For example, deserializing `TimestampSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
///
/// This type also supports [`chrono::DateTime`] and [`chrono::NaiveDateTime`][NaiveDateTime] with the `chrono`-[feature flag].
/// This type also supports [`time::OffsetDateTime`][::time_0_3::OffsetDateTime] and [`time::PrimitiveDateTime`][::time_0_3::PrimitiveDateTime] with the `time_0_3`-[feature flag].
///
/// This table lists the available `FORMAT`s for the different timestamp types.
/// The `FORMAT` specifier defaults to `i64` or `f64`.
///
/// | Timestamp Type | Converter | Available `FORMAT`s |
/// | ------------------------- | -------------------------- | ------------------------ |
/// | `std::time::SystemTime` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `std::time::SystemTime` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
/// | `chrono::DateTime<Utc>` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `chrono::DateTime<Utc>` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
/// | `chrono::DateTime<Local>` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `chrono::DateTime<Local>` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
/// | `chrono::NaiveDateTime` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `chrono::NaiveDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
/// | `time::OffsetDateTime` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `time::OffsetDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
/// | `time::PrimitiveDateTime` | `TimestampSeconds` | *`i64`*, `f64`, `String` |
/// | `time::PrimitiveDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String` |
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, TimestampSecondsWithFrac};
/// use std::time::{Duration, SystemTime};
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Timestamps {
/// #[serde_as(as = "TimestampSecondsWithFrac<f64>")]
/// st_f64: SystemTime,
/// #[serde_as(as = "TimestampSecondsWithFrac<String>")]
/// st_string: SystemTime,
/// }
///
/// // Serialization
/// // See how the values get rounded, since subsecond precision is not allowed.
///
/// let ts = Timestamps {
/// st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
/// st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 999_999_000)).unwrap(),
/// };
/// // Observe the different data types
/// let expected = json!({
/// "st_f64": 12345.5,
/// "st_string": "12345.999999",
/// });
/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
///
/// // Deserialization works too
/// // Subsecond precision in numbers will be rounded away
///
/// let json = json!({
/// "st_f64": 12345.5,
/// "st_string": "12345.987654",
/// });
/// let expected = Timestamps {
/// st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
/// st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 987_654_000)).unwrap(),
/// };
/// assert_eq!(expected, serde_json::from_value(json).unwrap());
/// # }
/// ```
///
/// [`chrono::DateTime<Utc>`] and [`chrono::DateTime<Local>`] are also supported when using the `chrono_0_4` feature.
/// Like [`SystemTime`], it is a signed timestamp, thus can be de/serialized as an `i64`.
///
/// ```rust
/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, TimestampSecondsWithFrac};
/// # use chrono_0_4::{DateTime, Local, TimeZone, Utc};
/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
/// use chrono::{DateTime, Local, TimeZone, Utc};
/// # */
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Timestamps {
/// #[serde_as(as = "TimestampSecondsWithFrac<f64>")]
/// dt_f64: DateTime<Utc>,
/// #[serde_as(as = "TimestampSecondsWithFrac<String>")]
/// dt_string: DateTime<Local>,
/// }
///
/// // Serialization
///
/// let ts = Timestamps {
/// dt_f64: Utc.timestamp_opt(-12345, 500_000_000).unwrap(),
/// dt_string: Local.timestamp_opt(12345, 999_999_000).unwrap(),
/// };
/// // Observe the different data types
/// let expected = json!({
/// "dt_f64": -12344.5,
/// "dt_string": "12345.999999",
/// });
/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
///
/// // Deserialization works too
///
/// let json = json!({
/// "dt_f64": -12344.5,
/// "dt_string": "12345.987",
/// });
/// let expected = Timestamps {
/// dt_f64: Utc.timestamp_opt(-12345, 500_000_000).unwrap(),
/// dt_string: Local.timestamp_opt(12345, 987_000_000).unwrap(),
/// };
/// assert_eq!(expected, serde_json::from_value(json).unwrap());
/// # }
/// ```
///
/// [`SystemTime`]: std::time::SystemTime
/// [`chrono::DateTime`]: ::chrono_0_4::DateTime
/// [`chrono::DateTime<Local>`]: ::chrono_0_4::DateTime
/// [`chrono::DateTime<Utc>`]: ::chrono_0_4::DateTime
/// [NaiveDateTime]: ::chrono_0_4::NaiveDateTime
/// [feature flag]: https://docs.rs/serde_with/3.11.0/serde_with/guide/feature_flags/index.html
pub struct TimestampSecondsWithFrac<
FORMAT: formats::Format = f64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`TimestampSeconds`] with milli-seconds as base unit.
///
/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 milli-second instead of 1 second for [`TimestampSeconds`].
pub struct TimestampMilliSeconds<
FORMAT: formats::Format = i64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`TimestampSecondsWithFrac`] with milli-seconds as base unit.
///
/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 milli-second instead of 1 second for [`TimestampSecondsWithFrac`].
pub struct TimestampMilliSecondsWithFrac<
FORMAT: formats::Format = f64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`TimestampSeconds`] with micro-seconds as base unit.
///
/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 micro-second instead of 1 second for [`TimestampSeconds`].
pub struct TimestampMicroSeconds<
FORMAT: formats::Format = i64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`TimestampSecondsWithFrac`] with micro-seconds as base unit.
///
/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 micro-second instead of 1 second for [`TimestampSecondsWithFrac`].
pub struct TimestampMicroSecondsWithFrac<
FORMAT: formats::Format = f64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`TimestampSeconds`] with nano-seconds as base unit.
///
/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 nano-second instead of 1 second for [`TimestampSeconds`].
pub struct TimestampNanoSeconds<
FORMAT: formats::Format = i64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Equivalent to [`TimestampSecondsWithFrac`] with nano-seconds as base unit.
///
/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 nano-second instead of 1 second for [`TimestampSecondsWithFrac`].
pub struct TimestampNanoSecondsWithFrac<
FORMAT: formats::Format = f64,
STRICTNESS: formats::Strictness = formats::Strict,
>(PhantomData<(FORMAT, STRICTNESS)>);
/// Optimized handling of owned and borrowed byte representations.
///
/// Serialization of byte sequences like `&[u8]` or `Vec<u8>` is quite inefficient since each value will be serialized individually.
/// This converter type optimizes the serialization and deserialization.
///
/// This is a port of the [`serde_bytes`] crate making it compatible with the `serde_as` annotation, which allows it to be used in more cases than provided by [`serde_bytes`].
///
/// The type provides de/serialization for these types:
///
/// * `[u8; N]`, not possible using `serde_bytes`
/// * `&[u8; N]`, not possible using `serde_bytes`
/// * `&[u8]`
/// * `Box<[u8; N]>`, not possible using `serde_bytes`
/// * `Box<[u8]>`
/// * `Vec<u8>`
/// * `Cow<'_, [u8]>`
/// * `Cow<'_, [u8; N]>`, not possible using `serde_bytes`
///
/// [`serde_bytes`]: https://crates.io/crates/serde_bytes
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_with::{serde_as, Bytes};
/// # use std::borrow::Cow;
/// #
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Test<'a> {
/// #[serde_as(as = "Bytes")]
/// array: [u8; 15],
/// #[serde_as(as = "Bytes")]
/// boxed: Box<[u8]>,
/// #[serde_as(as = "Bytes")]
/// #[serde(borrow)]
/// cow: Cow<'a, [u8]>,
/// #[serde_as(as = "Bytes")]
/// #[serde(borrow)]
/// cow_array: Cow<'a, [u8; 15]>,
/// #[serde_as(as = "Bytes")]
/// vec: Vec<u8>,
/// }
///
/// let value = Test {
/// array: *b"0123456789ABCDE",
/// boxed: b"...".to_vec().into_boxed_slice(),
/// cow: Cow::Borrowed(b"FooBar"),
/// cow_array: Cow::Borrowed(&[42u8; 15]),
/// vec: vec![0x41, 0x61, 0x21],
/// };
/// let expected = r#"(
/// array: "MDEyMzQ1Njc4OUFCQ0RF",
/// boxed: "Li4u",
/// cow: "Rm9vQmFy",
/// cow_array: "KioqKioqKioqKioqKioq",
/// vec: "QWEh",
/// )"#;
///
/// # let pretty_config = ron::ser::PrettyConfig::new()
/// # .new_line("\n".into());
/// assert_eq!(expected, ron::ser::to_string_pretty(&value, pretty_config).unwrap());
/// assert_eq!(value, ron::from_str(expected).unwrap());
/// # }
/// ```
///
/// Fully borrowed types can also be used but you'll need a Deserializer that
/// supports Serde's 0-copy deserialization:
///
/// ```
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_with::{serde_as, Bytes};
/// #
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct TestBorrows<'a> {
/// #[serde_as(as = "Bytes")]
/// #[serde(borrow)]
/// array_buf: &'a [u8; 15],
/// #[serde_as(as = "Bytes")]
/// #[serde(borrow)]
/// buf: &'a [u8],
/// }
///
/// let value = TestBorrows {
/// array_buf: &[10u8; 15],
/// buf: &[20u8, 21u8, 22u8],
/// };
/// let expected = r#"(
/// array_buf: "CgoKCgoKCgoKCgoKCgoK",
/// buf: "FBUW",
/// )"#;
///
/// # let pretty_config = ron::ser::PrettyConfig::new()
/// # .new_line("\n".into());
/// assert_eq!(expected, ron::ser::to_string_pretty(&value, pretty_config).unwrap());
/// // RON doesn't support borrowed deserialization of byte arrays
/// # }
/// ```
///
/// ## Alternative to [`BytesOrString`]
///
/// The [`Bytes`] can replace [`BytesOrString`].
/// [`Bytes`] is implemented for more types, which makes it better.
/// The serialization behavior of [`Bytes`] differs from [`BytesOrString`], therefore only `deserialize_as` should be used.
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::Deserialize;
/// # use serde_json::json;
/// # use serde_with::{serde_as, Bytes};
/// #
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, serde::Serialize)]
/// struct Test {
/// #[serde_as(deserialize_as = "Bytes")]
/// from_bytes: Vec<u8>,
/// #[serde_as(deserialize_as = "Bytes")]
/// from_str: Vec<u8>,
/// }
///
/// // Different serialized values ...
/// let j = json!({
/// "from_bytes": [70,111,111,45,66,97,114],
/// "from_str": "Foo-Bar",
/// });
///
/// // can be deserialized ...
/// let test = Test {
/// from_bytes: b"Foo-Bar".to_vec(),
/// from_str: b"Foo-Bar".to_vec(),
/// };
/// assert_eq!(test, serde_json::from_value(j).unwrap());
///
/// // and serialization will always be a byte sequence
/// # assert_eq!(json!(
/// {
/// "from_bytes": [70,111,111,45,66,97,114],
/// "from_str": [70,111,111,45,66,97,114],
/// }
/// # ), serde_json::to_value(&test).unwrap());
/// # }
/// ```
pub struct Bytes;
/// Deserialize one or many elements
///
/// Sometimes it is desirable to have a shortcut in writing 1-element lists in a config file.
/// Usually, this is done by either writing a list or the list element itself.
/// This distinction is not semantically important on the Rust side, thus both forms should deserialize into the same `Vec`.
///
/// The `OneOrMany` adapter achieves exactly this use case.
/// The serialization behavior can be tweaked to either always serialize as a list using [`PreferMany`] or to serialize as the inner element if possible using [`PreferOne`].
/// By default, [`PreferOne`] is assumed, which can also be omitted like `OneOrMany<_>`.
///
/// [`PreferMany`]: crate::formats::PreferMany
/// [`PreferOne`]: crate::formats::PreferOne
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::Deserialize;
/// # use serde_json::json;
/// # use serde_with::{serde_as, OneOrMany};
/// # use serde_with::formats::{PreferOne, PreferMany};
/// #
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, serde::Serialize)]
/// struct Data {
/// #[serde_as(as = "OneOrMany<_, PreferOne>")]
/// countries: Vec<String>,
/// #[serde_as(as = "OneOrMany<_, PreferMany>")]
/// cities: Vec<String>,
/// }
///
/// // The adapter allows deserializing a `Vec` from either
/// // a single element
/// let j = json!({
/// "countries": "Spain",
/// "cities": "Berlin",
/// });
/// assert!(serde_json::from_value::<Data>(j).is_ok());
///
/// // or from a list.
/// let j = json!({
/// "countries": ["Germany", "France"],
/// "cities": ["Amsterdam"],
/// });
/// assert!(serde_json::from_value::<Data>(j).is_ok());
///
/// // For serialization you can choose how a single element should be encoded.
/// // Either directly, with `PreferOne` (default), or as a list with `PreferMany`.
/// let data = Data {
/// countries: vec!["Spain".to_string()],
/// cities: vec!["Berlin".to_string()],
/// };
/// let j = json!({
/// "countries": "Spain",
/// "cities": ["Berlin"],
/// });
/// assert_eq!(serde_json::to_value(data).unwrap(), j);
/// # }
/// ```
#[cfg(feature = "alloc")]
pub struct OneOrMany<T, FORMAT: formats::Format = formats::PreferOne>(PhantomData<(T, FORMAT)>);
/// Try multiple deserialization options until one succeeds.
///
/// This adapter allows you to specify a list of deserialization options.
/// They are tried in order and the first one working is applied.
/// Serialization always picks the first option.
///
/// `PickFirst` has one type parameter which must be instantiated with a tuple of two, three, or four elements.
/// For example, `PickFirst<(_, DisplayFromStr)>` on a field of type `u32` allows deserializing from a number or from a string via the `FromStr` trait.
/// The value will be serialized as a number, since that is what the first type `_` indicates.
///
/// # Examples
///
/// Deserialize a number from either a number or a string.
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, DisplayFromStr, PickFirst};
/// #
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Data {
/// #[serde_as(as = "PickFirst<(_, DisplayFromStr)>")]
/// as_number: u32,
/// #[serde_as(as = "PickFirst<(DisplayFromStr, _)>")]
/// as_string: u32,
/// }
/// let data = Data {
/// as_number: 123,
/// as_string: 456
/// };
///
/// // Both fields can be deserialized from numbers:
/// let j = json!({
/// "as_number": 123,
/// "as_string": 456,
/// });
/// assert_eq!(data, serde_json::from_value(j).unwrap());
///
/// // or from a string:
/// let j = json!({
/// "as_number": "123",
/// "as_string": "456",
/// });
/// assert_eq!(data, serde_json::from_value(j).unwrap());
///
/// // For serialization the first type in the tuple determines the behavior.
/// // The `as_number` field will use the normal `Serialize` behavior and produce a number,
/// // while `as_string` used `Display` to produce a string.
/// let expected = json!({
/// "as_number": 123,
/// "as_string": "456",
/// });
/// assert_eq!(expected, serde_json::to_value(&data).unwrap());
/// # }
/// ```
#[cfg(feature = "alloc")]
pub struct PickFirst<T>(PhantomData<T>);
/// Serialize value by converting to/from a proxy type with serde support.
///
/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
///
/// ```rust
/// # #[cfg(any())] {
/// struct S {
/// #[serde_as(as = "FromInto<T>")]
/// value: O,
/// }
/// # }
/// ```
///
/// For serialization `O` needs to be `O: Into<T> + Clone`.
/// For deserialization the opposite `T: Into<O>` is required.
/// The `Clone` bound is required since `serialize` operates on a reference but `Into` implementations on references are uncommon.
///
/// **Note**: [`TryFromInto`] is the more generalized version of this adapter which uses the [`TryInto`] trait instead.
///
/// # Example
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, FromInto};
/// #
/// #[derive(Clone, Debug, PartialEq)]
/// struct Rgb {
/// red: u8,
/// green: u8,
/// blue: u8,
/// }
///
/// # /*
/// impl From<(u8, u8, u8)> for Rgb { ... }
/// impl From<Rgb> for (u8, u8, u8) { ... }
/// # */
/// #
/// # impl From<(u8, u8, u8)> for Rgb {
/// # fn from(v: (u8, u8, u8)) -> Self {
/// # Rgb {
/// # red: v.0,
/// # green: v.1,
/// # blue: v.2,
/// # }
/// # }
/// # }
/// #
/// # impl From<Rgb> for (u8, u8, u8) {
/// # fn from(v: Rgb) -> Self {
/// # (v.red, v.green, v.blue)
/// # }
/// # }
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Color {
/// #[serde_as(as = "FromInto<(u8, u8, u8)>")]
/// rgb: Rgb,
/// }
/// let color = Color {
/// rgb: Rgb {
/// red: 128,
/// green: 64,
/// blue: 32,
/// },
/// };
///
/// // Define our expected JSON form
/// let j = json!({
/// "rgb": [128, 64, 32],
/// });
/// // Ensure serialization and deserialization produce the expected results
/// assert_eq!(j, serde_json::to_value(&color).unwrap());
/// assert_eq!(color, serde_json::from_value(j).unwrap());
/// # }
/// ```
pub struct FromInto<T>(PhantomData<T>);
/// Serialize a reference value by converting to/from a proxy type with serde support.
///
/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
///
/// ```rust
/// # #[cfg(any())] {
/// struct S {
/// #[serde_as(as = "FromIntoRef<T>")]
/// value: O,
/// }
/// # }
/// ```
///
/// For serialization `O` needs to be `for<'a> &'a O: Into<T>`.
/// For deserialization the opposite `T: Into<O>` is required.
///
/// **Note**: [`TryFromIntoRef`] is the more generalized version of this adapter which uses the [`TryInto`] trait instead.
///
/// # Example
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, FromIntoRef};
/// #
/// #[derive(Debug, PartialEq)]
/// struct Rgb {
/// red: u8,
/// green: u8,
/// blue: u8,
/// }
///
/// # /*
/// impl From<(u8, u8, u8)> for Rgb { ... }
/// impl From<Rgb> for (u8, u8, u8) { ... }
/// # */
/// #
/// # impl From<(u8, u8, u8)> for Rgb {
/// # fn from(v: (u8, u8, u8)) -> Self {
/// # Rgb {
/// # red: v.0,
/// # green: v.1,
/// # blue: v.2,
/// # }
/// # }
/// # }
/// #
/// # impl<'a> From<&'a Rgb> for (u8, u8, u8) {
/// # fn from(v: &'a Rgb) -> Self {
/// # (v.red, v.green, v.blue)
/// # }
/// # }
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Color {
/// #[serde_as(as = "FromIntoRef<(u8, u8, u8)>")]
/// rgb: Rgb,
/// }
/// let color = Color {
/// rgb: Rgb {
/// red: 128,
/// green: 64,
/// blue: 32,
/// },
/// };
///
/// // Define our expected JSON form
/// let j = json!({
/// "rgb": [128, 64, 32],
/// });
/// // Ensure serialization and deserialization produce the expected results
/// assert_eq!(j, serde_json::to_value(&color).unwrap());
/// assert_eq!(color, serde_json::from_value(j).unwrap());
/// # }
/// ```
pub struct FromIntoRef<T>(PhantomData<T>);
/// Serialize value by converting to/from a proxy type with serde support.
///
/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
///
/// ```rust
/// # #[cfg(any())] {
/// struct S {
/// #[serde_as(as = "TryFromInto<T>")]
/// value: O,
/// }
/// # }
/// ```
///
/// For serialization `O` needs to be `O: TryInto<T> + Clone`.
/// For deserialization the opposite `T: TryInto<O>` is required.
/// The `Clone` bound is required since `serialize` operates on a reference but `TryInto` implementations on references are uncommon.
/// In both cases the `TryInto::Error` type must implement [`Display`](std::fmt::Display).
///
/// **Note**: [`FromInto`] is the more specialized version of this adapter which uses the infallible [`Into`] trait instead.
/// [`TryFromInto`] is strictly more general and can also be used where [`FromInto`] is applicable.
/// The example shows a use case, when only the deserialization behavior is fallible, but not serializing.
///
/// # Example
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, TryFromInto};
/// #
/// #[derive(Clone, Debug, PartialEq)]
/// enum Boollike {
/// True,
/// False,
/// }
///
/// # /*
/// impl From<Boollike> for u8 { ... }
/// # */
/// #
/// impl TryFrom<u8> for Boollike {
/// type Error = String;
/// fn try_from(v: u8) -> Result<Self, Self::Error> {
/// match v {
/// 0 => Ok(Boollike::False),
/// 1 => Ok(Boollike::True),
/// _ => Err(format!("Boolikes can only be constructed from 0 or 1 but found {}", v))
/// }
/// }
/// }
/// #
/// # impl From<Boollike> for u8 {
/// # fn from(v: Boollike) -> Self {
/// # match v {
/// # Boollike::True => 1,
/// # Boollike::False => 0,
/// # }
/// # }
/// # }
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Data {
/// #[serde_as(as = "TryFromInto<u8>")]
/// b: Boollike,
/// }
/// let data = Data {
/// b: Boollike::True,
/// };
///
/// // Define our expected JSON form
/// let j = json!({
/// "b": 1,
/// });
/// // Ensure serialization and deserialization produce the expected results
/// assert_eq!(j, serde_json::to_value(&data).unwrap());
/// assert_eq!(data, serde_json::from_value(j).unwrap());
///
/// // Numbers besides 0 or 1 should be an error
/// let j = json!({
/// "b": 2,
/// });
/// assert_eq!("Boolikes can only be constructed from 0 or 1 but found 2", serde_json::from_value::<Data>(j).unwrap_err().to_string());
/// # }
/// ```
pub struct TryFromInto<T>(PhantomData<T>);
/// Serialize a reference value by converting to/from a proxy type with serde support.
///
/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
///
/// ```rust
/// # #[cfg(any())] {
/// struct S {
/// #[serde_as(as = "TryFromIntoRef<T>")]
/// value: O,
/// }
/// # }
/// ```
///
/// For serialization `O` needs to be `for<'a> &'a O: TryInto<T>`.
/// For deserialization the opposite `T: TryInto<O>` is required.
/// In both cases the `TryInto::Error` type must implement [`Display`](std::fmt::Display).
///
/// **Note**: [`FromIntoRef`] is the more specialized version of this adapter which uses the infallible [`Into`] trait instead.
/// [`TryFromIntoRef`] is strictly more general and can also be used where [`FromIntoRef`] is applicable.
/// The example shows a use case, when only the deserialization behavior is fallible, but not serializing.
///
/// # Example
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, TryFromIntoRef};
/// #
/// #[derive(Debug, PartialEq)]
/// enum Boollike {
/// True,
/// False,
/// }
///
/// # /*
/// impl From<Boollike> for u8 { ... }
/// # */
/// #
/// impl TryFrom<u8> for Boollike {
/// type Error = String;
/// fn try_from(v: u8) -> Result<Self, Self::Error> {
/// match v {
/// 0 => Ok(Boollike::False),
/// 1 => Ok(Boollike::True),
/// _ => Err(format!("Boolikes can only be constructed from 0 or 1 but found {}", v))
/// }
/// }
/// }
/// #
/// # impl<'a> From<&'a Boollike> for u8 {
/// # fn from(v: &'a Boollike) -> Self {
/// # match v {
/// # Boollike::True => 1,
/// # Boollike::False => 0,
/// # }
/// # }
/// # }
///
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Data {
/// #[serde_as(as = "TryFromIntoRef<u8>")]
/// b: Boollike,
/// }
/// let data = Data {
/// b: Boollike::True,
/// };
///
/// // Define our expected JSON form
/// let j = json!({
/// "b": 1,
/// });
/// // Ensure serialization and deserialization produce the expected results
/// assert_eq!(j, serde_json::to_value(&data).unwrap());
/// assert_eq!(data, serde_json::from_value(j).unwrap());
///
/// // Numbers besides 0 or 1 should be an error
/// let j = json!({
/// "b": 2,
/// });
/// assert_eq!("Boolikes can only be constructed from 0 or 1 but found 2", serde_json::from_value::<Data>(j).unwrap_err().to_string());
/// # }
/// ```
pub struct TryFromIntoRef<T>(PhantomData<T>);
/// Borrow `Cow` data during deserialization when possible.
///
/// The types `Cow<'a, [u8]>`, `Cow<'a, [u8; N]>`, and `Cow<'a, str>` can borrow from the input data during deserialization.
/// serde supports this, by annotating the fields with `#[serde(borrow)]`. but does not support borrowing on nested types.
/// This gap is filled by this `BorrowCow` adapter.
///
/// Using this adapter with `Cow<'a, [u8]>`/`Cow<'a, [u8; N]>` will serialize the value as a sequence of `u8` values.
/// This *might* not allow to borrow the data during deserialization.
/// For a different format, which is also more efficient, use the [`Bytes`] adapter, which is also implemented for `Cow`.
///
/// When combined with the [`serde_as`] attribute, the `#[serde(borrow)]` annotation will be added automatically.
/// If the annotation is wrong or too broad, for example because of multiple lifetime parameters, a manual annotation is required.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_with::{serde_as, BorrowCow};
/// # use std::borrow::Cow;
/// #
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Data<'a, 'b, 'c> {
/// #[serde_as(as = "BorrowCow")]
/// str: Cow<'a, str>,
/// #[serde_as(as = "BorrowCow")]
/// slice: Cow<'b, [u8]>,
///
/// #[serde_as(as = "Option<[BorrowCow; 1]>")]
/// nested: Option<[Cow<'c, str>; 1]>,
/// }
/// let data = Data {
/// str: "foobar".into(),
/// slice: b"foobar"[..].into(),
/// nested: Some(["HelloWorld".into()]),
/// };
///
/// // Define our expected JSON form
/// let j = r#"{
/// "str": "foobar",
/// "slice": [
/// 102,
/// 111,
/// 111,
/// 98,
/// 97,
/// 114
/// ],
/// "nested": [
/// "HelloWorld"
/// ]
/// }"#;
/// // Ensure serialization and deserialization produce the expected results
/// assert_eq!(j, serde_json::to_string_pretty(&data).unwrap());
/// assert_eq!(data, serde_json::from_str(j).unwrap());
///
/// // Cow borrows from the input data
/// let deserialized: Data<'_, '_, '_> = serde_json::from_str(j).unwrap();
/// assert!(matches!(deserialized.str, Cow::Borrowed(_)));
/// assert!(matches!(deserialized.nested, Some([Cow::Borrowed(_)])));
/// // JSON does not allow borrowing bytes, so `slice` does not borrow
/// assert!(matches!(deserialized.slice, Cow::Owned(_)));
/// # }
/// ```
#[cfg(feature = "alloc")]
pub struct BorrowCow;
/// Deserialize a sequence into `Vec<T>`, skipping elements which fail to deserialize.
///
/// The serialization behavior is identical to `Vec<T>`. This is an alternative to `Vec<T>`
/// which is resilient against unexpected data.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_with::{serde_as, VecSkipError};
/// #
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// # #[non_exhaustive]
/// enum Color {
/// Red,
/// Green,
/// Blue,
/// }
/// # use Color::*;
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Palette(#[serde_as(as = "VecSkipError<_>")] Vec<Color>);
///
/// let data = Palette(vec![Blue, Green,]);
/// let source_json = r#"["Blue", "Yellow", "Green"]"#;
/// let data_json = r#"["Blue","Green"]"#;
/// // Ensure serialization and deserialization produce the expected results
/// assert_eq!(data_json, serde_json::to_string(&data).unwrap());
/// assert_eq!(data, serde_json::from_str(source_json).unwrap());
/// # }
/// ```
#[cfg(feature = "alloc")]
pub struct VecSkipError<T>(PhantomData<T>);
/// Deserialize a map, skipping keys and values which fail to deserialize.
///
/// By default serde terminates if it fails to deserialize a key or a value when deserializing
/// a map. Sometimes a map has heterogeneous keys or values but we only care about some specific
/// types, and it is desirable to skip entries on errors.
///
/// It is especially useful in conjunction to `#[serde(flatten)]` to capture a map mixed in with
/// other entries which we don't want to exhaust in the type definition.
///
/// The serialization behavior is identical to the underlying map.
///
/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
///
/// [`BTreeMap`]: std::collections::BTreeMap
/// [`HashMap`]: std::collections::HashMap
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use std::collections::BTreeMap;
/// # use serde_with::{serde_as, DisplayFromStr, MapSkipError};
/// #
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct VersionNames {
/// yanked: Vec<u16>,
/// #[serde_as(as = "MapSkipError<DisplayFromStr, _>")]
/// #[serde(flatten)]
/// names: BTreeMap<u16, String>,
/// }
///
/// let data = VersionNames {
/// yanked: vec![2, 5],
/// names: BTreeMap::from_iter([
/// (0u16, "v0".to_string()),
/// (1, "v1".to_string()),
/// (4, "v4".to_string())
/// ]),
/// };
/// let source_json = r#"{
/// "0": "v0",
/// "1": "v1",
/// "4": "v4",
/// "yanked": [2, 5],
/// "last_updated": 1704085200
/// }"#;
/// let data_json = r#"{"yanked":[2,5],"0":"v0","1":"v1","4":"v4"}"#;
/// // Ensure serialization and deserialization produce the expected results
/// assert_eq!(data_json, serde_json::to_string(&data).unwrap());
/// assert_eq!(data, serde_json::from_str(source_json).unwrap());
/// # }
/// ```
#[cfg(feature = "alloc")]
pub struct MapSkipError<K, V>(PhantomData<(K, V)>);
/// Deserialize a boolean from a number
///
/// Deserialize a number (of `u8`) and turn it into a boolean.
/// The adapter supports a [`Strict`](crate::formats::Strict) and [`Flexible`](crate::formats::Flexible) format.
/// In `Strict` mode, the number must be `0` or `1`.
/// All other values produce an error.
/// In `Flexible` mode, the number any non-zero value is converted to `true`.
///
/// During serialization only `0` or `1` are ever emitted.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, BoolFromInt};
/// #
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Data(#[serde_as(as = "BoolFromInt")] bool);
///
/// let data = Data(true);
/// let j = json!(1);
/// // Ensure serialization and deserialization produce the expected results
/// assert_eq!(j, serde_json::to_value(&data).unwrap());
/// assert_eq!(data, serde_json::from_value(j).unwrap());
///
/// // false maps to 0
/// let data = Data(false);
/// let j = json!(0);
/// assert_eq!(j, serde_json::to_value(&data).unwrap());
/// assert_eq!(data, serde_json::from_value(j).unwrap());
//
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct Flexible(#[serde_as(as = "BoolFromInt<serde_with::formats::Flexible>")] bool);
///
/// // Flexible turns any non-zero number into true
/// let data = Flexible(true);
/// let j = json!(100);
/// assert_eq!(data, serde_json::from_value(j).unwrap());
/// # }
/// ```
pub struct BoolFromInt<S: formats::Strictness = formats::Strict>(PhantomData<S>);
/// De/Serialize a delimited collection using [`Display`] and [`FromStr`] implementation
///
/// `StringWithSeparator` takes a second type, which needs to implement [`Display`]+[`FromStr`] and constitutes the inner type of the collection.
/// You can define an arbitrary separator, by specifying a type which implements [`Separator`].
/// Some common ones, like space and comma are already predefined and you can find them [here][`Separator`].
///
/// An empty string deserializes as an empty collection.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// #
/// # use serde_with::{serde_as, StringWithSeparator};
/// use serde_with::formats::{CommaSeparator, SpaceSeparator};
/// use std::collections::BTreeSet;
///
/// #[serde_as]
/// #[derive(Deserialize, Serialize)]
/// struct A {
/// #[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
/// tags: Vec<String>,
/// #[serde_as(as = "StringWithSeparator::<CommaSeparator, String>")]
/// more_tags: BTreeSet<String>,
/// }
///
/// let v: A = serde_json::from_str(r##"{
/// "tags": "#hello #world",
/// "more_tags": "foo,bar,bar"
/// }"##).unwrap();
/// assert_eq!(vec!["#hello", "#world"], v.tags);
/// assert_eq!(2, v.more_tags.len());
///
/// let x = A {
/// tags: vec!["1".to_string(), "2".to_string(), "3".to_string()],
/// more_tags: BTreeSet::new(),
/// };
/// assert_eq!(
/// r#"{"tags":"1 2 3","more_tags":""}"#,
/// serde_json::to_string(&x).unwrap()
/// );
/// # }
/// ```
///
/// [`Display`]: core::fmt::Display
/// [`FromStr`]: core::str::FromStr
/// [`Separator`]: crate::formats::Separator
/// [`serde_as`]: crate::guide::serde_as
pub struct StringWithSeparator<Sep, T>(PhantomData<(Sep, T)>);
/// This serializes a list of tuples into a map
///
/// Normally, you want to use a [`HashMap`] or a [`BTreeMap`] when deserializing a map.
/// However, sometimes this is not possible due to type constraints, e.g., if the type implements neither [`Hash`] nor [`Ord`].
/// Another use case is deserializing a map with duplicate keys.
///
/// # Examples
///
/// `Wrapper` does not implement [`Hash`] nor [`Ord`], thus prohibiting the use [`HashMap`] or [`BTreeMap`].
/// The JSON also contains a duplicate key.
///
/// [`BTreeMap`]: std::collections::BTreeMap
/// [`HashMap`]: std::collections::HashMap
/// [`Vec`]: std::vec::Vec
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_with::{serde_as, Map};
/// #
/// #[serde_as]
/// #[derive(Debug, Deserialize, Serialize, Default)]
/// struct S {
/// #[serde_as(as = "Map<_, _>")]
/// s: Vec<(Wrapper<i32>, String)>,
/// }
///
/// #[derive(Clone, Debug, Serialize, Deserialize)]
/// #[serde(transparent)]
/// struct Wrapper<T>(T);
///
/// let data = S {
/// s: vec![
/// (Wrapper(1), "a".to_string()),
/// (Wrapper(2), "b".to_string()),
/// (Wrapper(3), "c".to_string()),
/// (Wrapper(2), "d".to_string()),
/// ],
/// };
///
/// let json = r#"{
/// "s": {
/// "1": "a",
/// "2": "b",
/// "3": "c",
/// "2": "d"
/// }
/// }"#;
/// assert_eq!(json, serde_json::to_string_pretty(&data).unwrap());
/// # }
/// ```
pub struct Map<K, V>(PhantomData<(K, V)>);
/// De/Serialize a Map into a list of tuples
///
/// Some formats, like JSON, have limitations on the types of keys for maps.
/// In case of JSON, keys are restricted to strings.
/// Rust features more powerful keys, for example tuples, which can not be serialized to JSON.
///
/// This helper serializes the Map into a list of tuples, which do not have the same type restrictions.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::{Deserialize, Serialize};
/// # use serde_json::json;
/// # use serde_with::{serde_as, Seq};
/// # use std::collections::BTreeMap;
/// #
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, Serialize)]
/// struct A {
/// #[serde_as(as = "Seq<(_, _)>")]
/// s: BTreeMap<(String, u32), u32>,
/// }
///
/// // This converts the Rust type
/// let data = A {
/// s: BTreeMap::from([
/// (("Hello".to_string(), 123), 0),
/// (("World".to_string(), 456), 1),
/// ]),
/// };
///
/// // into this JSON
/// let value = json!({
/// "s": [
/// [["Hello", 123], 0],
/// [["World", 456], 1]
/// ]
/// });
///
/// assert_eq!(value, serde_json::to_value(&data).unwrap());
/// assert_eq!(data, serde_json::from_value(value).unwrap());
/// # }
/// ```
pub struct Seq<V>(PhantomData<V>);
/// Ensure no duplicate keys exist in a map.
///
/// By default serde has a last-value-wins implementation, if duplicate keys for a map exist.
/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
/// and it can indicate an error in the serialized data.
///
/// This helper returns an error if two identical keys exist in a map.
///
/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
///
/// [`BTreeMap`]: std::collections::BTreeMap
/// [`HashMap`]: std::collections::HashMap
///
/// # Example
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::Deserialize;
/// # use std::collections::HashMap;
/// # use serde_with::{serde_as, MapPreventDuplicates};
/// #
/// #[serde_as]
/// # #[derive(Debug, Eq, PartialEq)]
/// #[derive(Deserialize)]
/// struct Doc {
/// #[serde_as(as = "MapPreventDuplicates<_, _>")]
/// map: HashMap<usize, usize>,
/// }
///
/// // Maps are serialized normally,
/// let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
/// let mut v = Doc {
/// map: HashMap::new(),
/// };
/// v.map.insert(1, 1);
/// v.map.insert(2, 2);
/// v.map.insert(3, 3);
/// assert_eq!(v, serde_json::from_str(s).unwrap());
///
/// // but create an error if duplicate keys, like the `1`, exist.
/// let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
/// let res: Result<Doc, _> = serde_json::from_str(s);
/// assert!(res.is_err());
/// # }
/// ```
#[cfg(feature = "alloc")]
pub struct MapPreventDuplicates<K, V>(PhantomData<(K, V)>);
/// Ensure that the first key is taken, if duplicate keys exist
///
/// By default serde has a last-key-wins implementation, if duplicate keys for a map exist.
/// Sometimes the opposite strategy is desired. This helper implements a first-key-wins strategy.
///
/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
///
/// [`BTreeMap`]: std::collections::BTreeMap
/// [`HashMap`]: std::collections::HashMap
#[cfg(feature = "alloc")]
pub struct MapFirstKeyWins<K, V>(PhantomData<(K, V)>);
/// Ensure no duplicate values exist in a set.
///
/// By default serde has a last-value-wins implementation, if duplicate values for a set exist.
/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
/// and it can indicate an error in the serialized data.
///
/// This helper returns an error if two identical values exist in a set.
///
/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
///
/// [`BTreeSet`]: std::collections::BTreeSet
/// [`HashSet`]: std::collections::HashSet
///
/// # Example
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use std::collections::HashSet;
/// # use serde::Deserialize;
/// # use serde_with::{serde_as, SetPreventDuplicates};
/// #
/// #[serde_as]
/// # #[derive(Debug, Eq, PartialEq)]
/// #[derive(Deserialize)]
/// struct Doc {
/// #[serde_as(as = "SetPreventDuplicates<_>")]
/// set: HashSet<usize>,
/// }
///
/// // Sets are serialized normally,
/// let s = r#"{"set": [1, 2, 3, 4]}"#;
/// let v = Doc {
/// set: HashSet::from_iter(vec![1, 2, 3, 4]),
/// };
/// assert_eq!(v, serde_json::from_str(s).unwrap());
///
/// // but create an error if duplicate values, like the `1`, exist.
/// let s = r#"{"set": [1, 2, 3, 4, 1]}"#;
/// let res: Result<Doc, _> = serde_json::from_str(s);
/// assert!(res.is_err());
/// # }
/// ```
#[cfg(feature = "alloc")]
pub struct SetPreventDuplicates<T>(PhantomData<T>);
/// Ensure that the last value is taken, if duplicate values exist
///
/// By default serde has a first-value-wins implementation, if duplicate keys for a set exist.
/// Sometimes the opposite strategy is desired. This helper implements a first-value-wins strategy.
///
/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
///
/// [`BTreeSet`]: std::collections::BTreeSet
/// [`HashSet`]: std::collections::HashSet
#[cfg(feature = "alloc")]
pub struct SetLastValueWins<T>(PhantomData<T>);
/// Helper for implementing [`JsonSchema`] on serializers whose output depends
/// on the type of the concrete field.
///
/// It is added implicitly by the [`#[serde_as]`](crate::serde_as) macro when any `schemars`
/// feature is enabled.
///
/// [`JsonSchema`]: ::schemars_0_8::JsonSchema
#[cfg(feature = "schemars_0_8")]
pub struct Schema<T: ?Sized, TA>(PhantomData<T>, PhantomData<TA>);