1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147
|
// Written in the D programming language.
/*
Copyright: Copyright The D Language Foundation 2000-2013.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP walterbright.com, Walter Bright), $(HTTP erdani.com,
Andrei Alexandrescu), and Kenji Hara
Source: $(PHOBOSSRC std/format/internal/write.d)
*/
module std.format.internal.write;
import std.format.spec : FormatSpec;
import std.range.primitives : isInputRange;
import std.traits;
version (StdUnittest)
{
import std.exception : assertCTFEable;
import std.format : format;
}
package(std.format):
/*
`bool`s are formatted as `"true"` or `"false"` with `%s` and as `1` or
`0` with integral-specific format specs.
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, const(T) obj, scope const ref FormatSpec!Char f)
if (is(BooleanTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
BooleanTypeOf!T val = obj;
if (f.spec == 's')
writeAligned(w, val ? "true" : "false", f);
else
formatValueImpl(w, cast(byte) val, f);
}
@safe pure unittest
{
assertCTFEable!(
{
formatTest(false, "false");
formatTest(true, "true");
});
}
@safe unittest
{
class C1
{
bool val;
alias val this;
this(bool v){ val = v; }
}
class C2 {
bool val;
alias val this;
this(bool v){ val = v; }
override string toString() const { return "C"; }
}
() @trusted {
formatTest(new C1(false), "false");
formatTest(new C1(true), "true");
formatTest(new C2(false), "C");
formatTest(new C2(true), "C");
} ();
struct S1
{
bool val;
alias val this;
}
struct S2
{
bool val;
alias val this;
string toString() const { return "S"; }
}
formatTest(S1(false), "false");
formatTest(S1(true), "true");
formatTest(S2(false), "S");
formatTest(S2(true), "S");
}
@safe pure unittest
{
string t1 = format("[%6s] [%6s] [%-6s]", true, false, true);
assert(t1 == "[ true] [ false] [true ]");
string t2 = format("[%3s] [%-2s]", true, false);
assert(t2 == "[true] [false]");
}
// https://issues.dlang.org/show_bug.cgi?id=20534
@safe pure unittest
{
assert(format("%r",false) == "\0");
}
@safe pure unittest
{
assert(format("%07s",true) == " true");
}
@safe pure unittest
{
assert(format("%=8s",true) == " true ");
assert(format("%=9s",false) == " false ");
assert(format("%=9s",true) == " true ");
assert(format("%-=9s",true) == " true ");
assert(format("%=10s",false) == " false ");
assert(format("%-=10s",false) == " false ");
}
/*
`null` literal is formatted as `"null"`
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, const(T) obj, scope const ref FormatSpec!Char f)
if (is(immutable T == immutable typeof(null)) && !is(T == enum) && !hasToString!(T, Char))
{
import std.format : enforceFmt;
const spec = f.spec;
enforceFmt(spec == 's', "null literal cannot match %" ~ spec);
writeAligned(w, "null", f);
}
@safe pure unittest
{
import std.exception : collectExceptionMsg;
import std.format : FormatException;
import std.range.primitives : back;
assert(collectExceptionMsg!FormatException(format("%p", null)).back == 'p');
assertCTFEable!(
{
formatTest(null, "null");
});
}
@safe pure unittest
{
string t = format("[%6s] [%-6s]", null, null);
assert(t == "[ null] [null ]");
}
/*
Integrals are formatted like $(REF printf, core, stdc, stdio).
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, const(T) obj, scope const ref FormatSpec!Char f)
if (is(IntegralTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
alias U = IntegralTypeOf!T;
U val = obj; // Extracting alias this may be impure/system/may-throw
if (f.spec == 'r')
{
// raw write, skip all else and write the thing
auto raw = (ref val) @trusted {
return (cast(const char*) &val)[0 .. val.sizeof];
}(val);
import std.range.primitives : put;
if (needToSwapEndianess(f))
foreach_reverse (c; raw)
put(w, c);
else
foreach (c; raw)
put(w, c);
return;
}
static if (isSigned!U)
{
const negative = val < 0 && f.spec != 'x' && f.spec != 'X' && f.spec != 'b' && f.spec != 'o' && f.spec != 'u';
ulong arg = negative ? -cast(ulong) val : val;
}
else
{
const negative = false;
ulong arg = val;
}
arg &= Unsigned!U.max;
formatValueImplUlong!(Writer, Char)(w, arg, negative, f);
}
// Helper function for `formatValueImpl` that avoids template bloat
private void formatValueImplUlong(Writer, Char)(auto ref Writer w, ulong arg, in bool negative,
scope const ref FormatSpec!Char f)
{
immutable uint base = baseOfSpec(f.spec);
const bool zero = arg == 0;
char[64] digits = void;
size_t pos = digits.length - 1;
do
{
/* `cast(char)` is needed because value range propagation (VRP) cannot
* analyze `base` because it’s computed in a separate function
* (`baseOfSpec`). */
digits[pos--] = cast(char) ('0' + arg % base);
if (base > 10 && digits[pos + 1] > '9')
digits[pos + 1] += ((f.spec == 'x' || f.spec == 'a') ? 'a' : 'A') - '0' - 10;
arg /= base;
} while (arg > 0);
char[3] prefix = void;
size_t left = 2;
size_t right = 2;
// add sign
if (f.spec != 'x' && f.spec != 'X' && f.spec != 'b' && f.spec != 'o' && f.spec != 'u')
{
if (negative)
prefix[right++] = '-';
else if (f.flPlus)
prefix[right++] = '+';
else if (f.flSpace)
prefix[right++] = ' ';
}
// not a floating point like spec
if (f.spec == 'x' || f.spec == 'X' || f.spec == 'b' || f.spec == 'o' || f.spec == 'u'
|| f.spec == 'd' || f.spec == 's')
{
if (f.flHash && (base == 16) && !zero)
{
prefix[--left] = f.spec;
prefix[--left] = '0';
}
if (f.flHash && (base == 8) && !zero
&& (digits.length - (pos + 1) >= f.precision || f.precision == f.UNSPECIFIED))
prefix[--left] = '0';
writeAligned(w, prefix[left .. right], digits[pos + 1 .. $], "", f, true);
return;
}
FormatSpec!Char fs = f;
if (f.precision == f.UNSPECIFIED)
fs.precision = cast(typeof(fs.precision)) (digits.length - pos - 2);
// %f like output
if (f.spec == 'f' || f.spec == 'F'
|| ((f.spec == 'g' || f.spec == 'G') && (fs.precision >= digits.length - pos - 2)))
{
if (f.precision == f.UNSPECIFIED)
fs.precision = 0;
writeAligned(w, prefix[left .. right], digits[pos + 1 .. $], ".", "", fs,
(f.spec == 'g' || f.spec == 'G') ? PrecisionType.allDigits : PrecisionType.fractionalDigits);
return;
}
import std.algorithm.searching : all;
// at least one digit for %g
if ((f.spec == 'g' || f.spec == 'G') && fs.precision == 0)
fs.precision = 1;
// rounding
size_t digit_end = pos + fs.precision + ((f.spec == 'g' || f.spec == 'G') ? 1 : 2);
if (digit_end <= digits.length)
{
RoundingClass rt = RoundingClass.ZERO;
if (digit_end < digits.length)
{
auto tie = (f.spec == 'a' || f.spec == 'A') ? '8' : '5';
if (digits[digit_end] >= tie)
{
rt = RoundingClass.UPPER;
if (digits[digit_end] == tie && digits[digit_end + 1 .. $].all!(a => a == '0'))
rt = RoundingClass.FIVE;
}
else
{
rt = RoundingClass.LOWER;
if (digits[digit_end .. $].all!(a => a == '0'))
rt = RoundingClass.ZERO;
}
}
if (round(digits, pos + 1, digit_end, rt, negative,
f.spec == 'a' ? 'f' : (f.spec == 'A' ? 'F' : '9')))
{
pos--;
digit_end--;
}
}
// convert to scientific notation
char[1] int_digit = void;
int_digit[0] = digits[pos + 1];
digits[pos + 1] = '.';
char[4] suffix = void;
if (f.spec == 'e' || f.spec == 'E' || f.spec == 'g' || f.spec == 'G')
{
suffix[0] = (f.spec == 'e' || f.spec == 'g') ? 'e' : 'E';
suffix[1] = '+';
suffix[2] = cast(char) ('0' + (digits.length - pos - 2) / 10);
suffix[3] = cast(char) ('0' + (digits.length - pos - 2) % 10);
}
else
{
if (right == 3)
prefix[0] = prefix[2];
prefix[1] = '0';
prefix[2] = f.spec == 'a' ? 'x' : 'X';
left = right == 3 ? 0 : 1;
right = 3;
suffix[0] = f.spec == 'a' ? 'p' : 'P';
suffix[1] = '+';
suffix[2] = cast(char) ('0' + ((digits.length - pos - 2) * 4) / 10);
suffix[3] = cast(char) ('0' + ((digits.length - pos - 2) * 4) % 10);
}
import std.algorithm.comparison : min;
// remove trailing zeros
if ((f.spec == 'g' || f.spec == 'G') && !f.flHash)
{
digit_end = min(digit_end, digits.length);
while (digit_end > pos + 1 &&
(digits[digit_end - 1] == '0' || digits[digit_end - 1] == '.'))
digit_end--;
}
writeAligned(w, prefix[left .. right], int_digit[0 .. $],
digits[pos + 1 .. min(digit_end, $)],
suffix[0 .. $], fs,
(f.spec == 'g' || f.spec == 'G') ? PrecisionType.allDigits : PrecisionType.fractionalDigits);
}
private uint baseOfSpec(in char spec) @safe pure
{
typeof(return) base =
spec == 'x' || spec == 'X' || spec == 'a' || spec == 'A' ? 16 :
spec == 'o' ? 8 :
spec == 'b' ? 2 :
spec == 's' || spec == 'd' || spec == 'u'
|| spec == 'e' || spec == 'E' || spec == 'f' || spec == 'F'
|| spec == 'g' || spec == 'G' ? 10 :
0;
import std.format : enforceFmt;
enforceFmt(base > 0,
"incompatible format character for integral argument: %" ~ spec);
return base;
}
@safe pure unittest
{
assertCTFEable!(
{
formatTest(byte.min, "-128");
formatTest(byte.max, "127");
formatTest(short.min, "-32768");
formatTest(short.max, "32767");
formatTest(int.min, "-2147483648");
formatTest(int.max, "2147483647");
formatTest(long.min, "-9223372036854775808");
formatTest(long.max, "9223372036854775807");
formatTest(ubyte.min, "0");
formatTest(ubyte.max, "255");
formatTest(ushort.min, "0");
formatTest(ushort.max, "65535");
formatTest(uint.min, "0");
formatTest(uint.max, "4294967295");
formatTest(ulong.min, "0");
formatTest(ulong.max, "18446744073709551615");
});
}
// https://issues.dlang.org/show_bug.cgi?id=18838
@safe pure unittest
{
assert("%12,d".format(0) == " 0");
}
@safe pure unittest
{
import std.exception : collectExceptionMsg;
import std.format : FormatException;
import std.range.primitives : back;
assert(collectExceptionMsg!FormatException(format("%c", 5)).back == 'c');
assertCTFEable!(
{
formatTest(9, "9");
formatTest(10, "10");
});
}
@safe unittest
{
class C1
{
long val;
alias val this;
this(long v){ val = v; }
}
class C2
{
long val;
alias val this;
this(long v){ val = v; }
override string toString() const { return "C"; }
}
() @trusted {
formatTest(new C1(10), "10");
formatTest(new C2(10), "C");
} ();
struct S1
{
long val;
alias val this;
}
struct S2
{
long val;
alias val this;
string toString() const { return "S"; }
}
formatTest(S1(10), "10");
formatTest(S2(10), "S");
}
// https://issues.dlang.org/show_bug.cgi?id=20064
@safe unittest
{
assert(format( "%03,d", 1234) == "1,234");
assert(format( "%04,d", 1234) == "1,234");
assert(format( "%05,d", 1234) == "1,234");
assert(format( "%06,d", 1234) == "01,234");
assert(format( "%07,d", 1234) == "001,234");
assert(format( "%08,d", 1234) == "0,001,234");
assert(format( "%09,d", 1234) == "0,001,234");
assert(format("%010,d", 1234) == "00,001,234");
assert(format("%011,d", 1234) == "000,001,234");
assert(format("%012,d", 1234) == "0,000,001,234");
assert(format("%013,d", 1234) == "0,000,001,234");
assert(format("%014,d", 1234) == "00,000,001,234");
assert(format("%015,d", 1234) == "000,000,001,234");
assert(format("%016,d", 1234) == "0,000,000,001,234");
assert(format("%017,d", 1234) == "0,000,000,001,234");
assert(format( "%03,d", -1234) == "-1,234");
assert(format( "%04,d", -1234) == "-1,234");
assert(format( "%05,d", -1234) == "-1,234");
assert(format( "%06,d", -1234) == "-1,234");
assert(format( "%07,d", -1234) == "-01,234");
assert(format( "%08,d", -1234) == "-001,234");
assert(format( "%09,d", -1234) == "-0,001,234");
assert(format("%010,d", -1234) == "-0,001,234");
assert(format("%011,d", -1234) == "-00,001,234");
assert(format("%012,d", -1234) == "-000,001,234");
assert(format("%013,d", -1234) == "-0,000,001,234");
assert(format("%014,d", -1234) == "-0,000,001,234");
assert(format("%015,d", -1234) == "-00,000,001,234");
assert(format("%016,d", -1234) == "-000,000,001,234");
assert(format("%017,d", -1234) == "-0,000,000,001,234");
}
@safe pure unittest
{
string t1 = format("[%6s] [%-6s]", 123, 123);
assert(t1 == "[ 123] [123 ]");
string t2 = format("[%6s] [%-6s]", -123, -123);
assert(t2 == "[ -123] [-123 ]");
}
@safe pure unittest
{
formatTest(byte.min, "-128");
formatTest(short.min, "-32768");
formatTest(int.min, "-2147483648");
formatTest(long.min, "-9223372036854775808");
}
// https://issues.dlang.org/show_bug.cgi?id=21777
@safe pure unittest
{
assert(format!"%20.5,d"(cast(short) 120) == " 00,120");
assert(format!"%20.5,o"(cast(short) 120) == " 00,170");
assert(format!"%20.5,x"(cast(short) 120) == " 00,078");
assert(format!"%20.5,2d"(cast(short) 120) == " 0,01,20");
assert(format!"%20.5,2o"(cast(short) 120) == " 0,01,70");
assert(format!"%20.5,4d"(cast(short) 120) == " 0,0120");
assert(format!"%20.5,4o"(cast(short) 120) == " 0,0170");
assert(format!"%20.5,4x"(cast(short) 120) == " 0,0078");
assert(format!"%20.5,2x"(3000) == " 0,0b,b8");
assert(format!"%20.5,4d"(3000) == " 0,3000");
assert(format!"%20.5,4o"(3000) == " 0,5670");
assert(format!"%20.5,4x"(3000) == " 0,0bb8");
assert(format!"%20.5,d"(-400) == " -00,400");
assert(format!"%20.30d"(-400) == "-000000000000000000000000000400");
assert(format!"%20.5,4d"(0) == " 0,0000");
assert(format!"%0#.8,2s"(12345) == "00,01,23,45");
assert(format!"%0#.9,3x"(55) == "0x000,000,037");
}
// https://issues.dlang.org/show_bug.cgi?id=21814
@safe pure unittest
{
assert(format("%,0d",1000) == "1000");
}
// https://issues.dlang.org/show_bug.cgi?id=21817
@safe pure unittest
{
assert(format!"%u"(-5) == "4294967291");
}
// https://issues.dlang.org/show_bug.cgi?id=21820
@safe pure unittest
{
assert(format!"%#.0o"(0) == "0");
}
@safe pure unittest
{
assert(format!"%e"(10000) == "1.0000e+04");
assert(format!"%.2e"(10000) == "1.00e+04");
assert(format!"%.10e"(10000) == "1.0000000000e+04");
assert(format!"%e"(9999) == "9.999e+03");
assert(format!"%.2e"(9999) == "1.00e+04");
assert(format!"%.10e"(9999) == "9.9990000000e+03");
assert(format!"%f"(10000) == "10000");
assert(format!"%.2f"(10000) == "10000.00");
assert(format!"%g"(10000) == "10000");
assert(format!"%.2g"(10000) == "1e+04");
assert(format!"%.10g"(10000) == "10000");
assert(format!"%#g"(10000) == "10000.");
assert(format!"%#.2g"(10000) == "1.0e+04");
assert(format!"%#.10g"(10000) == "10000.00000");
assert(format!"%g"(9999) == "9999");
assert(format!"%.2g"(9999) == "1e+04");
assert(format!"%.10g"(9999) == "9999");
assert(format!"%a"(0x10000) == "0x1.0000p+16");
assert(format!"%.2a"(0x10000) == "0x1.00p+16");
assert(format!"%.10a"(0x10000) == "0x1.0000000000p+16");
assert(format!"%a"(0xffff) == "0xf.fffp+12");
assert(format!"%.2a"(0xffff) == "0x1.00p+16");
assert(format!"%.10a"(0xffff) == "0xf.fff0000000p+12");
}
@safe pure unittest
{
assert(format!"%.3e"(ulong.max) == "1.845e+19");
assert(format!"%.3f"(ulong.max) == "18446744073709551615.000");
assert(format!"%.3g"(ulong.max) == "1.84e+19");
assert(format!"%.3a"(ulong.max) == "0x1.000p+64");
assert(format!"%.3e"(long.min) == "-9.223e+18");
assert(format!"%.3f"(long.min) == "-9223372036854775808.000");
assert(format!"%.3g"(long.min) == "-9.22e+18");
assert(format!"%.3a"(long.min) == "-0x8.000p+60");
assert(format!"%e"(0) == "0e+00");
assert(format!"%f"(0) == "0");
assert(format!"%g"(0) == "0");
assert(format!"%a"(0) == "0x0p+00");
}
@safe pure unittest
{
assert(format!"%.0g"(1500) == "2e+03");
}
// https://issues.dlang.org/show_bug.cgi?id=21900#
@safe pure unittest
{
assert(format!"%.1a"(472) == "0x1.ep+08");
}
/*
Floating-point values are formatted like $(REF printf, core, stdc, stdio)
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, const(T) obj,
scope const ref FormatSpec!Char f)
if (is(FloatingPointTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
import std.algorithm.searching : find;
import std.format : enforceFmt;
import std.range.primitives : put;
FloatingPointTypeOf!T val = obj;
const char spec = f.spec;
if (spec == 'r')
{
// raw write, skip all else and write the thing
auto raw = (ref val) @trusted {
return (cast(const char*) &val)[0 .. val.sizeof];
}(val);
if (needToSwapEndianess(f))
{
foreach_reverse (c; raw)
put(w, c);
}
else
{
foreach (c; raw)
put(w, c);
}
return;
}
enforceFmt(find("fgFGaAeEs", spec).length,
"incompatible format character for floating point argument: %" ~ spec);
FormatSpec!Char fs = f; // fs is copy for change its values.
fs.spec = spec == 's' ? 'g' : spec;
static if (is(T == float) || is(T == double)
|| (is(T == real) && (T.mant_dig == double.mant_dig || T.mant_dig == 64)))
{
alias tval = val;
}
else
{
import std.math.traits : isInfinity;
import std.math.operations : nextUp;
// reals that are not supported by printFloat are cast to double.
double tval = val;
// Numbers greater than double.max are converted to double.max:
if (val > double.max && !isInfinity(val))
tval = double.max;
if (val < -double.max && !isInfinity(val))
tval = -double.max;
// Numbers between the smallest representable double subnormal and 0.0
// are converted to the smallest representable double subnormal:
enum doubleLowest = nextUp(0.0);
if (val > 0 && val < doubleLowest)
tval = doubleLowest;
if (val < 0 && val > -doubleLowest)
tval = -doubleLowest;
}
import std.format.internal.floats : printFloat;
printFloat(w, tval, fs);
}
@safe unittest
{
assert(format("%.1f", 1337.7) == "1337.7");
assert(format("%,3.2f", 1331.982) == "1,331.98");
assert(format("%,3.0f", 1303.1982) == "1,303");
assert(format("%#,3.4f", 1303.1982) == "1,303.1982");
assert(format("%#,3.0f", 1303.1982) == "1,303.");
}
@safe pure unittest
{
import std.conv : to;
import std.exception : collectExceptionMsg;
import std.format : FormatException;
import std.meta : AliasSeq;
import std.range.primitives : back;
assert(collectExceptionMsg!FormatException(format("%d", 5.1)).back == 'd');
static foreach (T; AliasSeq!(float, double, real))
{
formatTest(to!( T)(5.5), "5.5");
formatTest(to!( const T)(5.5), "5.5");
formatTest(to!(immutable T)(5.5), "5.5");
formatTest(T.nan, "nan");
}
}
@safe unittest
{
formatTest(2.25, "2.25");
class C1
{
double val;
alias val this;
this(double v){ val = v; }
}
class C2
{
double val;
alias val this;
this(double v){ val = v; }
override string toString() const { return "C"; }
}
() @trusted {
formatTest(new C1(2.25), "2.25");
formatTest(new C2(2.25), "C");
} ();
struct S1
{
double val;
alias val this;
}
struct S2
{
double val;
alias val this;
string toString() const { return "S"; }
}
formatTest(S1(2.25), "2.25");
formatTest(S2(2.25), "S");
}
// https://issues.dlang.org/show_bug.cgi?id=19939
@safe unittest
{
assert(format("^%13,3.2f$", 1.00) == "^ 1.00$");
assert(format("^%13,3.2f$", 10.00) == "^ 10.00$");
assert(format("^%13,3.2f$", 100.00) == "^ 100.00$");
assert(format("^%13,3.2f$", 1_000.00) == "^ 1,000.00$");
assert(format("^%13,3.2f$", 10_000.00) == "^ 10,000.00$");
assert(format("^%13,3.2f$", 100_000.00) == "^ 100,000.00$");
assert(format("^%13,3.2f$", 1_000_000.00) == "^ 1,000,000.00$");
assert(format("^%13,3.2f$", 10_000_000.00) == "^10,000,000.00$");
}
// https://issues.dlang.org/show_bug.cgi?id=20069
@safe unittest
{
assert(format("%012,f", -1234.0) == "-1,234.000000");
assert(format("%013,f", -1234.0) == "-1,234.000000");
assert(format("%014,f", -1234.0) == "-01,234.000000");
assert(format("%011,f", 1234.0) == "1,234.000000");
assert(format("%012,f", 1234.0) == "1,234.000000");
assert(format("%013,f", 1234.0) == "01,234.000000");
assert(format("%014,f", 1234.0) == "001,234.000000");
assert(format("%015,f", 1234.0) == "0,001,234.000000");
assert(format("%016,f", 1234.0) == "0,001,234.000000");
assert(format( "%08,.2f", -1234.0) == "-1,234.00");
assert(format( "%09,.2f", -1234.0) == "-1,234.00");
assert(format("%010,.2f", -1234.0) == "-01,234.00");
assert(format("%011,.2f", -1234.0) == "-001,234.00");
assert(format("%012,.2f", -1234.0) == "-0,001,234.00");
assert(format("%013,.2f", -1234.0) == "-0,001,234.00");
assert(format("%014,.2f", -1234.0) == "-00,001,234.00");
assert(format( "%08,.2f", 1234.0) == "1,234.00");
assert(format( "%09,.2f", 1234.0) == "01,234.00");
assert(format("%010,.2f", 1234.0) == "001,234.00");
assert(format("%011,.2f", 1234.0) == "0,001,234.00");
assert(format("%012,.2f", 1234.0) == "0,001,234.00");
assert(format("%013,.2f", 1234.0) == "00,001,234.00");
assert(format("%014,.2f", 1234.0) == "000,001,234.00");
assert(format("%015,.2f", 1234.0) == "0,000,001,234.00");
assert(format("%016,.2f", 1234.0) == "0,000,001,234.00");
}
@safe unittest
{
import std.math.hardware; // cannot be selective, because FloatingPointControl might not be defined
// std.math's FloatingPointControl isn't available on all target platforms
static if (is(FloatingPointControl))
{
assert(FloatingPointControl.rounding == FloatingPointControl.roundToNearest);
}
// issue 20320
real a = 0.16;
real b = 0.016;
assert(format("%.1f", a) == "0.2");
assert(format("%.2f", b) == "0.02");
double a1 = 0.16;
double b1 = 0.016;
assert(format("%.1f", a1) == "0.2");
assert(format("%.2f", b1) == "0.02");
// issue 9889
assert(format("%.1f", 0.09) == "0.1");
assert(format("%.1f", -0.09) == "-0.1");
assert(format("%.1f", 0.095) == "0.1");
assert(format("%.1f", -0.095) == "-0.1");
assert(format("%.1f", 0.094) == "0.1");
assert(format("%.1f", -0.094) == "-0.1");
}
@safe unittest
{
double a = 123.456;
double b = -123.456;
double c = 123.0;
assert(format("%10.4f",a) == " 123.4560");
assert(format("%-10.4f",a) == "123.4560 ");
assert(format("%+10.4f",a) == " +123.4560");
assert(format("% 10.4f",a) == " 123.4560");
assert(format("%010.4f",a) == "00123.4560");
assert(format("%#10.4f",a) == " 123.4560");
assert(format("%10.4f",b) == " -123.4560");
assert(format("%-10.4f",b) == "-123.4560 ");
assert(format("%+10.4f",b) == " -123.4560");
assert(format("% 10.4f",b) == " -123.4560");
assert(format("%010.4f",b) == "-0123.4560");
assert(format("%#10.4f",b) == " -123.4560");
assert(format("%10.0f",c) == " 123");
assert(format("%-10.0f",c) == "123 ");
assert(format("%+10.0f",c) == " +123");
assert(format("% 10.0f",c) == " 123");
assert(format("%010.0f",c) == "0000000123");
assert(format("%#10.0f",c) == " 123.");
assert(format("%+010.4f",a) == "+0123.4560");
assert(format("% 010.4f",a) == " 0123.4560");
assert(format("% +010.4f",a) == "+0123.4560");
}
@safe unittest
{
string t1 = format("[%6s] [%-6s]", 12.3, 12.3);
assert(t1 == "[ 12.3] [12.3 ]");
string t2 = format("[%6s] [%-6s]", -12.3, -12.3);
assert(t2 == "[ -12.3] [-12.3 ]");
}
// https://issues.dlang.org/show_bug.cgi?id=20396
@safe unittest
{
import std.math.operations : nextUp;
assert(format!"%a"(nextUp(0.0f)) == "0x0.000002p-126");
assert(format!"%a"(nextUp(0.0)) == "0x0.0000000000001p-1022");
}
// https://issues.dlang.org/show_bug.cgi?id=20371
@safe unittest
{
assert(format!"%.1000a"(1.0).length == 1007);
assert(format!"%.600f"(0.1).length == 602);
assert(format!"%.600e"(0.1L).length == 606);
}
@safe unittest
{
import std.math.hardware; // cannot be selective, because FloatingPointControl might not be defined
// std.math's FloatingPointControl isn't available on all target platforms
static if (is(FloatingPointControl))
{
FloatingPointControl fpctrl;
fpctrl.rounding = FloatingPointControl.roundUp;
assert(format!"%.0e"(3.5) == "4e+00");
assert(format!"%.0e"(4.5) == "5e+00");
assert(format!"%.0e"(-3.5) == "-3e+00");
assert(format!"%.0e"(-4.5) == "-4e+00");
fpctrl.rounding = FloatingPointControl.roundDown;
assert(format!"%.0e"(3.5) == "3e+00");
assert(format!"%.0e"(4.5) == "4e+00");
assert(format!"%.0e"(-3.5) == "-4e+00");
assert(format!"%.0e"(-4.5) == "-5e+00");
fpctrl.rounding = FloatingPointControl.roundToZero;
assert(format!"%.0e"(3.5) == "3e+00");
assert(format!"%.0e"(4.5) == "4e+00");
assert(format!"%.0e"(-3.5) == "-3e+00");
assert(format!"%.0e"(-4.5) == "-4e+00");
fpctrl.rounding = FloatingPointControl.roundToNearest;
assert(format!"%.0e"(3.5) == "4e+00");
assert(format!"%.0e"(4.5) == "4e+00");
assert(format!"%.0e"(-3.5) == "-4e+00");
assert(format!"%.0e"(-4.5) == "-4e+00");
}
}
@safe pure unittest
{
static assert(format("%e",1.0) == "1.000000e+00");
static assert(format("%e",-1.234e156) == "-1.234000e+156");
static assert(format("%a",1.0) == "0x1p+0");
static assert(format("%a",-1.234e156) == "-0x1.7024c96ca3ce4p+518");
static assert(format("%f",1.0) == "1.000000");
static assert(format("%f",-1.234e156) ==
"-123399999999999990477495546305353609103201879173427886566531" ~
"0740685826234179310516880117527217443004051984432279880308552" ~
"009640198043032289366552939010719744.000000");
static assert(format("%g",1.0) == "1");
static assert(format("%g",-1.234e156) == "-1.234e+156");
static assert(format("%e",1.0f) == "1.000000e+00");
static assert(format("%e",-1.234e23f) == "-1.234000e+23");
static assert(format("%a",1.0f) == "0x1p+0");
static assert(format("%a",-1.234e23f) == "-0x1.a2187p+76");
static assert(format("%f",1.0f) == "1.000000");
static assert(format("%f",-1.234e23f) == "-123399998884238311030784.000000");
static assert(format("%g",1.0f) == "1");
static assert(format("%g",-1.234e23f) == "-1.234e+23");
}
// https://issues.dlang.org/show_bug.cgi?id=21641
@safe unittest
{
float a = -999999.8125;
assert(format("%#.5g",a) == "-1.0000e+06");
assert(format("%#.6g",a) == "-1.00000e+06");
}
// https://issues.dlang.org/show_bug.cgi?id=8424
@safe pure unittest
{
static assert(format("%s", 0.6f) == "0.6");
static assert(format("%s", 0.6) == "0.6");
static assert(format("%s", 0.6L) == "0.6");
}
// https://issues.dlang.org/show_bug.cgi?id=9297
@safe pure unittest
{
static if (real.mant_dig == 64) // 80 bit reals
{
assert(format("%.25f", 1.6180339887_4989484820_4586834365L) == "1.6180339887498948482072100");
}
}
// https://issues.dlang.org/show_bug.cgi?id=21853
@safe pure unittest
{
import std.math.exponential : log2;
// log2 is broken for x87-reals on some computers in CTFE
// the following test excludes these computers from the test
// (issue 21757)
enum test = cast(int) log2(3.05e2312L);
static if (real.mant_dig == 64 && test == 7681) // 80 bit reals
{
static assert(format!"%e"(real.max) == "1.189731e+4932");
}
}
// https://issues.dlang.org/show_bug.cgi?id=21842
@safe pure unittest
{
assert(format!"%-+05,g"(1.0) == "+1 ");
}
// https://issues.dlang.org/show_bug.cgi?id=20536
@safe pure unittest
{
real r = .00000095367431640625L;
assert(format("%a", r) == "0x1p-20");
}
// https://issues.dlang.org/show_bug.cgi?id=21840
@safe pure unittest
{
assert(format!"% 0,e"(0.0) == " 0.000000e+00");
}
// https://issues.dlang.org/show_bug.cgi?id=21841
@safe pure unittest
{
assert(format!"%0.0,e"(0.0) == "0e+00");
}
// https://issues.dlang.org/show_bug.cgi?id=21836
@safe pure unittest
{
assert(format!"%-5,1g"(0.0) == "0 ");
}
// https://issues.dlang.org/show_bug.cgi?id=21838
@safe pure unittest
{
assert(format!"%#,a"(0.0) == "0x0.p+0");
}
/*
Formatting a `creal` is deprecated but still kept around for a while.
*/
deprecated("Use of complex types is deprecated. Use std.complex")
void formatValueImpl(Writer, T, Char)(auto ref Writer w, const(T) obj, scope const ref FormatSpec!Char f)
if (is(immutable T : immutable creal) && !is(T == enum) && !hasToString!(T, Char))
{
import std.range.primitives : put;
immutable creal val = obj;
formatValueImpl(w, val.re, f);
if (val.im >= 0)
{
put(w, '+');
}
formatValueImpl(w, val.im, f);
put(w, 'i');
}
/*
Formatting an `ireal` is deprecated but still kept around for a while.
*/
deprecated("Use of imaginary types is deprecated. Use std.complex")
void formatValueImpl(Writer, T, Char)(auto ref Writer w, const(T) obj, scope const ref FormatSpec!Char f)
if (is(immutable T : immutable ireal) && !is(T == enum) && !hasToString!(T, Char))
{
import std.range.primitives : put;
immutable ireal val = obj;
formatValueImpl(w, val.im, f);
put(w, 'i');
}
/*
Individual characters are formatted as Unicode characters with `%s`
and as integers with integral-specific format specs
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, const(T) obj, scope const ref FormatSpec!Char f)
if (is(CharTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
import std.meta : AliasSeq;
CharTypeOf!T[1] val = obj;
if (f.spec == 's' || f.spec == 'c')
writeAligned(w, val[], f);
else
{
alias U = AliasSeq!(ubyte, ushort, uint)[CharTypeOf!T.sizeof/2];
formatValueImpl(w, cast(U) val[0], f);
}
}
@safe pure unittest
{
assertCTFEable!(
{
formatTest('c', "c");
});
}
@safe unittest
{
class C1
{
char val;
alias val this;
this(char v){ val = v; }
}
class C2
{
char val;
alias val this;
this(char v){ val = v; }
override string toString() const { return "C"; }
}
() @trusted {
formatTest(new C1('c'), "c");
formatTest(new C2('c'), "C");
} ();
struct S1
{
char val;
alias val this;
}
struct S2
{
char val;
alias val this;
string toString() const { return "S"; }
}
formatTest(S1('c'), "c");
formatTest(S2('c'), "S");
}
@safe unittest
{
//Little Endian
formatTest("%-r", cast( char)'c', ['c' ]);
formatTest("%-r", cast(wchar)'c', ['c', 0 ]);
formatTest("%-r", cast(dchar)'c', ['c', 0, 0, 0]);
formatTest("%-r", '本', ['\x2c', '\x67'] );
//Big Endian
formatTest("%+r", cast( char)'c', [ 'c']);
formatTest("%+r", cast(wchar)'c', [0, 'c']);
formatTest("%+r", cast(dchar)'c', [0, 0, 0, 'c']);
formatTest("%+r", '本', ['\x67', '\x2c']);
}
@safe pure unittest
{
string t1 = format("[%6s] [%-6s]", 'A', 'A');
assert(t1 == "[ A] [A ]");
string t2 = format("[%6s] [%-6s]", '本', '本');
assert(t2 == "[ 本] [本 ]");
}
/*
Strings are formatted like $(REF printf, core, stdc, stdio)
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, scope const(T) obj,
scope const ref FormatSpec!Char f)
if (is(StringTypeOf!T) && !is(StaticArrayTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
Unqual!(const(StringTypeOf!T)) val = obj; // for `alias this`, see bug5371
formatRange(w, val, f);
}
@safe unittest
{
formatTest("abc", "abc");
}
@safe pure unittest
{
import std.exception : collectExceptionMsg;
import std.range.primitives : back;
assert(collectExceptionMsg(format("%d", "hi")).back == 'd');
}
@safe unittest
{
// Test for bug 5371 for classes
class C1
{
const string var;
alias var this;
this(string s){ var = s; }
}
class C2
{
string var;
alias var this;
this(string s){ var = s; }
}
() @trusted {
formatTest(new C1("c1"), "c1");
formatTest(new C2("c2"), "c2");
} ();
// Test for bug 5371 for structs
struct S1
{
const string var;
alias var this;
}
struct S2
{
string var;
alias var this;
}
formatTest(S1("s1"), "s1");
formatTest(S2("s2"), "s2");
}
@safe unittest
{
class C3
{
string val;
alias val this;
this(string s){ val = s; }
override string toString() const { return "C"; }
}
() @trusted { formatTest(new C3("c3"), "C"); } ();
struct S3
{
string val; alias val this;
string toString() const { return "S"; }
}
formatTest(S3("s3"), "S");
}
@safe pure unittest
{
//Little Endian
formatTest("%-r", "ab"c, ['a' , 'b' ]);
formatTest("%-r", "ab"w, ['a', 0 , 'b', 0 ]);
formatTest("%-r", "ab"d, ['a', 0, 0, 0, 'b', 0, 0, 0]);
formatTest("%-r", "日本語"c, ['\xe6', '\x97', '\xa5', '\xe6', '\x9c', '\xac',
'\xe8', '\xaa', '\x9e']);
formatTest("%-r", "日本語"w, ['\xe5', '\x65', '\x2c', '\x67', '\x9e', '\x8a']);
formatTest("%-r", "日本語"d, ['\xe5', '\x65', '\x00', '\x00', '\x2c', '\x67',
'\x00', '\x00', '\x9e', '\x8a', '\x00', '\x00']);
//Big Endian
formatTest("%+r", "ab"c, [ 'a', 'b']);
formatTest("%+r", "ab"w, [ 0, 'a', 0, 'b']);
formatTest("%+r", "ab"d, [0, 0, 0, 'a', 0, 0, 0, 'b']);
formatTest("%+r", "日本語"c, ['\xe6', '\x97', '\xa5', '\xe6', '\x9c', '\xac',
'\xe8', '\xaa', '\x9e']);
formatTest("%+r", "日本語"w, ['\x65', '\xe5', '\x67', '\x2c', '\x8a', '\x9e']);
formatTest("%+r", "日本語"d, ['\x00', '\x00', '\x65', '\xe5', '\x00', '\x00',
'\x67', '\x2c', '\x00', '\x00', '\x8a', '\x9e']);
}
@safe pure unittest
{
string t1 = format("[%6s] [%-6s]", "AB", "AB");
assert(t1 == "[ AB] [AB ]");
string t2 = format("[%6s] [%-6s]", "本Ä", "本Ä");
assert(t2 == "[ 本Ä] [本Ä ]");
}
// https://issues.dlang.org/show_bug.cgi?id=6640
@safe unittest
{
import std.range.primitives : front, popFront;
struct Range
{
@safe:
string value;
@property bool empty() const { return !value.length; }
@property dchar front() const { return value.front; }
void popFront() { value.popFront(); }
@property size_t length() const { return value.length; }
}
immutable table =
[
["[%s]", "[string]"],
["[%10s]", "[ string]"],
["[%-10s]", "[string ]"],
["[%(%02x %)]", "[73 74 72 69 6e 67]"],
["[%(%c %)]", "[s t r i n g]"],
];
foreach (e; table)
{
formatTest(e[0], "string", e[1]);
formatTest(e[0], Range("string"), e[1]);
}
}
@safe unittest
{
import std.meta : AliasSeq;
// string literal from valid UTF sequence is encoding free.
static foreach (StrType; AliasSeq!(string, wstring, dstring))
{
// Valid and printable (ASCII)
formatTest([cast(StrType)"hello"],
`["hello"]`);
// 1 character escape sequences (' is not escaped in strings)
formatTest([cast(StrType)"\"'\0\\\a\b\f\n\r\t\v"],
`["\"'\0\\\a\b\f\n\r\t\v"]`);
// 1 character optional escape sequences
formatTest([cast(StrType)"\'\?"],
`["'?"]`);
// Valid and non-printable code point (<= U+FF)
formatTest([cast(StrType)"\x10\x1F\x20test"],
`["\x10\x1F test"]`);
// Valid and non-printable code point (<= U+FFFF)
formatTest([cast(StrType)"\u200B..\u200F"],
`["\u200B..\u200F"]`);
// Valid and non-printable code point (<= U+10FFFF)
formatTest([cast(StrType)"\U000E0020..\U000E007F"],
`["\U000E0020..\U000E007F"]`);
}
// invalid UTF sequence needs hex-string literal postfix (c/w/d)
() @trusted
{
// U+FFFF with UTF-8 (Invalid code point for interchange)
formatTest([cast(string)[0xEF, 0xBF, 0xBF]],
`[[cast(char) 0xEF, cast(char) 0xBF, cast(char) 0xBF]]`);
// U+FFFF with UTF-16 (Invalid code point for interchange)
formatTest([cast(wstring)[0xFFFF]],
`[[cast(wchar) 0xFFFF]]`);
// U+FFFF with UTF-32 (Invalid code point for interchange)
formatTest([cast(dstring)[0xFFFF]],
`[[cast(dchar) 0xFFFF]]`);
} ();
}
/*
Static-size arrays are formatted as dynamic arrays.
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, auto ref const(T) obj,
scope const ref FormatSpec!Char f)
if (is(StaticArrayTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
formatValueImpl(w, obj[], f);
}
// Test for https://issues.dlang.org/show_bug.cgi?id=8310
@safe unittest
{
import std.array : appender;
import std.format : formatValue;
FormatSpec!char f;
auto w = appender!string();
char[2] two = ['a', 'b'];
formatValue(w, two, f);
char[2] getTwo() { return two; }
formatValue(w, getTwo(), f);
}
// https://issues.dlang.org/show_bug.cgi?id=18205
@safe pure unittest
{
assert("|%8s|".format("abc") == "| abc|");
assert("|%8s|".format("αβγ") == "| αβγ|");
assert("|%8s|".format(" ") == "| |");
assert("|%8s|".format("été"d) == "| été|");
assert("|%8s|".format("été 2018"w) == "|été 2018|");
assert("%2s".format("e\u0301"w) == " e\u0301");
assert("%2s".format("a\u0310\u0337"d) == " a\u0310\u0337");
}
/*
Dynamic arrays are formatted as input ranges.
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, T obj, scope const ref FormatSpec!Char f)
if (is(DynamicArrayTypeOf!T) && !is(StringTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
static if (is(immutable(ArrayTypeOf!T) == immutable(void[])))
{
formatValueImpl(w, cast(const ubyte[]) obj, f);
}
else static if (!isInputRange!T)
{
alias U = Unqual!(ArrayTypeOf!T);
static assert(isInputRange!U, U.stringof ~ " must be an InputRange");
U val = obj;
formatValueImpl(w, val, f);
}
else
{
formatRange(w, obj, f);
}
}
// https://issues.dlang.org/show_bug.cgi?id=20848
@safe unittest
{
class C
{
immutable(void)[] data;
}
import std.typecons : Nullable;
Nullable!C c;
}
// alias this, input range I/F, and toString()
@safe unittest
{
struct S(int flags)
{
int[] arr;
static if (flags & 1)
alias arr this;
static if (flags & 2)
{
@property bool empty() const { return arr.length == 0; }
@property int front() const { return arr[0] * 2; }
void popFront() { arr = arr[1 .. $]; }
}
static if (flags & 4)
string toString() const { return "S"; }
}
formatTest(S!0b000([0, 1, 2]), "S!0([0, 1, 2])");
formatTest(S!0b001([0, 1, 2]), "[0, 1, 2]"); // Test for bug 7628
formatTest(S!0b010([0, 1, 2]), "[0, 2, 4]");
formatTest(S!0b011([0, 1, 2]), "[0, 2, 4]");
formatTest(S!0b100([0, 1, 2]), "S");
formatTest(S!0b101([0, 1, 2]), "S"); // Test for bug 7628
formatTest(S!0b110([0, 1, 2]), "S");
formatTest(S!0b111([0, 1, 2]), "S");
class C(uint flags)
{
int[] arr;
static if (flags & 1)
alias arr this;
this(int[] a) { arr = a; }
static if (flags & 2)
{
@property bool empty() const { return arr.length == 0; }
@property int front() const { return arr[0] * 2; }
void popFront() { arr = arr[1 .. $]; }
}
static if (flags & 4)
override string toString() const { return "C"; }
}
() @trusted {
formatTest(new C!0b000([0, 1, 2]), (new C!0b000([])).toString());
formatTest(new C!0b001([0, 1, 2]), "[0, 1, 2]"); // Test for bug 7628
formatTest(new C!0b010([0, 1, 2]), "[0, 2, 4]");
formatTest(new C!0b011([0, 1, 2]), "[0, 2, 4]");
formatTest(new C!0b100([0, 1, 2]), "C");
formatTest(new C!0b101([0, 1, 2]), "C"); // Test for bug 7628
formatTest(new C!0b110([0, 1, 2]), "C");
formatTest(new C!0b111([0, 1, 2]), "C");
} ();
}
@safe unittest
{
// void[]
void[] val0;
formatTest(val0, "[]");
void[] val = cast(void[]) cast(ubyte[])[1, 2, 3];
formatTest(val, "[1, 2, 3]");
void[0] sval0 = [];
formatTest(sval0, "[]");
void[3] sval = () @trusted { return cast(void[3]) cast(ubyte[3])[1, 2, 3]; } ();
formatTest(sval, "[1, 2, 3]");
}
@safe unittest
{
// const(T[]) -> const(T)[]
const short[] a = [1, 2, 3];
formatTest(a, "[1, 2, 3]");
struct S
{
const(int[]) arr;
alias arr this;
}
auto s = S([1,2,3]);
formatTest(s, "[1, 2, 3]");
}
@safe unittest
{
// nested range formatting with array of string
formatTest("%({%(%02x %)}%| %)", ["test", "msg"],
`{74 65 73 74} {6d 73 67}`);
}
@safe unittest
{
// stop auto escaping inside range formatting
auto arr = ["hello", "world"];
formatTest("%(%s, %)", arr, `"hello", "world"`);
formatTest("%-(%s, %)", arr, `hello, world`);
auto aa1 = [1:"hello", 2:"world"];
formatTest("%(%s:%s, %)", aa1, [`1:"hello", 2:"world"`, `2:"world", 1:"hello"`]);
formatTest("%-(%s:%s, %)", aa1, [`1:hello, 2:world`, `2:world, 1:hello`]);
auto aa2 = [1:["ab", "cd"], 2:["ef", "gh"]];
formatTest("%-(%s:%s, %)", aa2, [`1:["ab", "cd"], 2:["ef", "gh"]`, `2:["ef", "gh"], 1:["ab", "cd"]`]);
formatTest("%-(%s:%(%s%), %)", aa2, [`1:"ab""cd", 2:"ef""gh"`, `2:"ef""gh", 1:"ab""cd"`]);
formatTest("%-(%s:%-(%s%)%|, %)", aa2, [`1:abcd, 2:efgh`, `2:efgh, 1:abcd`]);
}
// https://issues.dlang.org/show_bug.cgi?id=18778
@safe pure unittest
{
assert(format("%-(%1$s - %1$s, %)", ["A", "B", "C"]) == "A - A, B - B, C - C");
}
@safe pure unittest
{
int[] a = [ 1, 3, 2 ];
formatTest("testing %(%s & %) embedded", a,
"testing 1 & 3 & 2 embedded");
formatTest("testing %((%s) %)) wyda3", a,
"testing (1) (3) (2) wyda3");
int[0] empt = [];
formatTest("(%s)", empt, "([])");
}
// input range formatting
private void formatRange(Writer, T, Char)(ref Writer w, ref T val, scope const ref FormatSpec!Char f)
if (isInputRange!T)
{
import std.conv : text;
import std.format : FormatException, formatValue, NoOpSink;
import std.range.primitives : ElementType, empty, front, hasLength,
walkLength, isForwardRange, isInfinite, popFront, put;
// in this mode, we just want to do a representative print to discover
// if the format spec is valid
enum formatTestMode = is(Writer == NoOpSink);
// Formatting character ranges like string
if (f.spec == 's')
{
alias E = ElementType!T;
static if (!is(E == enum) && is(CharTypeOf!E))
{
static if (is(StringTypeOf!T))
writeAligned(w, val[0 .. f.precision < $ ? f.precision : $], f);
else
{
if (!f.flDash)
{
static if (hasLength!T)
{
// right align
auto len = val.length;
}
else static if (isForwardRange!T && !isInfinite!T)
{
auto len = walkLength(val.save);
}
else
{
import std.format : enforceFmt;
enforceFmt(f.width == 0, "Cannot right-align a range without length");
size_t len = 0;
}
if (f.precision != f.UNSPECIFIED && len > f.precision)
len = f.precision;
if (f.width > len)
foreach (i ; 0 .. f.width - len)
put(w, ' ');
if (f.precision == f.UNSPECIFIED)
put(w, val);
else
{
size_t printed = 0;
for (; !val.empty && printed < f.precision; val.popFront(), ++printed)
put(w, val.front);
}
}
else
{
size_t printed = void;
// left align
if (f.precision == f.UNSPECIFIED)
{
static if (hasLength!T)
{
printed = val.length;
put(w, val);
}
else
{
printed = 0;
for (; !val.empty; val.popFront(), ++printed)
{
put(w, val.front);
static if (formatTestMode) break; // one is enough to test
}
}
}
else
{
printed = 0;
for (; !val.empty && printed < f.precision; val.popFront(), ++printed)
put(w, val.front);
}
if (f.width > printed)
foreach (i ; 0 .. f.width - printed)
put(w, ' ');
}
}
}
else
{
put(w, f.seqBefore);
if (!val.empty)
{
formatElement(w, val.front, f);
val.popFront();
for (size_t i; !val.empty; val.popFront(), ++i)
{
put(w, f.seqSeparator);
formatElement(w, val.front, f);
static if (formatTestMode) break; // one is enough to test
}
}
static if (!isInfinite!T) put(w, f.seqAfter);
}
}
else if (f.spec == 'r')
{
static if (is(DynamicArrayTypeOf!T))
{
alias ARR = DynamicArrayTypeOf!T;
scope a = cast(ARR) val;
foreach (e ; a)
{
formatValue(w, e, f);
static if (formatTestMode) break; // one is enough to test
}
}
else
{
for (size_t i; !val.empty; val.popFront(), ++i)
{
formatValue(w, val.front, f);
static if (formatTestMode) break; // one is enough to test
}
}
}
else if (f.spec == '(')
{
if (val.empty)
return;
// Nested specifier is to be used
for (;;)
{
auto fmt = FormatSpec!Char(f.nested);
w: while (true)
{
immutable r = fmt.writeUpToNextSpec(w);
// There was no format specifier, so break
if (!r)
break;
if (f.flDash)
formatValue(w, val.front, fmt);
else
formatElement(w, val.front, fmt);
// Check if there will be a format specifier farther on in the
// string. If so, continue the loop, otherwise break. This
// prevents extra copies of the `sep` from showing up.
foreach (size_t i; 0 .. fmt.trailing.length)
if (fmt.trailing[i] == '%')
continue w;
break w;
}
static if (formatTestMode)
{
break; // one is enough to test
}
else
{
if (f.sep !is null)
{
put(w, fmt.trailing);
val.popFront();
if (val.empty)
break;
put(w, f.sep);
}
else
{
val.popFront();
if (val.empty)
break;
put(w, fmt.trailing);
}
}
}
}
else
throw new FormatException(text("Incorrect format specifier for range: %", f.spec));
}
// https://issues.dlang.org/show_bug.cgi?id=20218
@safe pure unittest
{
void notCalled()
{
import std.range : repeat;
auto value = 1.repeat;
// test that range is not evaluated to completion at compiletime
format!"%s"(value);
}
}
// character formatting with ecaping
void formatChar(Writer)(ref Writer w, in dchar c, in char quote)
{
import std.format : formattedWrite;
import std.range.primitives : put;
import std.uni : isGraphical;
string fmt;
if (isGraphical(c))
{
if (c == quote || c == '\\')
put(w, '\\');
put(w, c);
return;
}
else if (c <= 0xFF)
{
if (c < 0x20)
{
foreach (i, k; "\n\r\t\a\b\f\v\0")
{
if (c == k)
{
put(w, '\\');
put(w, "nrtabfv0"[i]);
return;
}
}
}
fmt = "\\x%02X";
}
else if (c <= 0xFFFF)
fmt = "\\u%04X";
else
fmt = "\\U%08X";
formattedWrite(w, fmt, cast(uint) c);
}
/*
Associative arrays are formatted by using `':'` and $(D ", ") as
separators, and enclosed by `'['` and `']'`.
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, const(T) obj, scope const ref FormatSpec!Char f)
if (is(AssocArrayTypeOf!T) && !is(T == enum) && !hasToString!(T, Char))
{
import std.format : enforceFmt, formatValue;
import std.range.primitives : put;
AssocArrayTypeOf!(const(T)) val = obj;
const spec = f.spec;
enforceFmt(spec == 's' || spec == '(',
"incompatible format character for associative array argument: %" ~ spec);
enum const(Char)[] defSpec = "%s" ~ f.keySeparator ~ "%s" ~ f.seqSeparator;
auto fmtSpec = spec == '(' ? f.nested : defSpec;
auto key_first = true;
// testing correct nested format spec
import std.format : NoOpSink;
auto noop = NoOpSink();
auto test = FormatSpec!Char(fmtSpec);
enforceFmt(test.writeUpToNextSpec(noop),
"nested format string for associative array contains no format specifier");
enforceFmt(test.indexStart <= 2,
"positional parameter in nested format string for associative array may only be 1 or 2");
if (test.indexStart == 2)
key_first = false;
enforceFmt(test.writeUpToNextSpec(noop),
"nested format string for associative array contains only one format specifier");
enforceFmt(test.indexStart <= 2,
"positional parameter in nested format string for associative array may only be 1 or 2");
enforceFmt(test.indexStart == 0 || ((test.indexStart == 2) == key_first),
"wrong combination of positional parameters in nested format string");
enforceFmt(!test.writeUpToNextSpec(noop),
"nested format string for associative array contains more than two format specifiers");
size_t i = 0;
immutable end = val.length;
if (spec == 's')
put(w, f.seqBefore);
foreach (k, ref v; val)
{
auto fmt = FormatSpec!Char(fmtSpec);
foreach (pos; 1 .. 3)
{
fmt.writeUpToNextSpec(w);
if (key_first == (pos == 1))
{
if (f.flDash)
formatValue(w, k, fmt);
else
formatElement(w, k, fmt);
}
else
{
if (f.flDash)
formatValue(w, v, fmt);
else
formatElement(w, v, fmt);
}
}
if (f.sep !is null)
{
fmt.writeUpToNextSpec(w);
if (++i != end)
put(w, f.sep);
}
else
{
if (++i != end)
fmt.writeUpToNextSpec(w);
}
}
if (spec == 's')
put(w, f.seqAfter);
}
@safe unittest
{
import std.exception : collectExceptionMsg;
import std.format : FormatException;
import std.range.primitives : back;
assert(collectExceptionMsg!FormatException(format("%d", [0:1])).back == 'd');
int[string] aa0;
formatTest(aa0, `[]`);
// elements escaping
formatTest(["aaa":1, "bbb":2],
[`["aaa":1, "bbb":2]`, `["bbb":2, "aaa":1]`]);
formatTest(['c':"str"],
`['c':"str"]`);
formatTest(['"':"\"", '\'':"'"],
[`['"':"\"", '\'':"'"]`, `['\'':"'", '"':"\""]`]);
// range formatting for AA
auto aa3 = [1:"hello", 2:"world"];
// escape
formatTest("{%(%s:%s $ %)}", aa3,
[`{1:"hello" $ 2:"world"}`, `{2:"world" $ 1:"hello"}`]);
// use range formatting for key and value, and use %|
formatTest("{%([%04d->%(%c.%)]%| $ %)}", aa3,
[`{[0001->h.e.l.l.o] $ [0002->w.o.r.l.d]}`,
`{[0002->w.o.r.l.d] $ [0001->h.e.l.l.o]}`]);
// https://issues.dlang.org/show_bug.cgi?id=12135
formatTest("%(%s:<%s>%|,%)", [1:2], "1:<2>");
formatTest("%(%s:<%s>%|%)" , [1:2], "1:<2>");
}
@safe unittest
{
class C1
{
int[char] val;
alias val this;
this(int[char] v){ val = v; }
}
class C2
{
int[char] val;
alias val this;
this(int[char] v){ val = v; }
override string toString() const { return "C"; }
}
() @trusted {
formatTest(new C1(['c':1, 'd':2]), [`['c':1, 'd':2]`, `['d':2, 'c':1]`]);
formatTest(new C2(['c':1, 'd':2]), "C");
} ();
struct S1
{
int[char] val;
alias val this;
}
struct S2
{
int[char] val;
alias val this;
string toString() const { return "S"; }
}
formatTest(S1(['c':1, 'd':2]), [`['c':1, 'd':2]`, `['d':2, 'c':1]`]);
formatTest(S2(['c':1, 'd':2]), "S");
}
// https://issues.dlang.org/show_bug.cgi?id=21875
@safe unittest
{
import std.exception : assertThrown;
import std.format : FormatException;
auto aa = [ 1 : "x", 2 : "y", 3 : "z" ];
assertThrown!FormatException(format("%(%)", aa));
assertThrown!FormatException(format("%(%s%)", aa));
assertThrown!FormatException(format("%(%s%s%s%)", aa));
}
@safe unittest
{
import std.exception : assertThrown;
import std.format : FormatException;
auto aa = [ 1 : "x", 2 : "y", 3 : "z" ];
assertThrown!FormatException(format("%(%3$s%s%)", aa));
assertThrown!FormatException(format("%(%s%3$s%)", aa));
assertThrown!FormatException(format("%(%1$s%1$s%)", aa));
assertThrown!FormatException(format("%(%2$s%2$s%)", aa));
assertThrown!FormatException(format("%(%s%1$s%)", aa));
}
// https://issues.dlang.org/show_bug.cgi?id=21808
@safe unittest
{
auto spelled = [ 1 : "one" ];
assert(format("%-(%2$s (%1$s)%|, %)", spelled) == "one (1)");
spelled[2] = "two";
auto result = format("%-(%2$s (%1$s)%|, %)", spelled);
assert(result == "one (1), two (2)" || result == "two (2), one (1)");
}
enum HasToStringResult
{
none,
hasSomeToString,
inCharSink,
inCharSinkFormatString,
inCharSinkFormatSpec,
constCharSink,
constCharSinkFormatString,
constCharSinkFormatSpec,
customPutWriter,
customPutWriterFormatSpec,
}
private enum hasPreviewIn = !is(typeof(mixin(q{(in ref int a) => a})));
template hasToString(T, Char)
{
static if (isPointer!T)
{
// X* does not have toString, even if X is aggregate type has toString.
enum hasToString = HasToStringResult.none;
}
else static if (is(typeof(
(T val) {
const FormatSpec!Char f;
static struct S {void put(scope Char s){}}
S s;
val.toString(s, f);
static assert(!__traits(compiles, val.toString(s, FormatSpec!Char())),
"force toString to take parameters by ref");
static assert(!__traits(compiles, val.toString(S(), f)),
"force toString to take parameters by ref");
})))
{
enum hasToString = HasToStringResult.customPutWriterFormatSpec;
}
else static if (is(typeof(
(T val) {
static struct S {void put(scope Char s){}}
S s;
val.toString(s);
static assert(!__traits(compiles, val.toString(S())),
"force toString to take parameters by ref");
})))
{
enum hasToString = HasToStringResult.customPutWriter;
}
else static if (is(typeof((T val) { FormatSpec!Char f; val.toString((scope const(char)[] s){}, f); })))
{
enum hasToString = HasToStringResult.constCharSinkFormatSpec;
}
else static if (is(typeof((T val) { val.toString((scope const(char)[] s){}, "%s"); })))
{
enum hasToString = HasToStringResult.constCharSinkFormatString;
}
else static if (is(typeof((T val) { val.toString((scope const(char)[] s){}); })))
{
enum hasToString = HasToStringResult.constCharSink;
}
else static if (hasPreviewIn &&
is(typeof((T val) { FormatSpec!Char f; val.toString((in char[] s){}, f); })))
{
enum hasToString = HasToStringResult.inCharSinkFormatSpec;
}
else static if (hasPreviewIn &&
is(typeof((T val) { val.toString((in char[] s){}, "%s"); })))
{
enum hasToString = HasToStringResult.inCharSinkFormatString;
}
else static if (hasPreviewIn &&
is(typeof((T val) { val.toString((in char[] s){}); })))
{
enum hasToString = HasToStringResult.inCharSink;
}
else static if (is(ReturnType!((T val) { return val.toString(); }) S) && isSomeString!S)
{
enum hasToString = HasToStringResult.hasSomeToString;
}
else
{
enum hasToString = HasToStringResult.none;
}
}
@safe unittest
{
import std.range.primitives : isOutputRange;
static struct A
{
void toString(Writer)(ref Writer w)
if (isOutputRange!(Writer, string))
{}
}
static struct B
{
void toString(scope void delegate(scope const(char)[]) sink, scope FormatSpec!char fmt) {}
}
static struct C
{
void toString(scope void delegate(scope const(char)[]) sink, string fmt) {}
}
static struct D
{
void toString(scope void delegate(scope const(char)[]) sink) {}
}
static struct E
{
string toString() {return "";}
}
static struct F
{
void toString(Writer)(ref Writer w, scope const ref FormatSpec!char fmt)
if (isOutputRange!(Writer, string))
{}
}
static struct G
{
string toString() {return "";}
void toString(Writer)(ref Writer w) if (isOutputRange!(Writer, string)) {}
}
static struct H
{
string toString() {return "";}
void toString(Writer)(ref Writer w, scope const ref FormatSpec!char fmt)
if (isOutputRange!(Writer, string))
{}
}
static struct I
{
void toString(Writer)(ref Writer w) if (isOutputRange!(Writer, string)) {}
void toString(Writer)(ref Writer w, scope const ref FormatSpec!char fmt)
if (isOutputRange!(Writer, string))
{}
}
static struct J
{
string toString() {return "";}
void toString(Writer)(ref Writer w, scope ref FormatSpec!char fmt)
if (isOutputRange!(Writer, string))
{}
}
static struct K
{
void toString(Writer)(Writer w, scope const ref FormatSpec!char fmt)
if (isOutputRange!(Writer, string))
{}
}
static struct L
{
void toString(Writer)(ref Writer w, scope const FormatSpec!char fmt)
if (isOutputRange!(Writer, string))
{}
}
static struct M
{
void toString(scope void delegate(in char[]) sink, in FormatSpec!char fmt) {}
}
static struct N
{
void toString(scope void delegate(in char[]) sink, string fmt) {}
}
static struct O
{
void toString(scope void delegate(in char[]) sink) {}
}
with(HasToStringResult)
{
static assert(hasToString!(A, char) == customPutWriter);
static assert(hasToString!(B, char) == constCharSinkFormatSpec);
static assert(hasToString!(C, char) == constCharSinkFormatString);
static assert(hasToString!(D, char) == constCharSink);
static assert(hasToString!(E, char) == hasSomeToString);
static assert(hasToString!(F, char) == customPutWriterFormatSpec);
static assert(hasToString!(G, char) == customPutWriter);
static assert(hasToString!(H, char) == customPutWriterFormatSpec);
static assert(hasToString!(I, char) == customPutWriterFormatSpec);
static assert(hasToString!(J, char) == hasSomeToString);
static assert(hasToString!(K, char) == constCharSinkFormatSpec);
static assert(hasToString!(L, char) == none);
static if (hasPreviewIn)
{
static assert(hasToString!(M, char) == inCharSinkFormatSpec);
static assert(hasToString!(N, char) == inCharSinkFormatString);
static assert(hasToString!(O, char) == inCharSink);
}
}
}
// const toString methods
@safe unittest
{
import std.range.primitives : isOutputRange;
static struct A
{
void toString(Writer)(ref Writer w) const
if (isOutputRange!(Writer, string))
{}
}
static struct B
{
void toString(scope void delegate(scope const(char)[]) sink, scope FormatSpec!char fmt) const {}
}
static struct C
{
void toString(scope void delegate(scope const(char)[]) sink, string fmt) const {}
}
static struct D
{
void toString(scope void delegate(scope const(char)[]) sink) const {}
}
static struct E
{
string toString() const {return "";}
}
static struct F
{
void toString(Writer)(ref Writer w, scope const ref FormatSpec!char fmt) const
if (isOutputRange!(Writer, string))
{}
}
static struct G
{
string toString() const {return "";}
void toString(Writer)(ref Writer w) const if (isOutputRange!(Writer, string)) {}
}
static struct H
{
string toString() const {return "";}
void toString(Writer)(ref Writer w, scope const ref FormatSpec!char fmt) const
if (isOutputRange!(Writer, string))
{}
}
static struct I
{
void toString(Writer)(ref Writer w) const if (isOutputRange!(Writer, string)) {}
void toString(Writer)(ref Writer w, scope const ref FormatSpec!char fmt) const
if (isOutputRange!(Writer, string))
{}
}
static struct J
{
string toString() const {return "";}
void toString(Writer)(ref Writer w, scope ref FormatSpec!char fmt) const
if (isOutputRange!(Writer, string))
{}
}
static struct K
{
void toString(Writer)(Writer w, scope const ref FormatSpec!char fmt) const
if (isOutputRange!(Writer, string))
{}
}
static struct L
{
void toString(Writer)(ref Writer w, scope const FormatSpec!char fmt) const
if (isOutputRange!(Writer, string))
{}
}
static struct M
{
void toString(scope void delegate(in char[]) sink, in FormatSpec!char fmt) const {}
}
static struct N
{
void toString(scope void delegate(in char[]) sink, string fmt) const {}
}
static struct O
{
void toString(scope void delegate(in char[]) sink) const {}
}
with(HasToStringResult)
{
static assert(hasToString!(A, char) == customPutWriter);
static assert(hasToString!(B, char) == constCharSinkFormatSpec);
static assert(hasToString!(C, char) == constCharSinkFormatString);
static assert(hasToString!(D, char) == constCharSink);
static assert(hasToString!(E, char) == hasSomeToString);
static assert(hasToString!(F, char) == customPutWriterFormatSpec);
static assert(hasToString!(G, char) == customPutWriter);
static assert(hasToString!(H, char) == customPutWriterFormatSpec);
static assert(hasToString!(I, char) == customPutWriterFormatSpec);
static assert(hasToString!(J, char) == hasSomeToString);
static assert(hasToString!(K, char) == constCharSinkFormatSpec);
static assert(hasToString!(L, char) == none);
static if (hasPreviewIn)
{
static assert(hasToString!(M, char) == inCharSinkFormatSpec);
static assert(hasToString!(N, char) == inCharSinkFormatString);
static assert(hasToString!(O, char) == inCharSink);
}
// https://issues.dlang.org/show_bug.cgi?id=22873
static assert(hasToString!(inout(A), char) == customPutWriter);
static assert(hasToString!(inout(B), char) == constCharSinkFormatSpec);
static assert(hasToString!(inout(C), char) == constCharSinkFormatString);
static assert(hasToString!(inout(D), char) == constCharSink);
static assert(hasToString!(inout(E), char) == hasSomeToString);
static assert(hasToString!(inout(F), char) == customPutWriterFormatSpec);
static assert(hasToString!(inout(G), char) == customPutWriter);
static assert(hasToString!(inout(H), char) == customPutWriterFormatSpec);
static assert(hasToString!(inout(I), char) == customPutWriterFormatSpec);
static assert(hasToString!(inout(J), char) == hasSomeToString);
static assert(hasToString!(inout(K), char) == constCharSinkFormatSpec);
static assert(hasToString!(inout(L), char) == none);
static if (hasPreviewIn)
{
static assert(hasToString!(inout(M), char) == inCharSinkFormatSpec);
static assert(hasToString!(inout(N), char) == inCharSinkFormatString);
static assert(hasToString!(inout(O), char) == inCharSink);
}
}
}
// object formatting with toString
private void formatObject(Writer, T, Char)(ref Writer w, ref T val, scope const ref FormatSpec!Char f)
if (hasToString!(T, Char))
{
import std.format : NoOpSink;
import std.range.primitives : put;
enum overload = hasToString!(T, Char);
enum noop = is(Writer == NoOpSink);
static if (overload == HasToStringResult.customPutWriterFormatSpec)
{
static if (!noop) val.toString(w, f);
}
else static if (overload == HasToStringResult.customPutWriter)
{
static if (!noop) val.toString(w);
}
else static if (overload == HasToStringResult.constCharSinkFormatSpec)
{
static if (!noop) val.toString((scope const(char)[] s) { put(w, s); }, f);
}
else static if (overload == HasToStringResult.constCharSinkFormatString)
{
static if (!noop) val.toString((scope const(char)[] s) { put(w, s); }, f.getCurFmtStr());
}
else static if (overload == HasToStringResult.constCharSink)
{
static if (!noop) val.toString((scope const(char)[] s) { put(w, s); });
}
else static if (overload == HasToStringResult.inCharSinkFormatSpec)
{
static if (!noop) val.toString((in char[] s) { put(w, s); }, f);
}
else static if (overload == HasToStringResult.inCharSinkFormatString)
{
static if (!noop) val.toString((in char[] s) { put(w, s); }, f.getCurFmtStr());
}
else static if (overload == HasToStringResult.inCharSink)
{
static if (!noop) val.toString((in char[] s) { put(w, s); });
}
else static if (overload == HasToStringResult.hasSomeToString)
{
static if (!noop) put(w, val.toString());
}
else
{
static assert(0, "No way found to format " ~ T.stringof ~ " as string");
}
}
@system unittest
{
import std.exception : assertThrown;
import std.format : FormatException;
static interface IF1 { }
class CIF1 : IF1 { }
static struct SF1 { }
static union UF1 { }
static class CF1 { }
static interface IF2 { string toString(); }
static class CIF2 : IF2 { override string toString() { return ""; } }
static struct SF2 { string toString() { return ""; } }
static union UF2 { string toString() { return ""; } }
static class CF2 { override string toString() { return ""; } }
static interface IK1 { void toString(scope void delegate(scope const(char)[]) sink,
FormatSpec!char) const; }
static class CIK1 : IK1 { override void toString(scope void delegate(scope const(char)[]) sink,
FormatSpec!char) const { sink("CIK1"); } }
static struct KS1 { void toString(scope void delegate(scope const(char)[]) sink,
FormatSpec!char) const { sink("KS1"); } }
static union KU1 { void toString(scope void delegate(scope const(char)[]) sink,
FormatSpec!char) const { sink("KU1"); } }
static class KC1 { void toString(scope void delegate(scope const(char)[]) sink,
FormatSpec!char) const { sink("KC1"); } }
IF1 cif1 = new CIF1;
assertThrown!FormatException(format("%f", cif1));
assertThrown!FormatException(format("%f", SF1()));
assertThrown!FormatException(format("%f", UF1()));
assertThrown!FormatException(format("%f", new CF1()));
IF2 cif2 = new CIF2;
assertThrown!FormatException(format("%f", cif2));
assertThrown!FormatException(format("%f", SF2()));
assertThrown!FormatException(format("%f", UF2()));
assertThrown!FormatException(format("%f", new CF2()));
IK1 cik1 = new CIK1;
assert(format("%f", cik1) == "CIK1");
assert(format("%f", KS1()) == "KS1");
assert(format("%f", KU1()) == "KU1");
assert(format("%f", new KC1()) == "KC1");
}
/*
Aggregates
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, T val, scope const ref FormatSpec!Char f)
if (is(T == class) && !is(T == enum))
{
import std.range.primitives : put;
enforceValidFormatSpec!(T, Char)(f);
// TODO: remove this check once `@disable override` deprecation cycle is finished
static if (__traits(hasMember, T, "toString") && isSomeFunction!(val.toString))
static assert(!__traits(isDisabled, T.toString), T.stringof ~
" cannot be formatted because its `toString` is marked with `@disable`");
if (val is null)
put(w, "null");
else
{
import std.algorithm.comparison : among;
enum overload = hasToString!(T, Char);
with(HasToStringResult)
static if ((is(T == immutable) || is(T == const) || is(T == shared)) && overload == none)
{
// Remove this when Object gets const toString
// https://issues.dlang.org/show_bug.cgi?id=7879
static if (is(T == immutable))
put(w, "immutable(");
else static if (is(T == const))
put(w, "const(");
else static if (is(T == shared))
put(w, "shared(");
put(w, typeid(Unqual!T).name);
put(w, ')');
}
else static if (overload.among(constCharSink, constCharSinkFormatString, constCharSinkFormatSpec) ||
(!isInputRange!T && !is(BuiltinTypeOf!T)))
{
formatObject!(Writer, T, Char)(w, val, f);
}
else
{
static if (!is(__traits(parent, T.toString) == Object)) // not inherited Object.toString
{
formatObject(w, val, f);
}
else static if (isInputRange!T)
{
formatRange(w, val, f);
}
else static if (is(BuiltinTypeOf!T X))
{
X x = val;
formatValueImpl(w, x, f);
}
else
{
formatObject(w, val, f);
}
}
}
}
@system unittest
{
import std.array : appender;
import std.range.interfaces : inputRangeObject;
// class range (https://issues.dlang.org/show_bug.cgi?id=5154)
auto c = inputRangeObject([1,2,3,4]);
formatTest(c, "[1, 2, 3, 4]");
assert(c.empty);
c = null;
formatTest(c, "null");
}
@system unittest
{
// https://issues.dlang.org/show_bug.cgi?id=5354
// If the class has both range I/F and custom toString, the use of custom
// toString routine is prioritized.
// Enable the use of custom toString that gets a sink delegate
// for class formatting.
enum inputRangeCode =
q{
int[] arr;
this(int[] a){ arr = a; }
@property int front() const { return arr[0]; }
@property bool empty() const { return arr.length == 0; }
void popFront(){ arr = arr[1 .. $]; }
};
class C1
{
mixin(inputRangeCode);
void toString(scope void delegate(scope const(char)[]) dg,
scope const ref FormatSpec!char f) const
{
dg("[012]");
}
}
class C2
{
mixin(inputRangeCode);
void toString(scope void delegate(const(char)[]) dg, string f) const { dg("[012]"); }
}
class C3
{
mixin(inputRangeCode);
void toString(scope void delegate(const(char)[]) dg) const { dg("[012]"); }
}
class C4
{
mixin(inputRangeCode);
override string toString() const { return "[012]"; }
}
class C5
{
mixin(inputRangeCode);
}
formatTest(new C1([0, 1, 2]), "[012]");
formatTest(new C2([0, 1, 2]), "[012]");
formatTest(new C3([0, 1, 2]), "[012]");
formatTest(new C4([0, 1, 2]), "[012]");
formatTest(new C5([0, 1, 2]), "[0, 1, 2]");
}
// outside the unittest block, otherwise the FQN of the
// class contains the line number of the unittest
version (StdUnittest)
{
private class C {}
}
// https://issues.dlang.org/show_bug.cgi?id=7879
@safe unittest
{
const(C) c;
auto s = format("%s", c);
assert(s == "null");
immutable(C) c2 = new C();
s = format("%s", c2);
assert(s == "immutable(std.format.internal.write.C)");
const(C) c3 = new C();
s = format("%s", c3);
assert(s == "const(std.format.internal.write.C)");
shared(C) c4 = new C();
s = format("%s", c4);
assert(s == "shared(std.format.internal.write.C)");
}
// https://issues.dlang.org/show_bug.cgi?id=7879
@safe unittest
{
class F
{
override string toString() const @safe
{
return "Foo";
}
}
const(F) c;
auto s = format("%s", c);
assert(s == "null");
const(F) c2 = new F();
s = format("%s", c2);
assert(s == "Foo", s);
}
void formatValueImpl(Writer, T, Char)(auto ref Writer w, T val, scope const ref FormatSpec!Char f)
if (is(T == interface) && (hasToString!(T, Char) || !is(BuiltinTypeOf!T)) && !is(T == enum))
{
import std.range.primitives : put;
enforceValidFormatSpec!(T, Char)(f);
if (val is null)
put(w, "null");
else
{
static if (__traits(hasMember, T, "toString") && isSomeFunction!(val.toString))
static assert(!__traits(isDisabled, T.toString), T.stringof ~
" cannot be formatted because its `toString` is marked with `@disable`");
static if (hasToString!(T, Char) != HasToStringResult.none)
{
formatObject(w, val, f);
}
else static if (isInputRange!T)
{
formatRange(w, val, f);
}
else
{
version (Windows)
{
import core.sys.windows.com : IUnknown;
static if (is(T : IUnknown))
{
formatValueImpl(w, *cast(void**)&val, f);
}
else
{
formatValueImpl(w, cast(Object) val, f);
}
}
else
{
formatValueImpl(w, cast(Object) val, f);
}
}
}
}
@system unittest
{
import std.range.interfaces : InputRange, inputRangeObject;
// interface
InputRange!int i = inputRangeObject([1,2,3,4]);
formatTest(i, "[1, 2, 3, 4]");
assert(i.empty);
i = null;
formatTest(i, "null");
// interface (downcast to Object)
interface Whatever {}
class C : Whatever
{
override @property string toString() const { return "ab"; }
}
Whatever val = new C;
formatTest(val, "ab");
// https://issues.dlang.org/show_bug.cgi?id=11175
version (Windows)
{
import core.sys.windows.com : IID, IUnknown;
import core.sys.windows.windef : HRESULT;
interface IUnknown2 : IUnknown { }
class D : IUnknown2
{
extern(Windows) HRESULT QueryInterface(const(IID)* riid, void** pvObject) { return typeof(return).init; }
extern(Windows) uint AddRef() { return 0; }
extern(Windows) uint Release() { return 0; }
}
IUnknown2 d = new D;
string expected = format("%X", cast(void*) d);
formatTest(d, expected);
}
}
// Maybe T is noncopyable struct, so receive it by 'auto ref'.
void formatValueImpl(Writer, T, Char)(auto ref Writer w, auto ref T val,
scope const ref FormatSpec!Char f)
if ((is(T == struct) || is(T == union)) && (hasToString!(T, Char) || !is(BuiltinTypeOf!T))
&& !is(T == enum))
{
import std.range.primitives : put;
static if (__traits(hasMember, T, "toString") && isSomeFunction!(val.toString))
static assert(!__traits(isDisabled, T.toString), T.stringof ~
" cannot be formatted because its `toString` is marked with `@disable`");
enforceValidFormatSpec!(T, Char)(f);
static if (hasToString!(T, Char))
{
formatObject(w, val, f);
}
else static if (isInputRange!T)
{
formatRange(w, val, f);
}
else static if (is(T == struct))
{
enum left = T.stringof~"(";
enum separator = ", ";
enum right = ")";
put(w, left);
foreach (i, e; val.tupleof)
{
static if (__traits(identifier, val.tupleof[i]) == "this")
continue;
else static if (0 < i && val.tupleof[i-1].offsetof == val.tupleof[i].offsetof)
{
static if (i == val.tupleof.length - 1 || val.tupleof[i].offsetof != val.tupleof[i+1].offsetof)
{
enum el = separator ~ val.tupleof[i].stringof[4 .. $] ~ "}";
put(w, el);
}
else
{
enum el = separator ~ val.tupleof[i].stringof[4 .. $];
put(w, el);
}
}
else static if (i+1 < val.tupleof.length && val.tupleof[i].offsetof == val.tupleof[i+1].offsetof)
{
enum el = (i > 0 ? separator : "") ~ "#{overlap " ~ val.tupleof[i].stringof[4 .. $];
put(w, el);
}
else
{
static if (i > 0)
put(w, separator);
formatElement(w, e, f);
}
}
put(w, right);
}
else
{
put(w, T.stringof);
}
}
// https://issues.dlang.org/show_bug.cgi?id=9588
@safe pure unittest
{
struct S { int x; bool empty() { return false; } }
formatTest(S(), "S(0)");
}
// https://issues.dlang.org/show_bug.cgi?id=4638
@safe unittest
{
struct U8 { string toString() const { return "blah"; } }
struct U16 { wstring toString() const { return "blah"; } }
struct U32 { dstring toString() const { return "blah"; } }
formatTest(U8(), "blah");
formatTest(U16(), "blah");
formatTest(U32(), "blah");
}
// https://issues.dlang.org/show_bug.cgi?id=3890
@safe unittest
{
struct Int{ int n; }
struct Pair{ string s; Int i; }
formatTest(Pair("hello", Int(5)),
`Pair("hello", Int(5))`);
}
// https://issues.dlang.org/show_bug.cgi?id=9117
@safe unittest
{
import std.format : formattedWrite;
static struct Frop {}
static struct Foo
{
int n = 0;
alias n this;
T opCast(T) () if (is(T == Frop))
{
return Frop();
}
string toString()
{
return "Foo";
}
}
static struct Bar
{
Foo foo;
alias foo this;
string toString()
{
return "Bar";
}
}
const(char)[] result;
void put(scope const char[] s) { result ~= s; }
Foo foo;
formattedWrite(&put, "%s", foo); // OK
assert(result == "Foo");
result = null;
Bar bar;
formattedWrite(&put, "%s", bar); // NG
assert(result == "Bar");
result = null;
int i = 9;
formattedWrite(&put, "%s", 9);
assert(result == "9");
}
@safe unittest
{
// union formatting without toString
union U1
{
int n;
string s;
}
U1 u1;
formatTest(u1, "U1");
// union formatting with toString
union U2
{
int n;
string s;
string toString() const { return s; }
}
U2 u2;
() @trusted { u2.s = "hello"; } ();
formatTest(u2, "hello");
}
@safe unittest
{
import std.array : appender;
import std.format : formatValue;
// https://issues.dlang.org/show_bug.cgi?id=7230
static struct Bug7230
{
string s = "hello";
union {
string a;
int b;
double c;
}
long x = 10;
}
Bug7230 bug;
bug.b = 123;
FormatSpec!char f;
auto w = appender!(char[])();
formatValue(w, bug, f);
assert(w.data == `Bug7230("hello", #{overlap a, b, c}, 10)`);
}
@safe unittest
{
import std.array : appender;
import std.format : formatValue;
static struct S{ @disable this(this); }
S s;
FormatSpec!char f;
auto w = appender!string();
formatValue(w, s, f);
assert(w.data == "S()");
}
@safe unittest
{
import std.array : appender;
import std.format : formatValue;
//struct Foo { @disable string toString(); }
//Foo foo;
interface Bar { @disable string toString(); }
Bar bar;
auto w = appender!(char[])();
FormatSpec!char f;
// NOTE: structs cant be tested : the assertion is correct so compilation
// continues and fails when trying to link the unimplemented toString.
//static assert(!__traits(compiles, formatValue(w, foo, f)));
static assert(!__traits(compiles, formatValue(w, bar, f)));
}
// https://issues.dlang.org/show_bug.cgi?id=21722
@safe unittest
{
struct Bar
{
void toString (scope void delegate (scope const(char)[]) sink, string fmt)
{
sink("Hello");
}
}
Bar b;
auto result = () @trusted { return format("%b", b); } ();
assert(result == "Hello");
static if (hasPreviewIn)
{
struct Foo
{
void toString(scope void delegate(in char[]) sink, in FormatSpec!char fmt)
{
sink("Hello");
}
}
Foo f;
assert(format("%b", f) == "Hello");
struct Foo2
{
void toString(scope void delegate(in char[]) sink, string fmt)
{
sink("Hello");
}
}
Foo2 f2;
assert(format("%b", f2) == "Hello");
}
}
@safe unittest
{
import std.array : appender;
import std.format : singleSpec;
// Bug #17269. Behavior similar to `struct A { Nullable!string B; }`
struct StringAliasThis
{
@property string value() const { assert(0); }
alias value this;
string toString() { return "helloworld"; }
private string _value;
}
struct TestContainer
{
StringAliasThis testVar;
}
auto w = appender!string();
auto spec = singleSpec("%s");
formatElement(w, TestContainer(), spec);
assert(w.data == "TestContainer(helloworld)", w.data);
}
// https://issues.dlang.org/show_bug.cgi?id=17269
@safe unittest
{
import std.typecons : Nullable;
struct Foo
{
Nullable!string bar;
}
Foo f;
formatTest(f, "Foo(Nullable.null)");
}
// https://issues.dlang.org/show_bug.cgi?id=19003
@safe unittest
{
struct S
{
int i;
@disable this();
invariant { assert(this.i); }
this(int i) @safe in { assert(i); } do { this.i = i; }
string toString() { return "S"; }
}
S s = S(1);
format!"%s"(s);
}
void enforceValidFormatSpec(T, Char)(scope const ref FormatSpec!Char f)
{
import std.format : enforceFmt;
import std.range : isInputRange;
import std.format.internal.write : hasToString, HasToStringResult;
enum overload = hasToString!(T, Char);
static if (
overload != HasToStringResult.constCharSinkFormatSpec &&
overload != HasToStringResult.constCharSinkFormatString &&
overload != HasToStringResult.inCharSinkFormatSpec &&
overload != HasToStringResult.inCharSinkFormatString &&
overload != HasToStringResult.customPutWriterFormatSpec &&
!isInputRange!T)
{
enforceFmt(f.spec == 's',
"Expected '%s' format specifier for type '" ~ T.stringof ~ "'");
}
}
/*
`enum`s are formatted like their base value
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, const(T) val, scope const ref FormatSpec!Char f)
if (is(T == enum))
{
import std.array : appender;
import std.range.primitives : put;
if (f.spec == 's')
{
foreach (i, e; EnumMembers!T)
{
if (val == e)
{
formatValueImpl(w, __traits(allMembers, T)[i], f);
return;
}
}
auto w2 = appender!string();
// val is not a member of T, output cast(T) rawValue instead.
put(w2, "cast(");
put(w2, T.stringof);
put(w2, ")");
static assert(!is(OriginalType!T == T), "OriginalType!" ~ T.stringof ~
"must not be equal to " ~ T.stringof);
FormatSpec!Char f2 = f;
f2.width = 0;
formatValueImpl(w2, cast(OriginalType!T) val, f2);
writeAligned(w, w2.data, f);
return;
}
formatValueImpl(w, cast(OriginalType!T) val, f);
}
@safe unittest
{
enum A { first, second, third }
formatTest(A.second, "second");
formatTest(cast(A) 72, "cast(A)72");
}
@safe unittest
{
enum A : string { one = "uno", two = "dos", three = "tres" }
formatTest(A.three, "three");
formatTest(cast(A)"mill\ón", "cast(A)mill\ón");
}
@safe unittest
{
enum A : bool { no, yes }
formatTest(A.yes, "yes");
formatTest(A.no, "no");
}
@safe unittest
{
// Test for bug 6892
enum Foo { A = 10 }
formatTest("%s", Foo.A, "A");
formatTest(">%4s<", Foo.A, "> A<");
formatTest("%04d", Foo.A, "0010");
formatTest("%+2u", Foo.A, "10");
formatTest("%02x", Foo.A, "0a");
formatTest("%3o", Foo.A, " 12");
formatTest("%b", Foo.A, "1010");
}
@safe pure unittest
{
enum A { one, two, three }
string t1 = format("[%6s] [%-6s]", A.one, A.one);
assert(t1 == "[ one] [one ]");
string t2 = format("[%10s] [%-10s]", cast(A) 10, cast(A) 10);
assert(t2 == "[ cast(A)" ~ "10] [cast(A)" ~ "10 ]"); // due to bug in style checker
}
// https://issues.dlang.org/show_bug.cgi?id=8921
@safe unittest
{
enum E : char { A = 'a', B = 'b', C = 'c' }
E[3] e = [E.A, E.B, E.C];
formatTest(e, "[A, B, C]");
E[] e2 = [E.A, E.B, E.C];
formatTest(e2, "[A, B, C]");
}
/*
Pointers are formatted as hex integers.
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, scope const(T) val, scope const ref FormatSpec!Char f)
if (isPointer!T && !is(T == enum) && !hasToString!(T, Char))
{
static if (is(typeof({ shared const void* p = val; })))
alias SharedOf(T) = shared(T);
else
alias SharedOf(T) = T;
const SharedOf!(void*) p = val;
const pnum = () @trusted { return cast(ulong) p; }();
if (f.spec == 's')
{
if (p is null)
{
writeAligned(w, "null", f);
return;
}
FormatSpec!Char fs = f; // fs is copy for change its values.
fs.spec = 'X';
formatValueImpl(w, pnum, fs);
}
else
{
import std.format : enforceFmt;
enforceFmt(f.spec == 'X' || f.spec == 'x',
"Expected one of %s, %x or %X for pointer type.");
formatValueImpl(w, pnum, f);
}
}
@safe pure unittest
{
int* p;
string t1 = format("[%6s] [%-6s]", p, p);
assert(t1 == "[ null] [null ]");
}
@safe pure unittest
{
int* p = null;
formatTest(p, "null");
auto q = () @trusted { return cast(void*) 0xFFEECCAA; }();
formatTest(q, "FFEECCAA");
}
// https://issues.dlang.org/show_bug.cgi?id=11782
@safe pure unittest
{
import std.range : iota;
auto a = iota(0, 10);
auto b = iota(0, 10);
auto p = () @trusted { auto p = &a; return p; }();
assert(format("%s",p) != format("%s",b));
}
@safe pure unittest
{
// Test for https://issues.dlang.org/show_bug.cgi?id=7869
struct S
{
string toString() const { return ""; }
}
S* p = null;
formatTest(p, "null");
S* q = () @trusted { return cast(S*) 0xFFEECCAA; } ();
formatTest(q, "FFEECCAA");
}
// https://issues.dlang.org/show_bug.cgi?id=8186
@system unittest
{
class B
{
int* a;
this() { a = new int; }
alias a this;
}
formatTest(B.init, "null");
}
// https://issues.dlang.org/show_bug.cgi?id=9336
@system pure unittest
{
shared int i;
format("%s", &i);
}
// https://issues.dlang.org/show_bug.cgi?id=11778
@safe pure unittest
{
import std.exception : assertThrown;
import std.format : FormatException;
int* p = null;
assertThrown!FormatException(format("%d", p));
assertThrown!FormatException(format("%04d", () @trusted { return p + 2; } ()));
}
// https://issues.dlang.org/show_bug.cgi?id=12505
@safe pure unittest
{
void* p = null;
formatTest("%08X", p, "00000000");
}
/*
SIMD vectors are formatted as arrays.
*/
void formatValueImpl(Writer, V, Char)(auto ref Writer w, const(V) val, scope const ref FormatSpec!Char f)
if (isSIMDVector!V)
{
formatValueImpl(w, val.array, f);
}
@safe unittest
{
import core.simd; // cannot be selective, because float4 might not be defined
static if (is(float4))
{
version (X86)
{
version (OSX) {/* https://issues.dlang.org/show_bug.cgi?id=17823 */}
}
else
{
float4 f;
f.array[0] = 1;
f.array[1] = 2;
f.array[2] = 3;
f.array[3] = 4;
formatTest(f, "[1, 2, 3, 4]");
}
}
}
/*
Delegates are formatted by `ReturnType delegate(Parameters) FunctionAttributes`
Known bug: Because of issue https://issues.dlang.org/show_bug.cgi?id=18269
the FunctionAttributes might be wrong.
*/
void formatValueImpl(Writer, T, Char)(auto ref Writer w, scope const(T), scope const ref FormatSpec!Char f)
if (isDelegate!T)
{
formatValueImpl(w, T.stringof, f);
}
@safe unittest
{
import std.array : appender;
import std.format : formatValue;
void func() @system { __gshared int x; ++x; throw new Exception("msg"); }
version (linux)
{
FormatSpec!char f;
auto w = appender!string();
formatValue(w, &func, f);
assert(w.data.length >= 15 && w.data[0 .. 15] == "void delegate()");
}
}
// string elements are formatted like UTF-8 string literals.
void formatElement(Writer, T, Char)(auto ref Writer w, T val, scope const ref FormatSpec!Char f)
if (is(StringTypeOf!T) && !hasToString!(T, Char) && !is(T == enum))
{
import std.array : appender;
import std.format.write : formattedWrite, formatValue;
import std.range.primitives : put;
import std.utf : decode, UTFException;
StringTypeOf!T str = val; // https://issues.dlang.org/show_bug.cgi?id=8015
if (f.spec == 's')
{
try
{
// ignore other specifications and quote
for (size_t i = 0; i < str.length; )
{
auto c = decode(str, i);
// \uFFFE and \uFFFF are considered valid by isValidDchar,
// so need checking for interchange.
if (c == 0xFFFE || c == 0xFFFF)
goto LinvalidSeq;
}
put(w, '\"');
for (size_t i = 0; i < str.length; )
{
auto c = decode(str, i);
formatChar(w, c, '"');
}
put(w, '\"');
return;
}
catch (UTFException)
{
}
// If val contains invalid UTF sequence, formatted like HexString literal
LinvalidSeq:
static if (is(typeof(str[0]) : const(char)))
{
enum type = "";
alias IntArr = const(ubyte)[];
}
else static if (is(typeof(str[0]) : const(wchar)))
{
enum type = "w";
alias IntArr = const(ushort)[];
}
else static if (is(typeof(str[0]) : const(dchar)))
{
enum type = "d";
alias IntArr = const(uint)[];
}
formattedWrite(w, "[%(cast(" ~ type ~ "char) 0x%X%|, %)]", cast(IntArr) str);
}
else
formatValue(w, str, f);
}
@safe pure unittest
{
import std.array : appender;
import std.format.spec : singleSpec;
auto w = appender!string();
auto spec = singleSpec("%s");
formatElement(w, "Hello World", spec);
assert(w.data == "\"Hello World\"");
}
@safe unittest
{
import std.array : appender;
import std.format.spec : singleSpec;
auto w = appender!string();
auto spec = singleSpec("%s");
formatElement(w, "H", spec);
assert(w.data == "\"H\"", w.data);
}
// https://issues.dlang.org/show_bug.cgi?id=15888
@safe pure unittest
{
import std.array : appender;
import std.format.spec : singleSpec;
ushort[] a = [0xFF_FE, 0x42];
auto w = appender!string();
auto spec = singleSpec("%s");
formatElement(w, cast(wchar[]) a, spec);
assert(w.data == `[cast(wchar) 0xFFFE, cast(wchar) 0x42]`);
uint[] b = [0x0F_FF_FF_FF, 0x42];
w = appender!string();
spec = singleSpec("%s");
formatElement(w, cast(dchar[]) b, spec);
assert(w.data == `[cast(dchar) 0xFFFFFFF, cast(dchar) 0x42]`);
}
// Character elements are formatted like UTF-8 character literals.
void formatElement(Writer, T, Char)(auto ref Writer w, T val, scope const ref FormatSpec!Char f)
if (is(CharTypeOf!T) && !is(T == enum))
{
import std.range.primitives : put;
import std.format.write : formatValue;
if (f.spec == 's')
{
put(w, '\'');
formatChar(w, val, '\'');
put(w, '\'');
}
else
formatValue(w, val, f);
}
// Maybe T is noncopyable struct, so receive it by 'auto ref'.
void formatElement(Writer, T, Char)(auto ref Writer w, auto ref T val, scope const ref FormatSpec!Char f)
if ((!is(StringTypeOf!T) || hasToString!(T, Char)) && !is(CharTypeOf!T) || is(T == enum))
{
import std.format.write : formatValue;
formatValue(w, val, f);
}
// Fix for https://issues.dlang.org/show_bug.cgi?id=1591
int getNthInt(string kind, A...)(uint index, A args)
{
return getNth!(kind, isIntegral, int)(index, args);
}
T getNth(string kind, alias Condition, T, A...)(uint index, A args)
{
import std.conv : text, to;
import std.format : FormatException;
switch (index)
{
foreach (n, _; A)
{
case n:
static if (Condition!(typeof(args[n])))
{
return to!T(args[n]);
}
else
{
throw new FormatException(
text(kind, " expected, not ", typeof(args[n]).stringof,
" for argument #", index + 1));
}
}
default:
throw new FormatException(text("Missing ", kind, " argument"));
}
}
private bool needToSwapEndianess(Char)(scope const ref FormatSpec!Char f)
{
import std.system : endian, Endian;
return endian == Endian.littleEndian && f.flPlus
|| endian == Endian.bigEndian && f.flDash;
}
void writeAligned(Writer, T, Char)(auto ref Writer w, T s, scope const ref FormatSpec!Char f)
if (isSomeString!T)
{
FormatSpec!Char fs = f;
fs.flZero = false;
writeAligned(w, "", "", s, fs);
}
@safe pure unittest
{
import std.array : appender;
import std.format : singleSpec;
auto w = appender!string();
auto spec = singleSpec("%s");
writeAligned(w, "a本Ä", spec);
assert(w.data == "a本Ä", w.data);
}
@safe pure unittest
{
import std.array : appender;
import std.format : singleSpec;
auto w = appender!string();
auto spec = singleSpec("%10s");
writeAligned(w, "a本Ä", spec);
assert(w.data == " a本Ä", "|" ~ w.data ~ "|");
}
@safe pure unittest
{
import std.array : appender;
import std.format : singleSpec;
auto w = appender!string();
auto spec = singleSpec("%-10s");
writeAligned(w, "a本Ä", spec);
assert(w.data == "a本Ä ", w.data);
}
enum PrecisionType
{
none,
integer,
fractionalDigits,
allDigits,
}
void writeAligned(Writer, T1, T2, T3, Char)(auto ref Writer w,
T1 prefix, T2 grouped, T3 suffix, scope const ref FormatSpec!Char f,
bool integer_precision = false)
if (isSomeString!T1 && isSomeString!T2 && isSomeString!T3)
{
writeAligned(w, prefix, grouped, "", suffix, f,
integer_precision ? PrecisionType.integer : PrecisionType.none);
}
void writeAligned(Writer, T1, T2, T3, T4, Char)(auto ref Writer w,
T1 prefix, T2 grouped, T3 fracts, T4 suffix, scope const ref FormatSpec!Char f,
PrecisionType p = PrecisionType.none)
if (isSomeString!T1 && isSomeString!T2 && isSomeString!T3 && isSomeString!T4)
{
// writes: left padding, prefix, leading zeros, grouped, fracts, suffix, right padding
if (p == PrecisionType.integer && f.precision == f.UNSPECIFIED)
p = PrecisionType.none;
import std.range.primitives : put;
long prefixWidth;
long groupedWidth = grouped.length; // TODO: does not take graphemes into account
long fractsWidth = fracts.length; // TODO: does not take graphemes into account
long suffixWidth;
// TODO: remove this workaround which hides issue 21815
if (f.width > 0)
{
prefixWidth = getWidth(prefix);
suffixWidth = getWidth(suffix);
}
auto doGrouping = f.flSeparator && groupedWidth > 0
&& f.separators > 0 && f.separators != f.UNSPECIFIED;
// front = number of symbols left of the leftmost separator
long front = doGrouping ? (groupedWidth - 1) % f.separators + 1 : 0;
// sepCount = number of separators to be inserted
long sepCount = doGrouping ? (groupedWidth - 1) / f.separators : 0;
long trailingZeros = 0;
if (p == PrecisionType.fractionalDigits)
trailingZeros = f.precision - (fractsWidth - 1);
if (p == PrecisionType.allDigits && f.flHash)
{
if (grouped != "0")
trailingZeros = f.precision - (fractsWidth - 1) - groupedWidth;
else
{
trailingZeros = f.precision - fractsWidth;
foreach (i;0 .. fracts.length)
if (fracts[i] != '0' && fracts[i] != '.')
{
trailingZeros = f.precision - (fracts.length - i);
break;
}
}
}
auto nodot = fracts == "." && trailingZeros == 0 && !f.flHash;
if (nodot) fractsWidth = 0;
long width = prefixWidth + sepCount + groupedWidth + fractsWidth + trailingZeros + suffixWidth;
long delta = f.width - width;
// with integers, precision is considered the minimum number of digits;
// if digits are missing, we have to recalculate everything
long pregrouped = 0;
if (p == PrecisionType.integer && groupedWidth < f.precision)
{
pregrouped = f.precision - groupedWidth;
delta -= pregrouped;
if (doGrouping)
{
front = ((front - 1) + pregrouped) % f.separators + 1;
delta -= (f.precision - 1) / f.separators - sepCount;
}
}
// left padding
if ((!f.flZero || p == PrecisionType.integer) && delta > 0)
{
if (f.flEqual)
{
foreach (i ; 0 .. delta / 2 + ((delta % 2 == 1 && !f.flDash) ? 1 : 0))
put(w, ' ');
}
else if (!f.flDash)
{
foreach (i ; 0 .. delta)
put(w, ' ');
}
}
// prefix
put(w, prefix);
// leading grouped zeros
if (f.flZero && p != PrecisionType.integer && !f.flDash && delta > 0)
{
if (doGrouping)
{
// front2 and sepCount2 are the same as above for the leading zeros
long front2 = (delta + front - 1) % (f.separators + 1) + 1;
long sepCount2 = (delta + front - 1) / (f.separators + 1);
delta -= sepCount2;
// according to POSIX: if the first symbol is a separator,
// an additional zero is put left of it, even if that means, that
// the total width is one more then specified
if (front2 > f.separators) { front2 = 1; }
foreach (i ; 0 .. delta)
{
if (front2 == 0)
{
put(w, f.separatorChar);
front2 = f.separators;
}
front2--;
put(w, '0');
}
// separator between zeros and grouped
if (front == f.separators)
put(w, f.separatorChar);
}
else
foreach (i ; 0 .. delta)
put(w, '0');
}
// grouped content
if (doGrouping)
{
// TODO: this does not take graphemes into account
foreach (i;0 .. pregrouped + grouped.length)
{
if (front == 0)
{
put(w, f.separatorChar);
front = f.separators;
}
front--;
put(w, i < pregrouped ? '0' : grouped[cast(size_t) (i - pregrouped)]);
}
}
else
{
foreach (i;0 .. pregrouped)
put(w, '0');
put(w, grouped);
}
// fracts
if (!nodot)
put(w, fracts);
// trailing zeros
foreach (i ; 0 .. trailingZeros)
put(w, '0');
// suffix
put(w, suffix);
// right padding
if (delta > 0)
{
if (f.flEqual)
{
foreach (i ; 0 .. delta / 2 + ((delta % 2 == 1 && f.flDash) ? 1 : 0))
put(w, ' ');
}
else if (f.flDash)
{
foreach (i ; 0 .. delta)
put(w, ' ');
}
}
}
@safe pure unittest
{
import std.array : appender;
import std.format : singleSpec;
auto w = appender!string();
auto spec = singleSpec("%s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pregroupingsuf", w.data);
w = appender!string();
spec = singleSpec("%20s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == " pregroupingsuf", w.data);
w = appender!string();
spec = singleSpec("%-20s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pregroupingsuf ", w.data);
w = appender!string();
spec = singleSpec("%020s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pre000000groupingsuf", w.data);
w = appender!string();
spec = singleSpec("%-020s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pregroupingsuf ", w.data);
w = appender!string();
spec = singleSpec("%20,1s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "preg,r,o,u,p,i,n,gsuf", w.data);
w = appender!string();
spec = singleSpec("%20,2s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == " pregr,ou,pi,ngsuf", w.data);
w = appender!string();
spec = singleSpec("%20,3s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == " pregr,oup,ingsuf", w.data);
w = appender!string();
spec = singleSpec("%20,10s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == " pregroupingsuf", w.data);
w = appender!string();
spec = singleSpec("%020,1s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "preg,r,o,u,p,i,n,gsuf", w.data);
w = appender!string();
spec = singleSpec("%020,2s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pre00,gr,ou,pi,ngsuf", w.data);
w = appender!string();
spec = singleSpec("%020,3s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pre00,0gr,oup,ingsuf", w.data);
w = appender!string();
spec = singleSpec("%020,10s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pre000,00groupingsuf", w.data);
w = appender!string();
spec = singleSpec("%021,3s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pre000,0gr,oup,ingsuf", w.data);
// According to https://github.com/dlang/phobos/pull/7112 this
// is defined by POSIX standard:
w = appender!string();
spec = singleSpec("%022,3s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pre0,000,0gr,oup,ingsuf", w.data);
w = appender!string();
spec = singleSpec("%023,3s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pre0,000,0gr,oup,ingsuf", w.data);
w = appender!string();
spec = singleSpec("%,3s");
writeAligned(w, "pre", "grouping", "suf", spec);
assert(w.data == "pregr,oup,ingsuf", w.data);
}
@safe pure unittest
{
import std.array : appender;
import std.format : singleSpec;
auto w = appender!string();
auto spec = singleSpec("%.10s");
writeAligned(w, "pre", "grouping", "suf", spec, true);
assert(w.data == "pre00groupingsuf", w.data);
w = appender!string();
spec = singleSpec("%.10,3s");
writeAligned(w, "pre", "grouping", "suf", spec, true);
assert(w.data == "pre0,0gr,oup,ingsuf", w.data);
w = appender!string();
spec = singleSpec("%25.10,3s");
writeAligned(w, "pre", "grouping", "suf", spec, true);
assert(w.data == " pre0,0gr,oup,ingsuf", w.data);
// precision has precedence over zero flag
w = appender!string();
spec = singleSpec("%025.12,3s");
writeAligned(w, "pre", "grouping", "suf", spec, true);
assert(w.data == " pre000,0gr,oup,ingsuf", w.data);
w = appender!string();
spec = singleSpec("%025.13,3s");
writeAligned(w, "pre", "grouping", "suf", spec, true);
assert(w.data == " pre0,000,0gr,oup,ingsuf", w.data);
}
@safe unittest
{
assert(format("%,d", 1000) == "1,000");
assert(format("%,f", 1234567.891011) == "1,234,567.891011");
assert(format("%,?d", '?', 1000) == "1?000");
assert(format("%,1d", 1000) == "1,0,0,0", format("%,1d", 1000));
assert(format("%,*d", 4, -12345) == "-1,2345");
assert(format("%,*?d", 4, '_', -12345) == "-1_2345");
assert(format("%,6?d", '_', -12345678) == "-12_345678");
assert(format("%12,3.3f", 1234.5678) == " 1,234.568", "'" ~
format("%12,3.3f", 1234.5678) ~ "'");
}
private long getWidth(T)(T s)
{
import std.algorithm.searching : all;
import std.uni : graphemeStride;
// check for non-ascii character
if (s.all!(a => a <= 0x7F)) return s.length;
//TODO: optimize this
long width = 0;
for (size_t i; i < s.length; i += graphemeStride(s, i))
++width;
return width;
}
enum RoundingClass { ZERO, LOWER, FIVE, UPPER }
enum RoundingMode { up, down, toZero, toNearestTiesToEven, toNearestTiesAwayFromZero }
bool round(T)(ref T sequence, size_t left, size_t right, RoundingClass type, bool negative, char max = '9')
in (left >= 0) // should be left > 0, but if you know ahead, that there's no carry, left == 0 is fine
in (left < sequence.length)
in (right >= 0)
in (right <= sequence.length)
in (right >= left)
in (max == '9' || max == 'f' || max == 'F')
{
import std.math.hardware;
auto mode = RoundingMode.toNearestTiesToEven;
if (!__ctfe)
{
// std.math's FloatingPointControl isn't available on all target platforms
static if (is(FloatingPointControl))
{
switch (FloatingPointControl.rounding)
{
case FloatingPointControl.roundUp:
mode = RoundingMode.up;
break;
case FloatingPointControl.roundDown:
mode = RoundingMode.down;
break;
case FloatingPointControl.roundToZero:
mode = RoundingMode.toZero;
break;
case FloatingPointControl.roundToNearest:
mode = RoundingMode.toNearestTiesToEven;
break;
default: assert(false, "Unknown floating point rounding mode");
}
}
}
bool roundUp = false;
if (mode == RoundingMode.up)
roundUp = type != RoundingClass.ZERO && !negative;
else if (mode == RoundingMode.down)
roundUp = type != RoundingClass.ZERO && negative;
else if (mode == RoundingMode.toZero)
roundUp = false;
else
{
roundUp = type == RoundingClass.UPPER;
if (type == RoundingClass.FIVE)
{
// IEEE754 allows for two different ways of implementing roundToNearest:
if (mode == RoundingMode.toNearestTiesAwayFromZero)
roundUp = true;
else
{
// Round to nearest, ties to even
auto last = sequence[right - 1];
if (last == '.') last = sequence[right - 2];
roundUp = (last <= '9' && last % 2 != 0) || (last > '9' && last % 2 == 0);
}
}
}
if (!roundUp) return false;
foreach_reverse (i;left .. right)
{
if (sequence[i] == '.') continue;
if (sequence[i] == max)
sequence[i] = '0';
else
{
if (max != '9' && sequence[i] == '9')
sequence[i] = max == 'f' ? 'a' : 'A';
else
sequence[i]++;
return false;
}
}
sequence[left - 1] = '1';
return true;
}
@safe unittest
{
char[10] c;
size_t left = 5;
size_t right = 8;
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.UPPER, false) == true);
assert(c[4 .. 8] == "1.00");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.FIVE, false) == true);
assert(c[4 .. 8] == "1.00");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.LOWER, false) == false);
assert(c[4 .. 8] == "x.99");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.ZERO, false) == false);
assert(c[4 .. 8] == "x.99");
import std.math.hardware;
static if (is(FloatingPointControl))
{
FloatingPointControl fpctrl;
fpctrl.rounding = FloatingPointControl.roundUp;
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.UPPER, false) == true);
assert(c[4 .. 8] == "1.00");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.FIVE, false) == true);
assert(c[4 .. 8] == "1.00");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.LOWER, false) == true);
assert(c[4 .. 8] == "1.00");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.ZERO, false) == false);
assert(c[4 .. 8] == "x.99");
fpctrl.rounding = FloatingPointControl.roundDown;
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.UPPER, false) == false);
assert(c[4 .. 8] == "x.99");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.FIVE, false) == false);
assert(c[4 .. 8] == "x.99");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.LOWER, false) == false);
assert(c[4 .. 8] == "x.99");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.ZERO, false) == false);
assert(c[4 .. 8] == "x.99");
fpctrl.rounding = FloatingPointControl.roundToZero;
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.UPPER, false) == false);
assert(c[4 .. 8] == "x.99");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.FIVE, false) == false);
assert(c[4 .. 8] == "x.99");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.LOWER, false) == false);
assert(c[4 .. 8] == "x.99");
c[4 .. 8] = "x.99";
assert(round(c, left, right, RoundingClass.ZERO, false) == false);
assert(c[4 .. 8] == "x.99");
}
}
@safe unittest
{
char[10] c;
size_t left = 5;
size_t right = 8;
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.UPPER, true) == false);
assert(c[4 .. 8] == "x8.6");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.FIVE, true) == false);
assert(c[4 .. 8] == "x8.6");
c[4 .. 8] = "x8.4";
assert(round(c, left, right, RoundingClass.FIVE, true) == false);
assert(c[4 .. 8] == "x8.4");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.LOWER, true) == false);
assert(c[4 .. 8] == "x8.5");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.ZERO, true) == false);
assert(c[4 .. 8] == "x8.5");
import std.math.hardware;
static if (is(FloatingPointControl))
{
FloatingPointControl fpctrl;
fpctrl.rounding = FloatingPointControl.roundUp;
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.UPPER, true) == false);
assert(c[4 .. 8] == "x8.5");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.FIVE, true) == false);
assert(c[4 .. 8] == "x8.5");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.LOWER, true) == false);
assert(c[4 .. 8] == "x8.5");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.ZERO, true) == false);
assert(c[4 .. 8] == "x8.5");
fpctrl.rounding = FloatingPointControl.roundDown;
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.UPPER, true) == false);
assert(c[4 .. 8] == "x8.6");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.FIVE, true) == false);
assert(c[4 .. 8] == "x8.6");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.LOWER, true) == false);
assert(c[4 .. 8] == "x8.6");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.ZERO, true) == false);
assert(c[4 .. 8] == "x8.5");
fpctrl.rounding = FloatingPointControl.roundToZero;
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.UPPER, true) == false);
assert(c[4 .. 8] == "x8.5");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.FIVE, true) == false);
assert(c[4 .. 8] == "x8.5");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.LOWER, true) == false);
assert(c[4 .. 8] == "x8.5");
c[4 .. 8] = "x8.5";
assert(round(c, left, right, RoundingClass.ZERO, true) == false);
assert(c[4 .. 8] == "x8.5");
}
}
@safe unittest
{
char[10] c;
size_t left = 5;
size_t right = 8;
c[4 .. 8] = "x8.9";
assert(round(c, left, right, RoundingClass.UPPER, true, 'f') == false);
assert(c[4 .. 8] == "x8.a");
c[4 .. 8] = "x8.9";
assert(round(c, left, right, RoundingClass.UPPER, true, 'F') == false);
assert(c[4 .. 8] == "x8.A");
c[4 .. 8] = "x8.f";
assert(round(c, left, right, RoundingClass.UPPER, true, 'f') == false);
assert(c[4 .. 8] == "x9.0");
}
version (StdUnittest)
private void formatTest(T)(T val, string expected, size_t ln = __LINE__, string fn = __FILE__)
{
formatTest(val, [expected], ln, fn);
}
version (StdUnittest)
private void formatTest(T)(string fmt, T val, string expected, size_t ln = __LINE__, string fn = __FILE__) @safe
{
formatTest(fmt, val, [expected], ln, fn);
}
version (StdUnittest)
private void formatTest(T)(T val, string[] expected, size_t ln = __LINE__, string fn = __FILE__)
{
import core.exception : AssertError;
import std.algorithm.searching : canFind;
import std.array : appender;
import std.conv : text;
import std.exception : enforce;
import std.format.write : formatValue;
FormatSpec!char f;
auto w = appender!string();
formatValue(w, val, f);
enforce!AssertError(expected.canFind(w.data),
text("expected one of `", expected, "`, result = `", w.data, "`"), fn, ln);
}
version (StdUnittest)
private void formatTest(T)(string fmt, T val, string[] expected, size_t ln = __LINE__, string fn = __FILE__) @safe
{
import core.exception : AssertError;
import std.algorithm.searching : canFind;
import std.array : appender;
import std.conv : text;
import std.exception : enforce;
import std.format.write : formattedWrite;
auto w = appender!string();
formattedWrite(w, fmt, val);
enforce!AssertError(expected.canFind(w.data),
text("expected one of `", expected, "`, result = `", w.data, "`"), fn, ln);
}
|