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
//! **!!Notice!!** This crate was migrated to [kdbplus](https://crates.io/crates/kdbplus) which has IPC module as well. //! //! Rust crate mirroring the C API header file (`k.h`) for kdb+. The expected usage is to build a //! shared library for kdb+ in Rust. //! //! In order to avoid writing too large `unsafe` block leading to poor optimization, most of native C API functions were provided //! with a wrapper funtion with a bit of ergonomic safety and with intuitive implementation as a trait method. The only exceptions //! are `knk` and `k` which are using elipsis (`...`) as its argument. These functions are provided under `native` namespace with the other C API functions. //! //! # Note //! - This library is for kdb+ version >= 3.0. //! - Meangless C macros are excluded but accessors of an underlying array like `kC`, `kJ`, `kK` etc. are provided in Rust way. //! //! ## Examples //! //! The examples of using C API wrapper are included in `c_api_examples` folder. The examples are mirroring the examples in the document of `kdb_c_api` library and the functions are also used for simple tests of the library. The test is conducted in the `test.q` under `tests/` by loading the functions defined in a shared library built from the examples. //! //! Here are some examples: //! //! ### C API Style //! //! ```rust //! use kdb_c_api::*; //! use kdb_c_api::native::*; //! //! #[no_mangle] //! pub extern "C" fn create_symbol_list(_: K) -> K{ //! unsafe{ //! let mut list=ktn(qtype::SYMBOL as i32, 0); //! js(&mut list, ss(str_to_S!("Abraham"))); //! js(&mut list, ss(str_to_S!("Isaac"))); //! js(&mut list, ss(str_to_S!("Jacob"))); //! js(&mut list, sn(str_to_S!("Josephine"), 6)); //! list //! } //! } //! //! #[no_mangle] //! pub extern "C" fn catchy(func: K, args: K) -> K{ //! unsafe{ //! let result=ee(dot(func, args)); //! if (*result).qtype == qtype::ERROR{ //! println!("error: {}", S_to_str((*result).value.symbol)); //! // Decrement reference count of the error object //! r0(result); //! KNULL //! } //! else{ //! result //! } //! } //! } //! //! #[no_mangle] //! pub extern "C" fn dictionary_list_to_table() -> K{ //! unsafe{ //! let dicts=knk(3); //! let dicts_slice=dicts.as_mut_slice::<K>(); //! for i in 0..3{ //! let keys=ktn(qtype::SYMBOL as i32, 2); //! let keys_slice=keys.as_mut_slice::<S>(); //! keys_slice[0]=ss(str_to_S!("a")); //! keys_slice[1]=ss(str_to_S!("b")); //! let values=ktn(qtype::INT as i32, 2); //! values.as_mut_slice::<I>()[0..2].copy_from_slice(&[i*10, i*100]); //! dicts_slice[i as usize]=xD(keys, values); //! } //! // Format list of dictionary as a table. //! // ([] a: 0 10 20i; b: 0 100 200i) //! k(0, str_to_S!("{[dicts] -1 _ dicts, (::)}"), dicts, KNULL) //! } //! } //! ``` //! //! q can use these functions like this: //! //! ```q //! q)summon:`libc_api_examples 2: (`create_symbol_list; 1) //! q)summon[] //! `Abraham`Isaac`Jacob`Joseph //! q)`Abraham`Isaac`Jacob`Joseph ~ summon[] //! q)catchy: `libc_api_examples 2: (`catchy; 2); //! q)catchy[$; ("J"; "42")] //! 42 //! q)catchy[+; (1; `a)] //! error: type //! q)unfortunate_fact: `libc_api_examples 2: (`dictionary_list_to_table; 1); //! q)unfortunate_fact[] //! a b //! ------ //! 0 0 //! 10 100 //! 20 200 //! ``` //! //! ### Rust Style //! //! The examples below are written without `unsafe` code. You can see how comfortably breathing are the wrapped functions in the code. //! //! ```rust //! use kdb_c_api::*; //! //! #[no_mangle] //! pub extern "C" fn create_symbol_list2(_: K) -> K{ //! let mut list=new_simple_list(qtype::SYMBOL, 0); //! list.push_symbol("Abraham").unwrap(); //! list.push_symbol("Isaac").unwrap(); //! list.push_symbol("Jacob").unwrap(); //! list.push_symbol_n("Josephine", 6).unwrap(); //! list //! } //! //! #[no_mangle] //! fn no_panick(func: K, args: K) -> K{ //! let result=error_to_string(apply(func, args)); //! if result.get_type() == qtype::ERROR{ //! println!("FYI: {}", result.get_symbol().unwrap()); //! // Decrement reference count of the error object which is no longer used. //! decrement_reference_count(result); //! KNULL //! } //! else{ //! println!("success!"); //! result //! } //! } //! //! #[no_mangle] //! pub extern "C" fn create_table2(_: K) -> K{ //! // Build keys //! let keys=new_simple_list(qtype::SYMBOL, 2); //! let keys_slice=keys.as_mut_slice::<S>(); //! keys_slice[0]=internalize(str_to_S!("time")); //! keys_slice[1]=internalize_n(str_to_S!("temperature_and_humidity"), 11); //! //! // Build values //! let values=new_simple_list(qtype::COMPOUND, 2); //! let time=new_simple_list(qtype::TIMESTAMP, 3); //! // 2003.10.10D02:24:19.167018272 2006.05.24D06:16:49.419710368 2008.08.12D23:12:24.018691392 //! time.as_mut_slice::<J>().copy_from_slice(&[119067859167018272_i64, 201766609419710368, 271897944018691392]); //! let temperature=new_simple_list(qtype::FLOAT, 3); //! temperature.as_mut_slice::<F>().copy_from_slice(&[22.1_f64, 24.7, 30.5]); //! values.as_mut_slice::<K>().copy_from_slice(&[time, temperature]); //! //! flip(new_dictionary(keys, values)) //! } //! ``` //! //! And q code is here: //! //! ```q //! q)summon:`libc_api_examples 2: (`create_symbol_list2; 1) //! q)summon[] //! `Abraham`Isaac`Jacob`Joseph //! q)chill: `libc_api_examples 2: (`no_panick; 2); //! q)chill[$; ("J"; "42")] //! success! //! 42 //! q)chill[+; (1; `a)] //! FYI: type //! q)climate_change: libc_api_examples 2: (`create_table2; 1); //! q)climate_change[] //! time temperature //! ----------------------------------------- //! 2003.10.10D02:24:19.167018272 22.1 //! 2006.05.24D06:16:49.419710368 24.7 //! 2008.08.12D23:12:24.018691392 30.5 //! ``` #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// // Load Libraries // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// use std::str; use std::ffi::CStr; use std::os::raw::{c_char, c_double, c_float, c_int, c_longlong, c_short, c_schar, c_uchar, c_void}; use std::convert::TryInto; pub mod native; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// // Global Variables // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// pub mod qtype{ //! This module provides a list of q types. The motivation to contain them in a module is to //! tie them up as related items rather than scattered values. Hence user should use these //! indicators with `qtype::` prefix, e.g., `qtype::BOOL`. use std::os::raw::c_schar; /// Type indicator of q mixed list. /// Access function: `kK` pub const COMPOUND:c_schar=0; /// Type indicator of q bool. /// Access fucntion: `kG` pub const BOOL:c_schar=1; /// Type indicator of q GUID. /// Access function: `kU` pub const GUID:c_schar=2; /// Type indicator of q byte /// Access function: `kG` pub const BYTE:c_schar=4; /// Type indicator of q short. /// Access function: `kH` pub const SHORT:c_schar=5; /// Type indicator of q int. /// Access function: `kI` pub const INT:c_schar=6; /// Type indicator of q long. /// Access function: `kJ` pub const LONG:c_schar=7; /// Type indicator of q real. /// Access function: `kE` pub const REAL:c_schar=8; /// Type indicator of q float. /// Access function: `kF` pub const FLOAT:c_schar=9; /// Type indicator of q char. /// Access function: `kC` pub const CHAR:c_schar=10; /// Type indicator of q symbol. /// Access function: `kS` pub const SYMBOL:c_schar=11; /// Type indicator of q timestamp. /// Access function: `kJ` pub const TIMESTAMP:c_schar=12; /// Type indicator of q month. /// Access function: `kI` pub const MONTH:c_schar=13; /// Type indicator of q date. /// Access function: `kI` pub const DATE:c_schar=14; /// Type indicator of q datetime. /// Access function: `kF` pub const DATETIME:c_schar=15; /// Type indicator of q timespan. /// Access function: `kJ` pub const TIMESPAN:c_schar=16; /// Type indicator of q minute. /// Access function: `kI` pub const MINUTE:c_schar=17; /// Type indicator of q second. /// Access function: `kI` pub const SECOND:c_schar=18; /// Type indicator of q time. /// Access function: `kI` pub const TIME:c_schar=19; /// Type indicator of q table. /// `*(qstruct).k` is q dictionary. pub const TABLE:c_schar=98; /// Type indicator of q dictionary. /// - `kK(x)[0]`: keys /// - `kK(x)[1]`: values pub const DICTIONARY:c_schar=99; /// Type indicator of q foreign object. pub const FOREIGN:c_schar=112; /// Type indicator of q sorted dictionary pub const SORTED_DICTIONARY:c_schar=127; /// Type indicator of q error pub const ERROR:c_schar=-128; /// Type indicator of q general null pub const NULL:c_schar=101; } pub mod qattribute{ //! This module provides a list of q attributes. The motivation to contain them in a module is to //! tie them up as related items rather than scattered values. Hence user should use these //! indicators with `qattribute::` prefix, e.g., `qattribute::UNIQUE`. use std::os::raw::c_char; /// Indicates no attribute is appended on the q object. pub const NONE: c_char=0; /// Sorted attribute, meaning that the q list is sorted in ascending order. pub const SORTED: c_char=1; /// Unique attribute, meaning that each element in the q list has a unique value within the list. pub const UNIQUE: c_char=2; /// Parted attribute, meaning that all the elements with the same value in the q object appear in a chunk. pub const PARTED: c_char=3; /// Grouped attribute, meaning that the elements of the q list are grouped with their indices by values implicitly. pub const GROUPED: c_char=4; } /// `K` nullptr. This value is used as general null returned value (`(::)`). /// # Example /// ``` /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn vanity(_: K) -> K{ /// println!("Initialized something, probably it is your mindset."); /// KNULL /// } /// ``` pub const KNULL:K=0 as K; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// // Macros // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //%% Utility %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Convert `&str` to `S` (null-terminated character array). /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn pingpong(_: K) -> K{ /// unsafe{native::k(0, str_to_S!("ping"), new_int(77), KNULL)} /// } /// ``` /// ```q /// q)ping:{[int] `$string[int], "_pong!!"} /// q)pingpong: `libc_api_examples 2: (`pingpong; 1); /// q)pingpong[] /// `77_pong!! /// ``` /// # Note /// This macro cannot be created as a function due to freeing resource of Rust (not sure). #[macro_export] macro_rules! str_to_S { ($string: expr) => { [$string.as_bytes(), &[b'\0']].concat().as_mut_ptr() as S }; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// // Structs // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //%% Alias %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// `char*` in C. Also used to access symbol of q. pub type S = *mut c_char; /// `const char*` in C. pub type const_S = *const c_char; /// `char` in C. Also used to access char of q. pub type C = c_char; /// `unsigned char` in C. Also used to access byte of q. pub type G = c_uchar; /// `i16` in C. Also used to access short of q. pub type H = c_short; /// `i32` in C. Also used to access int and compatible types (month, date, minute, second and time) of q. pub type I = c_int; /// `i64` in C. Also used to access long and compatible types (timestamp and timespan) of q. pub type J = c_longlong; /// `f32` in C. Also used to access real of q. pub type E = c_float; /// `f64` in C. Also used to access float and datetime of q. pub type F = c_double; /// `void` in C. pub type V = c_void; //%% U %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Struct representing 16-bytes GUID. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct U{ pub guid: [G; 16] } //%% K %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Underlying list value of q object. /// # Note /// Usually this struct does not need to be accessed this struct directly unless user wants to /// access via a raw pointer for non-trivial stuff. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct k0_list_info{ /// Length of the list. pub n: J, /// Pointer referring to the head of the list. This pointer will be interpreted /// as various types when accessing `K` object to edit the list with /// [`as_mut_slice`](trait.KUtility.html#tymethod.as_mut_slice). pub G0: [G; 1] } /// Underlying atom value of q object. /// # Note /// Usually this struct does not need to be accessed directly unless user wants to /// access via a raw pointer for non-trivial stuff. #[derive(Clone, Copy)] #[repr(C)] pub union k0_inner{ /// Byte type holder. pub byte: G, /// Short type holder. pub short: H, /// Int type holder. pub int: I, /// Long type older. pub long: J, /// Real type holder. pub real: E, /// Float type holder. pub float: F, /// Symbol type holder. pub symbol: S, /// Table type holder. pub table: *mut k0, /// List type holder. pub list: k0_list_info } /// Underlying struct of `K` object. #[repr(C)] #[derive(Clone, Copy)] pub struct k0{ /// For internal usage. pub m: c_schar, /// For internal usage. pub a: c_schar, /// Type indicator. pub qtype: c_schar, /// Attribute of list. pub attribute: C, /// Reference count of the object. pub refcount: I, /// Underlying value. pub value: k0_inner } /// Struct representing q object. pub type K=*mut k0; //%% KList %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ pub trait KUtility{ /// Derefer `K` as a mutable slice of the specified type. The supported types are: /// - `G`: Equivalent to C API macro `kG`. /// - `H`: Equivalent to C API macro `kH`. /// - `I`: Equivalent to C API macro `kI`. /// - `J`: Equivalent to C API macro `kJ`. /// - `E`: Equivalent to C API macro `kE`. /// - `F`: Equivalent to C API macro `kF`. /// - `C`: Equivalent to C API macro `kC`. /// - `S`: Equivalent to C API macro `kS`. /// - `K`: Equivalent to C API macro `kK`. /// # Example /// ``` /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn modify_long_list_a_bit(long_list: K) -> K{ /// if long_list.len() >= 2{ /// // Derefer as a mutable i64 slice. /// long_list.as_mut_slice::<J>()[1]=30000_i64; /// // Increment the counter to reuse on q side. /// increment_reference_count(long_list) /// } /// else{ /// new_error("this list is not long enough. how ironic...\0") /// } /// } /// ``` /// ```q /// q)ironic: `libc_api_examples 2: (`modify_long_list_a_bit; 1); /// q)list:1 2 3; /// q)ironic list /// 1 30000 3 /// q)ironic enlist 1 /// ``` /// # Note /// Intuitively the parameter should be `&mut self` but it restricts a manipulating /// `K` objects in the form of slice simultaneously. As copying a pointer is not /// an expensive operation, using `self` should be fine. fn as_mut_slice<'a, T>(self) -> &'a mut[T]; /// Get an underlying q byte. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_bool(atom: K) -> K{ /// match atom.get_bool(){ /// Ok(boolean) => { /// println!("bool: {}", boolean); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_boole: `libc_api_examples 2: (`print_bool; 1); /// q)print_bool[1b] /// bool: true /// ``` fn get_bool(&self) -> Result<bool, &'static str>; /// Get an underlying q byte. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_guid(atom: K) -> K{ /// match atom.get_guid(){ /// Ok(guid) => { /// let strguid=guid.iter().map(|b| format!("{:02x}", b)).collect::<String>(); /// println!("GUID: {}-{}-{}-{}-{}", &strguid[0..4], &strguid[4..6], &strguid[6..8], &strguid[8..10], &strguid[10..16]); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_guid: `libc_api_examples 2: (`print_guid; 1); /// q)guid: first 1?0Ng; /// q)print_guid[guid] /// GUID: 8c6b-8b-64-68-156084 /// ``` fn get_guid(&self) -> Result<[u8; 16], &'static str>; /// Get an underlying q byte. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_byte(atom: K) -> K{ /// match atom.get_byte(){ /// Ok(byte) => { /// println!("byte: {:#4x}", byte); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_byte: `libc_api_examples 2: (`print_byte; 1); /// q)print_byte[0xc4] /// byte: 0xc4 /// ``` fn get_byte(&self) -> Result<u8, &'static str>; /// Get an underlying q short. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_short(atom: K) -> K{ /// match atom.get_short(){ /// Ok(short) => { /// println!("short: {}", short); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_short: `libc_api_examples 2: (`print_short; 1); /// q)print_short[10h] /// short: 10 /// ``` fn get_short(&self) -> Result<i16, &'static str>; /// Get an underlying q int. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_int(atom: K) -> K{ /// match atom.get_int(){ /// Ok(int) => { /// println!("int: {}", int); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_int: `libc_api_examples 2: (`print_int; 1); /// q)print_int[03:57:20] /// int: 14240 /// ``` fn get_int(&self) -> Result<i32, &'static str>; /// Get an underlying q long. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_long(atom: K) -> K{ /// match atom.get_long(){ /// Ok(long) => { /// println!("long: {}", long); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_long: `libc_api_examples 2: (`print_long; 1); /// q)print_long[2000.01.01D12:00:00.123456789] /// long: 43200123456789 /// ``` fn get_long(&self) -> Result<i64, &'static str>; /// Get an underlying q real. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_real(atom: K) -> K{ /// match atom.get_real(){ /// Ok(real) => { /// println!("real: {}", real); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_real: `libc_api_examples 2: (`print_real; 1); /// q)print_real[193810.32e] /// real: 193810.31 /// ``` fn get_real(&self) -> Result<f32, &'static str>; /// Get an underlying q float. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_float(atom: K) -> K{ /// match atom.get_float(){ /// Ok(float) => { /// println!("float: {:.8}", float); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_float: `libc_api_examples 2: (`print_float; 1); /// q)print_float[2002.01.12T10:03:45.332] /// float: 742.41927468 /// ``` fn get_float(&self) -> Result<f64, &'static str>; /// Get an underlying q char. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_char(atom: K) -> K{ /// match atom.get_char(){ /// Ok(character) => { /// println!("char: \"{}\"", character); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_char: `libc_api_examples 2: (`print_char; 1); /// q)print_char["k"] /// char: "k" /// ``` fn get_char(&self) -> Result<char, &'static str>; /// Get an underlying q symbol. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_symbol2(atom: K) -> K{ /// match atom.get_symbol(){ /// Ok(symbol) => { /// println!("symbol: `{}", symbol); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_symbol2: `libc_api_examples 2: (`print_symbol2; 1); /// q)print_symbol2[`locust] /// symbol: `locust /// ``` fn get_symbol(&self) -> Result<&str, &'static str>; /// Get an underlying q string as `&str`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_string(string: K) -> K{ /// match string.get_str(){ /// Ok(string_) => { /// println!("string: \"{}\"", string_); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_string: `libc_api_examples 2: (`print_string; 1); /// q)print_string["gnat"] /// string: "gnat" /// ``` fn get_str(&self) -> Result<&str, &'static str>; /// Get an underlying q string as `String`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_string2(string: K) -> K{ /// match string.get_string(){ /// Ok(string_) => { /// println!("string: \"{}\"", string_); /// KNULL /// }, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)print_string: `libc_api_examples 2: (`print_string; 1); /// q)print_string["grasshopper"] /// string: "grasshopper" /// ``` fn get_string(&self) -> Result<String, &'static str>; /// Get a flipped underlying q table as `K` (dictionary). /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn hidden_key(table: K) -> K{ /// match table.get_dictionary(){ /// Ok(dictionary) => dictionary.as_mut_slice::<K>()[0].q_ipc_encode(3).unwrap(), /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)perceive_the_man: `libc_api_examples 2: (`hidden_key; 1); /// q)perceive_the_man ([] t: `timestamp$.z.p+1e9*til 9; chr:"ljppkgfgs"; is: 7 8 12 14 21 316 400 1000 6000i) /// 0x01000000170000000b0003000000740063687200697300 /// ``` /// # Note /// This method is provided because the ony way to examine the value of table type is to access the underlying dictionary (flipped table). /// Also when some serialization is necessary for a table, you can reuse a serializer for a dictionary if it is already provided. Actually /// when q serialize a table object with `-8!` (q function) or `b9` (C code), it just serializes the underlying dictionary with an additional /// marker indicating a table type. fn get_dictionary(&self) -> Result<K, &'static str>; /// Get an attribute of a q object. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn murmur(list: K) -> K{ /// match list.get_attribute(){ /// qattribute::SORTED => { /// new_string("Clean") /// }, /// qattribute::UNIQUE => { /// new_symbol("Alone") /// }, /// _ => KNULL /// } /// } /// ``` fn get_attribute(&self) -> C; /// Get a reference count of a q object. fn get_refcount(&self) -> I; /// Append a q list object to a q list. /// Returns a pointer to the (potentially reallocated) `K` object. /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn concat_list2(mut list1: K, list2: K) -> K{ /// if let Err(err) = list1.append(list2){ /// new_error(err) /// } /// else{ /// increment_reference_count(list1) /// } /// } /// ``` /// ```q /// q)plunder: `libc_api_examples 2: (`concat_list2; 2); /// q)plunder[(::; `metals; `fire); ("clay"; 316)] /// :: /// `metals /// `fire /// "clay" /// 316 /// q)plunder[1 2 3; 4 5] /// 1 2 3 4 5 /// q)plunder[`a`b`c; `d`e] /// `a`b`c`d`e /// ``` fn append(&mut self, list: K)->Result<K, &'static str>; /// Add a q object to a q compound list. /// Returns a pointer to the (potentially reallocated) `K` object. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_compound_list(int: K) -> K{ /// let mut list=new_simple_list(qtype::COMPOUND, 0); /// for i in 0..5{ /// list.push(new_long(i)).unwrap(); /// } /// list.push(increment_reference_count(int)).unwrap(); /// list /// } /// ``` /// ```q /// q)nums: `libc_api_examples 2: (`create_compound_list2; 1); /// q)nums[5i] /// 0 /// 1 /// 2 /// 3 /// 4 /// 5i /// ``` /// # Note /// In this example we did not allocate an array as `new_simple_list(qtype::COMPOUND, 0)` to use `push`. /// As `new_simple_list` initializes the internal list size `n` with its argument, preallocating memory with `new_simple_list` and /// then using `push` will crash. If you want to allocate a memory in advance, you can substitute a value /// after converting the q list object into a slice with [`as_mut_slice`](rait.KUtility.html#tymethod.as_mut_slice). fn push(&mut self, atom: K)->Result<K, &'static str>; /// Add a raw value to a q simple list and returns a pointer to the (potentially reallocated) `K` object. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_simple_list2(_: K) -> K{ /// let mut list=new_simple_list(qtype::DATE, 0); /// for i in 0..5{ /// list.push_raw(i).unwrap(); /// } /// list /// } /// ``` /// ```q /// q)simple_is_the_best: `lic_api_example 2: (`create_simple_list2; 1); /// q)simple_is_the_best[] /// 2000.01.01 2000.01.02 2000.01.03 2000.01.04 2000.01.05 /// ``` /// # Note /// - Concrete type of `T` is not checked. Its type must be either of `I`, `J` and `F` and it must be compatible /// with the list type. For example, timestamp list requires `J` type atom. /// - For symbol list, use [`push_symbol`](#fn.push_symbol) or [`push_symbol_n`](#fn.push_symbol_n). fn push_raw<T>(&mut self, atom: T)->Result<K, &'static str>; /// Add an internalized char array to symbol list. /// Returns a pointer to the (potentially reallocated) `K` object. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_symbol_list2(_: K) -> K{ /// let mut list=new_simple_list(qtype::SYMBOL, 0); /// list.push_symbol("Abraham").unwrap(); /// list.push_symbol("Isaac").unwrap(); /// list.push_symbol("Jacob").unwrap(); /// list.push_symbol_n("Josephine", 6).unwrap(); /// list /// } /// ``` /// ```q /// q)summon:`libc_api_examples 2: (`create_symbol_list2; 1) /// q)summon[] /// `Abraham`Isaac`Jacob`Joseph /// q)`Abraham`Isaac`Jacob`Joseph ~ summon[] /// 1b /// ``` /// # Note /// In this example we did not allocate an array as `new_simple_list(qtype::SYMBOL as I, 0)` to use `push_symbol`. /// As `new_simple_list` initializes the internal list size `n` with its argument, preallocating memory with `new_simple_list` /// and then using `push_symbol` will crash. If you want to allocate a memory in advance, you can substitute a value /// after converting the q list object into a slice with [`as_mut_slice`](trait.KUtility.html#tymethod.as_mut_slice). fn push_symbol(&mut self, symbol: &str)->Result<K, &'static str>; /// Add an internalized char array to symbol list. /// Returns a pointer to the (potentially reallocated) `K` object. /// # Example /// See the example of [`push_symbol`](#fn.push_symbol). fn push_symbol_n(&mut self, symbol: &str, n: I)->Result<K, &'static str>; /// Get a length of the list. More specifically, a value of `k0.value.list.n` for list types. /// Otherwise 2 for table and 1 for atom and null. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn numbers(obj: K) -> K{ /// let count=format!("{} people are in numbers", obj.len()); /// new_string(&count) /// } /// ``` /// ```q /// q)census: `libc_api_examples 2: (`numbers; 1); /// q)census[(::)] /// "1 people are in numbers" /// q)census[til 4] /// "4 people are in numbers" /// q)census[`a`b!("many"; `split`asunder)] /// "2 people are in numbers" /// q)census[([] id: til 1000)] /// "1000 people are in numbers" /// ``` fn len(&self) -> i64; /// Get a type of `K` object. fn get_type(&self) -> i8; /// Set a type of `K` object. /// # Example /// See the example of [`load_as_q_function](fn.load_as_q_function.html). fn set_type(&self, qtype: i8); /// Serialize q object and return serialized q byte list object on success: otherwise null. /// Mode is either of: /// - -1: Serialize within the same process. /// - 1: retain enumerations, allow serialization of timespan and timestamp: Useful for passing data between threads /// - 2: unenumerate, allow serialization of timespan and timestamp /// - 3: unenumerate, compress, allow serialization of timespan and timestamp /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn encrypt(object: K)->K{ /// match object.q_ipc_encode(3){ /// Ok(bytes) => bytes, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)disguise: `libc_api_examples 2: (`encrypt; 1); /// q)list: (til 3; "abc"; 2018.02.18D04:30:00.000000000; `revive); /// q)disguise list /// 0x010000004600000000000400000007000300000000000000000000000100000000000000020.. /// ``` fn q_ipc_encode(&self, mode: I) -> Result<K, &'static str>; /// Deserialize a bytes into q object. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn decrypt(bytes: K)->K{ /// match bytes.q_ipc_decode(){ /// Ok(object) => object, /// Err(error) => new_error(error) /// } /// } /// ``` /// ```q /// q)uncover: `libc_api_examples 2: (`decrypt; 1); /// q)uncover -8!"What is the purpose of CREATION?" /// "What is the purpose of CREATION?" /// ``` fn q_ipc_decode(&self) -> Result<K, &'static str>; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// // Implementation // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //%% U %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ impl U{ /// Create 16-byte GUID object. pub fn new(guid: [u8; 16]) -> Self{ U{guid:guid} } } //%% K %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ unsafe impl Send for k0_inner{} unsafe impl Send for k0{} impl KUtility for K{ #[inline] fn as_mut_slice<'a, T>(self) -> &'a mut[T]{ unsafe{ std::slice::from_raw_parts_mut((*self).value.list.G0.as_mut_ptr() as *mut T, (*self).value.list.n as usize) } } #[inline] fn get_bool(&self) -> Result<bool, &'static str>{ match unsafe{(**self).qtype}.saturating_mul(-1){ qtype::BOOL => Ok(unsafe{(**self).value.byte != 0}), _ => Err("not a bool\0") } } #[inline] fn get_guid(&self) -> Result<[u8; 16], &'static str>{ match unsafe{(**self).qtype}.saturating_mul(-1){ qtype::GUID => { Ok(unsafe{std::slice::from_raw_parts((**self).value.list.G0.as_ptr(), 16)}.try_into().unwrap()) }, _ => Err("not a GUID\0") } } #[inline] fn get_byte(&self) -> Result<u8, &'static str>{ match unsafe{(**self).qtype}.saturating_mul(-1){ qtype::BYTE => Ok(unsafe{(**self).value.byte}), _ => Err("not a byte\0") } } #[inline] fn get_short(&self) -> Result<i16, &'static str>{ match unsafe{(**self).qtype}.saturating_mul(-1){ qtype::SHORT => Ok(unsafe{(**self).value.short}), _ => Err("not a short\0") } } #[inline] fn get_int(&self) -> Result<i32, &'static str>{ match unsafe{(**self).qtype}.saturating_mul(-1){ qtype::INT | qtype::MONTH | qtype::DATE | qtype::MINUTE | qtype::SECOND | qtype::TIME => Ok(unsafe{(**self).value.int}), _ => Err("not an int\0") } } #[inline] fn get_long(&self) -> Result<i64, &'static str>{ match unsafe{(**self).qtype}.saturating_mul(-1){ qtype::LONG | qtype::TIMESTAMP | qtype::TIMESPAN => Ok(unsafe{(**self).value.long}), _ => Err("not a long\0") } } #[inline] fn get_real(&self) -> Result<f32, &'static str>{ match unsafe{(**self).qtype}.saturating_mul(-1){ qtype::REAL => Ok(unsafe{(**self).value.real}), _ => Err("not a real\0") } } #[inline] fn get_float(&self) -> Result<f64, &'static str>{ match unsafe{(**self).qtype}.saturating_mul(-1){ qtype::FLOAT | qtype::DATETIME => Ok(unsafe{(**self).value.float}), _ => Err("not a float\0") } } #[inline] fn get_char(&self) -> Result<char, &'static str>{ match unsafe{(**self).qtype}.saturating_mul(-1){ qtype::CHAR => Ok(unsafe{(**self).value.byte as char}), _ => Err("not a char\0") } } #[inline] fn get_symbol(&self) -> Result<&str, &'static str>{ if (unsafe{(**self).qtype} == -qtype::SYMBOL) || (unsafe{(**self).qtype} == qtype::ERROR){ Ok(S_to_str(unsafe{(**self).value.symbol})) } else{ Err("not a symbol\0") } } #[inline] fn get_str(&self) -> Result<&str, &'static str>{ match unsafe{(**self).qtype}{ qtype::CHAR => { Ok(unsafe{str::from_utf8_unchecked_mut(self.as_mut_slice::<G>())}) }, _ => Err("not a string\0") } } #[inline] fn get_string(&self) -> Result<String, &'static str>{ match unsafe{(**self).qtype}{ qtype::CHAR => { Ok(unsafe{String::from_utf8_unchecked(self.as_mut_slice::<G>().to_vec())}) }, _ => Err("not a string\0") } } #[inline] fn get_dictionary(&self) -> Result<K, &'static str>{ match unsafe{(**self).qtype}{ qtype::TABLE => { Ok(unsafe{(**self).value.table}) }, _ => Err("not a table\0") } } #[inline] fn get_attribute(&self) -> i8{ unsafe{(**self).attribute} } #[inline] fn get_refcount(&self) -> i32{ unsafe{(**self).refcount} } #[inline] fn append(&mut self, list: K)->Result<K, &'static str>{ if unsafe{(**self).qtype} >= 0 && unsafe{(**self).qtype} == unsafe{(*list).qtype}{ Ok(unsafe{native::jv(self, list)}) } else{ Err("not a list or types do not match\0") } } #[inline] fn push(&mut self, atom: K)->Result<K, &'static str>{ if unsafe{(**self).qtype} == 0 { Ok(unsafe{native::jk(self, atom)}) } else{ Err("not a list or types do not match\0") } } #[inline] fn push_raw<T>(&mut self, mut atom: T)->Result<K, &'static str>{ match unsafe{(**self).qtype}{ _t@1..=19 => Ok(unsafe{native::ja(self, std::mem::transmute::<*mut T, *mut V>(&mut atom))}), _ => Err("not a simple list or types do not match\0") } } #[inline] fn push_symbol(&mut self, symbol: &str)->Result<K, &'static str>{ if unsafe{(**self).qtype} == qtype::SYMBOL { Ok(unsafe{native::js(self, native::ss(str_to_S!(symbol)))}) } else{ Err("not a symbol list\0") } } #[inline] fn push_symbol_n(&mut self, symbol: &str, n: I)->Result<K, &'static str>{ if unsafe{(**self).qtype} == qtype::SYMBOL { Ok(unsafe{native::js(self, native::sn(str_to_S!(symbol), n))}) } else{ Err("not a symbol list or types do not match\0") } } #[inline] fn len(&self) -> i64{ unsafe{ if (**self).qtype < 0 || (**self).qtype == qtype::NULL{ // Atom or (::) 1 } else if (**self).qtype == qtype::TABLE{ // Table // Access underlying table (dictionary structure) and retrieve values of the dictionary. // The values (columns) is assured to be a list of lists as it is a table. so cast it to list of `K`. // Size of the table is a length of the first column. (*((**self).value.table).as_mut_slice::<K>()[1].as_mut_slice::<K>()[0]).value.list.n } else if (**self).qtype == qtype::DICTIONARY{ // Dictionary // Access to keys of the dictionary and retrieve its length. (*(*self).as_mut_slice::<K>()[0]).value.list.n } else{ // List (**self).value.list.n } } } #[inline] fn get_type(&self) -> i8{ unsafe{(**self).qtype} } #[inline] fn set_type(&self, qtype: i8){ unsafe{(**self).qtype=qtype}; } #[inline] fn q_ipc_encode(&self, mode: I) -> Result<K, &'static str>{ let result=error_to_string(unsafe{ native::b9(mode, *self) }); match unsafe{(*result).qtype}{ qtype::ERROR => { decrement_reference_count(result); Err("failed to encode\0") }, _ => Ok(result) } } #[inline] fn q_ipc_decode(&self) -> Result<K, &'static str>{ match unsafe{(**self).qtype}{ qtype::BYTE => { let result=error_to_string(unsafe{ native::d9(*self) }); match unsafe{(*result).qtype}{ qtype::ERROR => { decrement_reference_count(result); Err("failed to decode\0") }, _ => Ok(result) } }, _ => Err("not bytes\0") } } } impl k0{ /// Derefer `k0` as a mutable slice. For supported types, see [`as_mut_slice`](trait.KUtility.html#tymethod.as_mut_slice). /// # Note /// Used if `K` needs to be sent to another thread. `K` cannot implement `Send` and therefore /// its inner struct must be sent instead. /// # Example /// See the example of [`setm`](native/fn.setm.html). #[inline] pub fn as_mut_slice<'a, T>(&mut self) -> &'a mut[T]{ unsafe{ std::slice::from_raw_parts_mut(self.value.list.G0.as_mut_ptr() as *mut T, self.value.list.n as usize) } } } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// // Utility // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //%% Utility %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Convert `S` to `&str`. This function is intended to convert symbol type (null-terminated char-array) to `str`. /// # Extern /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn print_symbol(symbol: K) -> K{ /// unsafe{ /// if (*symbol).qtype == -qtype::SYMBOL{ /// println!("symbol: `{}", S_to_str((*symbol).value.symbol)); /// } /// // return null /// KNULL /// } /// } /// ``` /// ```q /// q)print_symbol:`libc_api_examples 2: (`print_symbol; 1) /// q)a:`kx /// q)print_symbol a /// symbol: `kx /// ``` #[inline] pub fn S_to_str<'a>(cstring: S) -> &'a str{ unsafe{ CStr::from_ptr(cstring).to_str().unwrap() } } /// Convert null-terminated `&str` to `S`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn pingpong2(_: K) -> K{ /// unsafe{native::k(0, null_terminated_str_to_S("ping\0"), new_int(77), KNULL)} /// } /// ``` /// ```q /// q)ping:{[int] `$string[int], "_pong!!"}; /// q)pingpong: `libc_api_examples 2: (`pingpong2; 1); /// q)pingpong[] /// `77_pong!! /// ``` #[inline] pub fn null_terminated_str_to_S(string: &str) -> S { unsafe{ CStr::from_bytes_with_nul_unchecked(string.as_bytes()).as_ptr() as S } } /// Convert null terminated `&str` into `const_S`. Expected usage is to build /// a q error object with `krr`. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// pub extern "C" fn must_be_int2(obj: K) -> K{ /// unsafe{ /// if (*obj).qtype != -qtype::INT{ /// krr(null_terminated_str_to_const_S("not an int\0")) /// } /// else{ /// KNULL /// } /// } /// } /// ``` /// ```q /// q)check:`libc_api_examples 2: (`must_be_int; 1) /// q)a:100 /// q)check a /// 'not an int /// [0] check a /// ^ /// q)a:42i /// q)check a /// ``` pub fn null_terminated_str_to_const_S(string: &str) -> const_S { string.as_bytes().as_ptr() as const_S } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// // Re-export // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //%% Constructor %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Constructor of q bool object. Relabeling of `kb`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_bool(_: K) -> K{ /// new_bool(0) /// } /// ``` /// ```q /// q)no: `libc_api_examples 2: (`create_bool; 1); /// q)no[] /// 0b /// ``` #[inline] pub fn new_bool(boolean: I) -> K{ unsafe{ native::kb(boolean) } } /// Constructor of q GUID object. Relabeling of `ku`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_guid(_: K) -> K{ /// new_guid([0x1e_u8, 0x11, 0x17, 0x0c, 0x42, 0x24, 0x25, 0x2c, 0x1c, 0x14, 0x1e, 0x22, 0x4d, 0x3d, 0x46, 0x24]) /// } /// ``` /// ```q /// q)create_guid: `libc_api_examples 2: (`create_guid; 1); /// q)create_guid[] /// 1e11170c-4224-252c-1c14-1e224d3d4624 /// ``` #[inline] pub fn new_guid(guid: [G; 16]) -> K{ unsafe{ native::ku(U::new(guid)) } } /// Constructor of q byte object. Relabeling of `kg`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_byte(_: K) -> K{ /// new_byte(0x3c) /// } /// ``` /// ```q /// q)create_byte: `libc_api_examples 2: (`create_byte; 1); /// q)create_byte[] /// 0x3c /// ``` #[inline] pub fn new_byte(byte: I) -> K{ unsafe{ native::kg(byte) } } /// Constructor of q short object. Relabeling of `kh`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_short(_: K) -> K{ /// new_short(-144) /// } /// ``` /// ```q /// q)shortage: `libc_api_examples 2: (`create_short; 1); /// q)shortage[] /// -144h /// ``` #[inline] pub fn new_short(short: I) -> K{ unsafe{ native::kh(short) } } /// Constructor of q int object. Relabeling of `ki`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_int(_: K) -> K{ /// new_int(86400000) /// } /// ``` /// ```q /// q)trvial: `libc_api_examples 2: (`create_int; 1); /// q)trivial[] /// 86400000i /// ``` #[inline] pub fn new_int(int: I) -> K{ unsafe{ native::ki(int) } } /// Constructor of q long object. Relabeling of `kj`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_long(_: K) -> K{ /// new_long(-668541276001729000) /// } /// ``` /// ```q /// q)lengthy: `libc_api_examples 2: (`create_long; 1); /// q)lengthy[] /// -668541276001729000 /// ``` #[inline] pub fn new_long(long: J) -> K{ unsafe{ native::kj(long) } } /// Constructor of q real object. Relabeling of `ke`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_real(_: K) -> K{ /// new_real(0.00324) /// } /// ``` /// ```q /// q)reality: `libc_api_examples 2: (`create_real; 1); /// q)reality[] /// 0.00324e /// ``` #[inline] pub fn new_real(real: F) -> K{ unsafe{ native::ke(real) } } /// Constructor of q float object. Relabeling of `kf`. /// # Example /// ``` /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_float(_: K) -> K{ /// new_float(-6302.620) /// } /// ``` /// ```q /// q)coffee_float: `libc_api_examples 2: (`create_float; 1); /// q)coffee_float[] /// -6302.62 /// ``` #[inline] pub fn new_float(float: F) -> K{ unsafe{ native::kf(float) } } /// Constructor of q char object. Relabeling of `kc`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_char2(_: K) -> K{ /// new_char('t') /// } /// ``` /// ```q /// q)heavy: `libc_api_examples 2: (`create_char2; 1); /// q)heavy[] /// "t" /// ``` #[inline] pub fn new_char(character: char) -> K{ unsafe{ native::kc(character as I) } } /// Constructor of q symbol object. Relabeling of `ks`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_symbol2(_: K) -> K{ /// new_symbol("symbolic") /// } /// ``` /// ```q /// q)hard: `libc_api_examples 2: (`create_symbol2; 1); /// q)hard[] /// `symbolic /// q)`symbolic ~ hard[] /// 1b /// ``` #[inline] pub fn new_symbol(symbol: &str) -> K{ unsafe{ native::ks(str_to_S!(symbol)) } } /// Constructor of q timestamp from elapsed time in nanoseconds since kdb+ epoch (`2000.01.01`). Relabeling of `ktj`. /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_timestamp2(_: K) -> K{ /// // 2015.03.16D00:00:00:00.000000000 /// new_timestamp(479779200000000000) /// } /// ``` /// ```q /// q)stamp: `libc_api_examples 2: (`create_timestamp2; 1); /// q)stamp[] /// 2015.03.16D00:00:00.000000000 /// ``` #[inline] pub fn new_timestamp(nanoseconds: J) -> K{ unsafe{ native::ktj(-qtype::TIMESTAMP as I, nanoseconds) } } /// Create a month object from the number of months since kdb+ epoch (`2000.01.01`). /// This is a complememtal constructor of missing month type. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_month(_: K) -> K{ /// // 2010.07m /// new_month(126) /// } /// ``` /// ```q /// q)create_month: `libc_api_examples 2: (`create_month; 1); /// q)create_month[] /// 2010.07m /// ``` #[inline] pub fn new_month(months: I) -> K{ unsafe{ let month=native::ka(-qtype::MONTH as I); (*month).value.int=months; month } } /// Constructor of q date object. Relabeling of `kd`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_date(_: K) -> K{ /// // 1999.12.25 /// new_date(-7) /// } /// ``` /// ```q /// q)nostradamus: `libc_api_examples 2: (`create_date; 1); /// q)nostradamus[] /// 1999.12.25 /// ``` #[inline] pub fn new_date(days: I) -> K{ unsafe{ native::kd(days) } } /// Constructor of q datetime object from the number of days since kdb+ epoch (`2000.01.01`). Relabeling of `kz`. /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_datetime(_: K) -> K{ /// // 2015.03.16T12:00:00:00.000 /// new_datetime(5553.5) /// } /// ``` /// ```q /// q)omega_date: libc_api_examples 2: (`create_datetime; 1); /// q)omega_date[] /// 2015.03.16T12:00:00.000 /// ``` #[inline] pub fn new_datetime(days: F) -> K{ unsafe{ native::kz(days) } } /// Constructor of q timespan object from nanoseconds. Relabeling of `ktj`. /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_timespan2(_: K) -> K{ /// // -1D01:30:00.001234567 /// new_timespan(-91800001234567) /// } /// ``` /// ```q /// q)duration: libc_api_examples 2: (`create_timespan2; 1); /// q)duration[] /// -1D01:30:00.001234567 /// ``` #[inline] pub fn new_timespan(nanoseconds: J) -> K{ unsafe{ native::ktj(-qtype::TIMESPAN as I, nanoseconds) } } /// Create a month object. This is a complememtal constructor of /// missing minute type. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_minute(_: K) -> K{ /// // 10:40 /// new_minute(640) /// } /// ``` /// ```q /// q)minty: `libc_api_examples 2: (`create_minute; 1); /// q)minty[] /// 10:40 /// ``` #[inline] pub fn new_minute(minutes: I) -> K{ unsafe{ let minute=native::ka(-qtype::MINUTE as I); (*minute).value.int=minutes; minute } } /// Create a month object. This is a complememtal constructor of /// missing second type. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_second(_: K) -> K{ /// // -02:00:00 /// new_second(-7200) /// } /// ``` /// ```q /// q)third: `libc_api_examples 2: (`create_second; 1); /// q)third[] /// -02:00:00 /// ``` #[inline] pub fn new_second(seconds: I) -> K{ unsafe{ let second=native::ka(-qtype::SECOND as I); (*second).value.int=seconds; second } } /// Constructor of q time object. Relabeling of `kt`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_time(_: K) -> K{ /// // -01:30:00.123 /// new_time(-5400123) /// } /// ``` /// ```q /// q)ancient: libc_api_examples 2: (`create_time; 1); /// q)ancient[] /// -01:30:00.123 /// ``` #[inline] pub fn new_time(milliseconds: I) -> K{ unsafe{ native::kt(milliseconds) } } /// Constructor of q simple list. /// # Example /// See the example of [`new_dictionary`](fn.new_dictionary.html). #[inline] pub fn new_simple_list(qtype: i8, length: J) -> K{ unsafe{ native::ktn(qtype as I, length) } } /// Constructor of q string object. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_string(_: K) -> K{ /// new_string("this is a text.") /// } /// ``` /// ```q /// q)text: libc_api_examples 2: (`create_string; 1); /// q)text[] /// "this is a text." /// ``` #[inline] pub fn new_string(string: &str) -> K{ unsafe{ native::kp(str_to_S!(string)) } } /// Constructor if q string object with a fixed length. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_string2(_: K) -> K{ /// new_string_n("The meeting was too long and I felt it s...", 24) /// } /// ``` /// ```q /// q)speak_inwardly: libc_api_examples 2: (`create_string2; 1); /// q)speak_inwardly[] /// "The meeting was too long" /// ``` #[inline] pub fn new_string_n(string: &str, length: J) -> K{ unsafe{ native::kpn(str_to_S!(string), length) } } /// Constructor of q dictionary object. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_dictionary() -> K{ /// let keys=new_simple_list(qtype::INT, 2); /// keys.as_mut_slice::<I>()[0..2].copy_from_slice(&[0, 1]); /// let values=new_simple_list(qtype::COMPOUND, 2); /// let date_list=new_simple_list(qtype::DATE, 3); /// // 2000.01.01 2000.01.02 2000.01.03 /// date_list.as_mut_slice::<I>()[0..3].copy_from_slice(&[0, 1, 2]); /// let string=new_string("I'm afraid I would crash the application..."); /// values.as_mut_slice::<K>()[0..2].copy_from_slice(&[date_list, string]); /// new_dictionary(keys, values) /// } /// ``` /// ```q /// q)create_dictionary: `libc_api_examples 2: (`create_dictionary; 1); /// q)create_dictionary[] /// 0| 2000.01.01 2000.01.02 2000.01.03 /// 1| "I'm afraid I would crash the application..." /// ``` #[inline] pub fn new_dictionary(keys: K, values: K) -> K{ unsafe{ native::xD(keys, values) } } /// Constructor of q error. The input must be null-terminated. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// pub extern "C" fn thai_kick(_: K) -> K{ /// new_error("Thai kick unconditionally!!\0") /// } /// ``` /// ```q /// q)monstrous: `libc_api_examples 2: (`thai_kick; 1); /// q)monstrous[] /// 'Thai kick unconditionally!! /// [0] monstrous[] /// ^ /// ``` #[inline] pub fn new_error(message: &str) -> K{ unsafe{ native::krr(null_terminated_str_to_const_S(message)) } } /// Similar to `new_error` but this function appends a system-error message to string `S` before passing it to internal `krr`. /// The input must be null-terminated. #[inline] pub fn new_error_os(message: &str) -> K{ unsafe{ native::orr(null_terminated_str_to_const_S(message)) } } /// Convert an error object into usual K object which has the error string in the field `s`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// extern "C" fn no_panick(func: K, args: K) -> K{ /// let result=error_to_string(apply(func, args)); /// if result.get_type() == qtype::ERROR{ /// println!("FYI: {}", result.get_symbol().unwrap()); /// // Decrement reference count of the error object which is no longer used. /// decrement_reference_count(result); /// KNULL /// } /// else{ /// result /// } /// } /// ``` /// ```q /// q)chill: `libc_api_examples 2: (`no_panick; 2); /// q)chill[$; ("J"; "42")] /// success! /// 42 /// q)chill[+; (1; `a)] /// FYI: type /// ``` #[inline] pub fn error_to_string(error: K) -> K{ unsafe{ native::ee(error) } } //%% Symbol %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Intern `n` chars from a char array. /// Returns an interned char array and should be used to add char array to a symbol vector. /// # Example /// See the example of [`flip`](fn.flip.html). #[inline] pub fn internalize_n(string: S, n: I) -> S{ unsafe{ native::sn(string, n) } } /// Intern a null-terminated char array. /// Returns an interned char array and should be used to add char array to a symbol vector. /// # Example /// See the example of [`flip`](fn.flip.html). #[inline] pub fn internalize(string: S) -> S{ unsafe{ native::ss(string) } } //%% Table %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Constructor of q table object from a q dictionary object. /// # Note /// Basically this is a `flip` command of q. Hence the value of the dictionary must have /// lists as its elements. /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_table2(_: K) -> K{ /// // Build keys /// let keys=new_simple_list(qtype::SYMBOL, 2); /// let keys_slice=keys.as_mut_slice::<S>(); /// keys_slice[0]=internalize(str_to_S!("time")); /// keys_slice[1]=internalize_n(str_to_S!("temperature_and_humidity"), 11); /// /// // Build values /// let values=new_simple_list(qtype::COMPOUND, 2); /// let time=new_simple_list(qtype::TIMESTAMP, 3); /// // 2003.10.10D02:24:19.167018272 2006.05.24D06:16:49.419710368 2008.08.12D23:12:24.018691392 /// time.as_mut_slice::<J>().copy_from_slice(&[119067859167018272_i64, 201766609419710368, 271897944018691392]); /// let temperature=new_simple_list(qtype::FLOAT, 3); /// temperature.as_mut_slice::<F>().copy_from_slice(&[22.1_f64, 24.7, 30.5]); /// values.as_mut_slice::<K>().copy_from_slice(&[time, temperature]); /// /// flip(new_dictionary(keys, values)) /// } /// ``` /// ```q /// q)climate_change: libc_api_examples 2: (`create_table2; 1); /// q)climate_change[] /// time temperature /// ----------------------------------------- /// 2003.10.10D02:24:19.167018272 22.1 /// 2006.05.24D06:16:49.419710368 24.7 /// 2008.08.12D23:12:24.018691392 30.5 /// ``` #[inline] pub fn flip(dictionary: K) -> K{ match unsafe{(*dictionary).qtype}{ qtype::DICTIONARY => unsafe{native::xT(dictionary)}, _ => unsafe{native::krr(null_terminated_str_to_const_S("not a dictionary\0"))} } } /// Constructor of simple q table object from a q keyed table object. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_table2(_: K) -> K{ /// // Build keys /// let keys=new_simple_list(qtype::SYMBOL, 2); /// let keys_slice=keys.as_mut_slice::<S>(); /// keys_slice[0]=internalize(str_to_S!("time")); /// keys_slice[1]=internalize_n(str_to_S!("temperature_and_humidity"), 11); /// /// // Build values /// let values=new_simple_list(qtype::COMPOUND, 2); /// let time=new_simple_list(qtype::TIMESTAMP, 3); /// // 2003.10.10D02:24:19.167018272 2006.05.24D06:16:49.419710368 2008.08.12D23:12:24.018691392 /// time.as_mut_slice::<J>().copy_from_slice(&[119067859167018272_i64, 201766609419710368, 271897944018691392]); /// let temperature=new_simple_list(qtype::FLOAT, 3); /// temperature.as_mut_slice::<F>().copy_from_slice(&[22.1_f64, 24.7, 30.5]); /// values.as_mut_slice::<K>().copy_from_slice(&[time, temperature]); /// /// flip(new_dictionary(keys, values)) /// } /// /// #[no_mangle] /// pub extern "C" fn create_keyed_table(dummy: K) -> K{ /// enkey(create_table2(dummy), 1) /// } /// /// #[no_mangle] /// pub extern "C" fn keyed_to_simple_table(dummy: K) -> K{ /// unkey(create_keyed_table(dummy)) /// } /// ``` /// ```q /// q)unkey: libc_api_examples 2: (`keyed_to_simple_table; 1); /// q)unkey[] /// time temperature /// ----------------------------------------- /// 2003.10.10D02:24:19.167018272 22.1 /// 2006.05.24D06:16:49.419710368 24.7 /// 2008.08.12D23:12:24.018691392 30.5 /// ``` #[inline] pub fn unkey(keyed_table: K) -> K{ match unsafe{(*keyed_table).qtype}{ qtype::DICTIONARY => unsafe{native::ktd(keyed_table)}, _ => unsafe{native::krr(null_terminated_str_to_const_S("not a keyed table\0"))} } } /// Constructor of q keyed table object. /// # Parameters /// - `table`: q table object to be enkeyed. /// - `n`: The number of key columns from the left. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn create_table2(_: K) -> K{ /// // Build keys /// let keys=new_simple_list(qtype::SYMBOL, 2); /// let keys_slice=keys.as_mut_slice::<S>(); /// keys_slice[0]=internalize(str_to_S!("time")); /// keys_slice[1]=internalize_n(str_to_S!("temperature_and_humidity"), 11); /// /// // Build values /// let values=new_simple_list(qtype::COMPOUND, 2); /// let time=new_simple_list(qtype::TIMESTAMP, 3); /// // 2003.10.10D02:24:19.167018272 2006.05.24D06:16:49.419710368 2008.08.12D23:12:24.018691392 /// time.as_mut_slice::<J>().copy_from_slice(&[119067859167018272_i64, 201766609419710368, 271897944018691392]); /// let temperature=new_simple_list(qtype::FLOAT, 3); /// temperature.as_mut_slice::<F>().copy_from_slice(&[22.1_f64, 24.7, 30.5]); /// values.as_mut_slice::<K>().copy_from_slice(&[time, temperature]); /// /// flip(new_dictionary(keys, values)) /// } /// /// #[no_mangle] /// pub extern "C" fn create_keyed_table(dummy: K) -> K{ /// enkey(create_table2(dummy), 1) /// } /// ``` /// ```q /// q)locker: libc_api_examples 2: (`create_keyed_table; 1); /// q)locker[] /// time | temperature /// -----------------------------| ----------- /// 2003.10.10D02:24:19.167018272| 22.1 /// 2006.05.24D06:16:49.419710368| 24.7 /// 2008.08.12D23:12:24.018691392| 30.5 /// ``` #[inline] pub fn enkey(table: K, n: J) -> K{ match unsafe{(*table).qtype}{ qtype::TABLE => unsafe{native::knt(n, table)}, _ => unsafe{native::krr(null_terminated_str_to_const_S("not a table\0"))} } } //%% Reference Count %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Decrement reference count of the q object. The decrement must be done when `k` function gets an error /// object whose type is `qtype::ERROR` and when you created an object but do not intend to return it to /// q side. See details on [the reference page](https://code.kx.com/q/interfaces/c-client-for-q/#managing-memory-and-reference-counting). /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[no_mangle] /// pub extern "C" fn agriculture(_: K)->K{ /// // Produce an apple. /// let fruit=new_symbol("apple"); /// // Sow the apple seed. /// decrement_reference_count(fruit); /// // Return null. /// KNULL /// } /// ``` /// ```q /// q)do_something: libc_api_examples 2: (`agriculture; 1); /// q)do_something[] /// q) /// ``` #[inline] pub fn decrement_reference_count(qobject: K) -> V{ unsafe{native::r0(qobject)} } /// Increment reference count of the q object. Increment must be done when you passed arguments /// to Rust function and intends to return it to q side or when you pass some `K` objects to `k` /// function and intend to use the argument after the call. /// See details on [the reference page](https://code.kx.com/q/interfaces/c-client-for-q/#managing-memory-and-reference-counting). /// # Example /// ```no_run /// use kdb_c_api::*; /// /// fn eat(apple: K){ /// println!("おいしい!"); /// } /// /// #[no_mangle] /// pub extern "C" fn satisfy_5000_men(apple: K) -> K{ /// for _ in 0..10{ /// eat(apple); /// } /// unsafe{native::k(0, str_to_S!("eat"), increment_reference_count(apple), KNULL);} /// increment_reference_count(apple) /// } /// ``` /// ```q /// q)eat:{[apple] show "Collect the clutter of apples!";} /// q)bread_is_a_sermon: libc_api_examples 2: (`satisfy_5000_men; 1); /// q)bread_is_a_sermon[`green_apple] /// おいしい! /// おいしい! /// おいしい! /// おいしい! /// おいしい! /// おいしい! /// おいしい! /// おいしい! /// おいしい! /// おいしい! /// "Collect the clutter of apples!" /// ``` #[inline] pub fn increment_reference_count(qobject: K) -> K{ unsafe{native::r1(qobject)} } //%% Callback %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Remove callback from the associated kdb+ socket and call `kclose`. /// Return null if the socket is invalid or not the one which had been registered by `sd1`. /// # Note /// A function which calls this function must be executed at the exit of the process. #[inline] pub fn destroy_socket(socket: I){ unsafe{ native::sd0(socket); } } /// Remove callback from the associated kdb+ socket and call `kclose` if the given condition is satisfied. /// Return null if the socket is invalid or not the one which had been registered by `sd1`. /// # Note /// A function which calls this function must be executed at the exit of the process. #[inline] pub fn destroy_socket_if(socket: I, condition: bool){ unsafe{ native::sd0x(socket, condition as I); } } /// Register callback to the associated kdb+ socket. /// ```no_run /// use kdb_c_api::*; /// /// static mut PIPE:[I; 2]=[-1, -1]; /// /// // Callback for some message queue. /// extern "C" fn callback(socket: I)->K{ /// let mut buffer: [K; 1]=[0 as K]; /// unsafe{libc::read(socket, buffer.as_mut_ptr() as *mut V, 8)}; /// // Call `shout` function on q side with the received data. /// let result=error_to_string(unsafe{native::k(0, str_to_S!("shout"), buffer[0], KNULL)}); /// if result.get_type() == qtype::ERROR{ /// eprintln!("Execution error: {}", result.get_symbol().unwrap()); /// decrement_reference_count(result); /// }; /// KNULL /// } /// /// #[no_mangle] /// pub extern "C" fn plumber(_: K) -> K{ /// if 0 != unsafe{libc::pipe(PIPE.as_mut_ptr())}{ /// return new_error("Failed to create pipe\0"); /// } /// if KNULL == register_callback(unsafe{PIPE[0]}, callback){ /// return new_error("Failed to register callback\0"); /// } /// // Lock symbol in a worker thread. /// pin_symbol(); /// let handle=std::thread::spawn(move ||{ /// let mut precious=new_simple_list(qtype::SYMBOL, 3); /// let precious_array=precious.as_mut_slice::<S>(); /// precious_array[0]=internalize(null_terminated_str_to_S("belief\0")); /// precious_array[1]=internalize(null_terminated_str_to_S("love\0")); /// precious_array[2]=internalize(null_terminated_str_to_S("hope\0")); /// unsafe{libc::write(PIPE[1], std::mem::transmute::<*mut K, *mut V>(&mut precious), 8)}; /// }); /// handle.join().unwrap(); /// unpin_symbol(); /// KNULL /// } /// ``` /// ```q /// q)shout:{[precious] -1 "What are the three largest elements?: ", .Q.s1 precious;}; /// q)fall_into_pipe: `libc_api_example 2: (`plumber; 1); /// q)fall_into_pipe[] /// What are the three largest elements?: `belief`love`hope /// ``` #[inline] pub fn register_callback(socket: I, function: extern fn(I) -> K) -> K{ unsafe{ native::sd1(socket, function) } } //%% Miscellaneous %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Apply a function to q list object `.[func; args]`. /// # Example /// See the example of [`error_to_string`](fn.error_to_string.html). #[inline] pub fn apply(func: K, args: K) -> K{ unsafe{native::dot(func, args)} } /// Lock a location of internalized symbol in remote threads. /// Returns the previously set value. /// # Example /// See the example of [`register_callback`](fn.register_callback.html). #[inline] pub fn pin_symbol() -> I{ unsafe{ native::setm(1) } } /// Unlock a location of internalized symbol in remote threads. /// # Example /// See the example of [`register_callback`](fn.register_callback.html). #[inline] pub fn unpin_symbol() -> I{ unsafe{ native::setm(0) } } /// Drop Rust object inside q. Passed as the first element of a foreign object. /// # Parameters /// - `obj`: List of (function to free the object; foreign object). /// # Example /// See the example of [`load_as_q_function`](fn.load_as_q_function.html). pub extern "C" fn drop_q_object(obj: K) -> K{ let obj_slice=obj.as_mut_slice::<K>(); // Take ownership of `K` object from a raw pointer and drop at the end of this scope. unsafe{Box::from_raw(obj_slice[1])}; // Fill the list with null. obj_slice.copy_from_slice(&[KNULL, KNULL]); obj } /// Load C function as a q function (`K` object). /// # Parameters /// - `func`: A function takes a C function that would take `n` `K` objects as arguments and returns a `K` object. /// - `n`: The number of arguments for the function. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// #[derive(Clone, Debug)] /// struct Planet{ /// name: String, /// population: i64, /// water: bool /// } /// /// impl Planet{ /// /// Constructor of `Planet`. /// fn new(name: &str, population: i64, water: bool) -> Self{ /// Planet{ /// name: name.to_string(), /// population: population, /// water: water /// } /// } /// /// /// Description of the planet. /// fn description(&self)->String{ /// let mut desc=format!("The planet {} is a beautiful planet where {} people reside.", self.name, self.population); /// if self.water{ /// desc+=" Furthermore water is flowing on the surface of it."; /// } /// desc /// } /// } /// /// /// Example of `set_type`. /// #[no_mangle] /// pub extern "C" fn eden(_: K) -> K{ /// let earth=Planet::new("earth", 7500_000_000, true); /// let foreign=new_simple_list(qtype::COMPOUND, 2); /// let foreign_slice=foreign.as_mut_slice::<K>(); /// foreign_slice[0]=drop_q_object as K; /// foreign_slice[1]=Box::into_raw(Box::new(earth)) as K; /// // Set as foreign object. /// foreign.set_type(qtype::FOREIGN); /// foreign /// } /// /// extern "C" fn invade(planet: K, action: K) -> K{ /// let obj=planet.as_mut_slice::<K>()[1] as *const Planet; /// println!("{:?}", unsafe{obj.as_ref()}.unwrap()); /// let mut desc=unsafe{obj.as_ref()}.unwrap().description(); /// if action.get_bool().unwrap(){ /// desc+=" You shall not curse what God blessed."; /// } /// else{ /// desc+=" I perceived I could find favor of God by blessing them."; /// } /// new_string(&desc) /// } /// /// /// Example of `load_as_q_function`. /// #[no_mangle] /// pub extern "C" fn probe(planet: K)->K{ /// // Return monadic function /// unsafe{native::k(0, str_to_S!("{[func; planet] func[planet]}"), load_as_q_function(invade as *const V, 2), planet, KNULL)} /// } /// ``` /// ```q /// q)eden: libc_api_example 2: (`eden; 1); /// q)earth: eden[] /// q)type earth /// 112h /// q)probe: libc_api_example 2: (`probe; 1); /// q)invade: probe[earth]; /// q)\c 25 200 /// q)invade 1b /// "The planet earth is a beautiful planet where 7500000000 people reside. Furthermore water is flowing on the surface of it. You shall not curse what God blessed." /// ``` #[inline] pub fn load_as_q_function(func: *const V, n: J) -> K{ unsafe{ native::dl(func, n) } } /// Convert ymd to the number of days from `2000.01.01`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// fn main(){ /// /// let days=ymd_to_days(2020, 4, 1); /// assert_eq!(days, 7396); /// /// } /// ``` #[inline] pub fn ymd_to_days(year: I, month: I, date:I) -> I{ unsafe{ native::ymd(year, month, date) } } /// Convert the number of days from `2000.01.01` to a number expressed as `yyyymmdd`. /// # Example /// ```no_run /// use kdb_c_api::*; /// /// fn main(){ /// /// let number=days_to_ymd(7396); /// assert_eq!(number, 20200401); /// /// } /// ``` #[inline] pub fn days_to_ymd(days: I) -> I{ unsafe{ native::dj(days) } }