Expand description
Constructor of q byte object. Relabeling of kg
.
Example
use kdbplus::api::*;
#[no_mangle]
pub extern "C" fn create_byte(_: K) -> K{
new_byte(0x3c)
}
q)create_byte: `libapi_examples 2: (`create_byte; 1);
q)create_byte[]
0x3c
Examples found in repository?
src/api/mod.rs (line 975)
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
fn get_row(&self, index: usize, enum_sources: &[&str]) -> Result<K, &'static str> {
match unsafe { (**self).qtype } {
qtype::TABLE => {
let keys = unsafe { (**self).value.table }.as_mut_slice::<K>()[0];
let values = unsafe { (**self).value.table }.as_mut_slice::<K>()[1];
if (unsafe { (*values.as_mut_slice::<K>()[0]).value.list }.n as usize) < index + 1 {
// Index out of bounds
Err("index out of bounds\0")
} else {
let num_columns = unsafe { (*keys).value.list }.n;
let row = new_list(qtype::COMPOUND_LIST, num_columns);
let row_slice = row.as_mut_slice::<K>();
let mut enum_source_index = 0;
let mut i = 0;
for column in values.as_mut_slice::<K>() {
match column.get_type() {
qtype::BOOL_LIST => {
row_slice[i] = new_bool(column.as_mut_slice::<G>()[index] as i32);
}
qtype::BYTE_LIST => {
row_slice[i] = new_byte(column.as_mut_slice::<G>()[index] as i32);
}
qtype::SHORT_LIST => {
row_slice[i] = new_short(column.as_mut_slice::<H>()[index] as i32);
}
qtype::INT_LIST => {
row_slice[i] = new_int(column.as_mut_slice::<I>()[index]);
}
qtype::LONG_LIST => {
row_slice[i] = new_long(column.as_mut_slice::<J>()[index]);
}
qtype::REAL_LIST => {
row_slice[i] = new_real(column.as_mut_slice::<E>()[index] as f64);
}
qtype::FLOAT_LIST => {
row_slice[i] = new_float(column.as_mut_slice::<F>()[index]);
}
qtype::STRING => {
row_slice[i] = new_char(column.as_mut_slice::<G>()[index] as char);
}
qtype::SYMBOL_LIST => {
row_slice[i] =
new_symbol(S_to_str(column.as_mut_slice::<S>()[index]));
}
qtype::TIMESTAMP_LIST => {
row_slice[i] = new_timestamp(column.as_mut_slice::<J>()[index]);
}
qtype::MONTH_LIST => {
row_slice[i] = new_month(column.as_mut_slice::<I>()[index]);
}
qtype::DATE_LIST => {
row_slice[i] = new_date(column.as_mut_slice::<I>()[index]);
}
qtype::DATETIME_LIST => {
row_slice[i] = new_datetime(column.as_mut_slice::<F>()[index]);
}
qtype::TIMESPAN_LIST => {
row_slice[i] = new_timespan(column.as_mut_slice::<J>()[index]);
}
qtype::MINUTE_LIST => {
row_slice[i] = new_minute(column.as_mut_slice::<I>()[index]);
}
qtype::SECOND_LIST => {
row_slice[i] = new_second(column.as_mut_slice::<I>()[index]);
}
qtype::TIME_LIST => {
row_slice[i] = new_time(column.as_mut_slice::<I>()[index]);
}
qtype::ENUM_LIST => {
if enum_sources.len() <= enum_source_index {
// Index out of bounds
decrement_reference_count(row);
return Err("insufficient enum sources\0");
}
let enum_value = new_enum(
enum_sources[enum_source_index],
column.as_mut_slice::<J>()[index],
);
if unsafe { (*enum_value).qtype } == qtype::ERROR {
// Error in creating enum object.
decrement_reference_count(row);
let error = S_to_str(unsafe { (*enum_value).value.symbol });
decrement_reference_count(enum_value);
return Err(error);
} else {
row_slice[i] = enum_value;
enum_source_index += 1;
}
}
qtype::COMPOUND_LIST => {
// Increment reference count since compound list consumes the element.
row_slice[i] =
increment_reference_count(column.as_mut_slice::<K>()[index]);
}
// There are no other list type
_ => unreachable!(),
}
i += 1;
}
Ok(new_dictionary(increment_reference_count(keys), row))
}
}
_ => Err("not a table\0"),
}
}
#[inline]
fn get_bool(&self) -> Result<bool, &'static str> {
match unsafe { (**self).qtype } {
qtype::BOOL_ATOM => 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 } {
qtype::GUID_ATOM => {
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 } {
qtype::BYTE_ATOM => Ok(unsafe { (**self).value.byte }),
_ => Err("not a byte\0"),
}
}
#[inline]
fn get_short(&self) -> Result<i16, &'static str> {
match unsafe { (**self).qtype } {
qtype::SHORT_ATOM => Ok(unsafe { (**self).value.short }),
_ => Err("not a short\0"),
}
}
#[inline]
fn get_int(&self) -> Result<i32, &'static str> {
match unsafe { (**self).qtype } {
qtype::INT_ATOM
| qtype::MONTH_ATOM
| qtype::DATE_ATOM
| qtype::MINUTE_ATOM
| qtype::SECOND_ATOM
| qtype::TIME_ATOM => Ok(unsafe { (**self).value.int }),
_ => Err("not an int\0"),
}
}
#[inline]
fn get_long(&self) -> Result<i64, &'static str> {
match unsafe { (**self).qtype } {
qtype::LONG_ATOM | qtype::TIMESTAMP_ATOM | qtype::TIMESPAN_ATOM | qtype::ENUM_ATOM => {
Ok(unsafe { (**self).value.long })
}
_ => Err("not a long\0"),
}
}
#[inline]
fn get_real(&self) -> Result<f32, &'static str> {
match unsafe { (**self).qtype } {
qtype::REAL_ATOM => Ok(unsafe { (**self).value.real }),
_ => Err("not a real\0"),
}
}
#[inline]
fn get_float(&self) -> Result<f64, &'static str> {
match unsafe { (**self).qtype } {
qtype::FLOAT_ATOM | qtype::DATETIME_ATOM => Ok(unsafe { (**self).value.float }),
_ => Err("not a float\0"),
}
}
#[inline]
fn get_char(&self) -> Result<char, &'static str> {
match unsafe { (**self).qtype } {
qtype::CHAR => Ok(unsafe { (**self).value.byte as char }),
_ => Err("not a char\0"),
}
}
#[inline]
fn get_symbol(&self) -> Result<&str, &'static str> {
match unsafe { (**self).qtype } {
qtype::SYMBOL_ATOM => Ok(S_to_str(unsafe { (**self).value.symbol })),
_ => Err("not a symbol\0"),
}
}
#[inline]
fn get_str(&self) -> Result<&str, &'static str> {
match unsafe { (**self).qtype } {
qtype::STRING => 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::STRING => {
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_error_string(&self) -> Result<&str, &'static str> {
match unsafe { (**self).qtype } {
qtype::ERROR => {
if unsafe { (**self).value.symbol } != std::ptr::null_mut::<C>() {
Ok(S_to_str(unsafe { (**self).value.symbol }))
} else {
Err("not an error\0")
}
}
_ => Err("not an error\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 } {
let result = Ok(unsafe { native::jv(self, list) });
// Free appended list for internally created object.
unsafe { native::r0(list) };
result
} else {
Err("not a list or types do not match\0")
}
}
#[inline]
fn push(&mut self, atom: K) -> Result<K, &'static str> {
match unsafe { (**self).qtype } {
qtype::COMPOUND_LIST => Ok(unsafe { native::jk(self, atom) }),
_ => 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 @ qtype::BOOL_LIST..=qtype::ENUM_LIST => {
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> {
match unsafe { (**self).qtype } {
qtype::SYMBOL_LIST => Ok(unsafe { native::js(self, native::ss(str_to_S!(symbol))) }),
_ => Err("not a symbol list\0"),
}
}
#[inline]
fn push_symbol_n(&mut self, symbol: &str, n: I) -> Result<K, &'static str> {
match unsafe { (**self).qtype } {
qtype::SYMBOL_LIST => Ok(unsafe { native::js(self, native::sn(str_to_S!(symbol), n)) }),
_ => Err("not a symbol list or types do not match\0"),
}
}
#[inline]
fn len(&self) -> i64 {
match unsafe { (**self).qtype } {
_t @ qtype::ENUM_ATOM..=qtype::BOOL_ATOM => {
// Atom
1
}
_t @ qtype::COMPOUND_LIST..=qtype::ENUM_LIST => {
// List
unsafe { (**self).value.list }.n
}
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.
unsafe {
(*((**self).value.table).as_mut_slice::<K>()[1].as_mut_slice::<K>()[0])
.value
.list
}
.n
}
qtype::DICTIONARY | qtype::SORTED_DICTIONARY => {
// Dictionary
// Access to keys of the dictionary and retrieve its length.
unsafe { (*(*self).as_mut_slice::<K>()[0]).value.list }.n
}
_ => {
// General null, function, foreign
1
}
}
}
#[inline]
fn get_type(&self) -> i8 {
unsafe { (**self).qtype }
}
#[inline]
fn set_type(&mut self, qtype: i8) {
unsafe { (**self).qtype = qtype };
}
#[inline]
fn set_attribute(&mut self, attribute: i8) -> Result<(), &'static str> {
match unsafe { (**self).qtype } {
_t @ qtype::BOOL_LIST..=qtype::TIME_LIST => {
Ok(unsafe { (**self).attribute = attribute })
}
_ => Err("not a simple list\0"),
}
}
#[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_LIST => {
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 %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
/// Convert `S` to `&str`. This function is intended to convert symbol type (null-terminated char-array) to `str`.
/// # Extern
/// ```no_run
/// use kdbplus::*;
/// use kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn print_symbol(symbol: K) -> K{
/// unsafe{
/// if (*symbol).qtype == qtype::SYMBOL_ATOM{
/// println!("symbol: `{}", S_to_str((*symbol).value.symbol));
/// }
/// // return null
/// KNULL
/// }
/// }
/// ```
/// ```q
/// q)print_symbol:`libapi_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 kdbplus::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: `libapi_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 kdbplus::api::*;
/// use kdbplus::api::native::*;
/// use kdbplus::qtype;
///
/// pub extern "C" fn must_be_int2(obj: K) -> K{
/// unsafe{
/// if (*obj).qtype != qtype::INT_ATOM{
/// krr(null_terminated_str_to_const_S("not an int\0"))
/// }
/// else{
/// KNULL
/// }
/// }
/// }
/// ```
/// ```q
/// q)check:`libapi_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 %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
/// Constructor of q bool object. Relabeling of `kb`.
/// # Example
/// ```no_run
/// use kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_bool(_: K) -> K{
/// new_bool(0)
/// }
/// ```
/// ```q
/// q)no: `libapi_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 kdbplus::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: `libapi_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 kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_byte(_: K) -> K{
/// new_byte(0x3c)
/// }
/// ```
/// ```q
/// q)create_byte: `libapi_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 kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_short(_: K) -> K{
/// new_short(-144)
/// }
/// ```
/// ```q
/// q)shortage: `libapi_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 kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_int(_: K) -> K{
/// new_int(86400000)
/// }
/// ```
/// ```q
/// q)trvial: `libapi_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 kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_long(_: K) -> K{
/// new_long(-668541276001729000)
/// }
/// ```
/// ```q
/// q)lengthy: `libapi_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 kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_real(_: K) -> K{
/// new_real(0.00324)
/// }
/// ```
/// ```q
/// q)reality: `libapi_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 kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_float(_: K) -> K{
/// new_float(-6302.620)
/// }
/// ```
/// ```q
/// q)coffee_float: `libapi_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 kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_char2(_: K) -> K{
/// new_char('t')
/// }
/// ```
/// ```q
/// q)heavy: `libapi_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 kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_symbol2(_: K) -> K{
/// new_symbol("symbolic")
/// }
/// ```
/// ```q
/// q)hard: `libapi_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 kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_timestamp2(_: K) -> K{
/// // 2015.03.16D00:00:00:00.000000000
/// new_timestamp(479779200000000000)
/// }
/// ```
/// ```q
/// q)stamp: `libapi_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_ATOM 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 kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_month(_: K) -> K{
/// // 2010.07m
/// new_month(126)
/// }
/// ```
/// ```q
/// q)create_month: `libapi_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_ATOM as I);
(*month).value.int = months;
month
}
}
/// Constructor of q date object. Relabeling of `kd`.
/// # Example
/// ```no_run
/// use kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_date(_: K) -> K{
/// // 1999.12.25
/// new_date(-7)
/// }
/// ```
/// ```q
/// q)nostradamus: `libapi_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 kdbplus::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 kdbplus::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_ATOM as I, nanoseconds) }
}
/// Create a month object. This is a complememtal constructor of
/// missing minute type.
/// # Example
/// ```no_run
/// use kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_minute(_: K) -> K{
/// // 10:40
/// new_minute(640)
/// }
/// ```
/// ```q
/// q)minty: `libapi_examples 2: (`create_minute; 1);
/// q)minty[]
/// 10:40
/// ```
#[inline]
pub fn new_minute(minutes: I) -> K {
unsafe {
let minute = native::ka(qtype::MINUTE_ATOM as I);
(*minute).value.int = minutes;
minute
}
}
/// Create a month object. This is a complememtal constructor of
/// missing second type.
/// # Example
/// ```no_run
/// use kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_second(_: K) -> K{
/// // -02:00:00
/// new_second(-7200)
/// }
/// ```
/// ```q
/// q)third: `libapi_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_ATOM as I);
(*second).value.int = seconds;
second
}
}
/// Constructor of q time object. Relabeling of `kt`.
/// # Example
/// ```no_run
/// use kdbplus::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 enum object. This is a complememtal constructor of
/// missing second type.
/// # Example
/// ```no_run
/// use kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn create_enum(source: K, index: K) -> K{
/// // Error if the specified enum source does not exist or it is not a symbol list or the index is out of enum range
/// new_enum(source.get_str().unwrap(), index.get_long().unwrap())
/// }
/// ```
/// ```q
/// q)enumerate: libc_api_examples 2: (`create_enum; 2);
/// q)sym: `a`b`c
/// q)enumerate["sym"; 1]
/// `sym$`b
/// q)enumerate["sym"; 3]
/// 'index out of enum range
/// [0] enumerate["sym"; 3]
/// ^
/// q)enumerate["som"; 0]
/// 'som
/// [1] som
/// ^
/// q))\
/// q)som:til 3
/// q)enumerate["som"; 0]
/// 'enum must be cast to symbol list
/// [0] enumerate["som"; 0]
/// ^
/// q)som:`a`b
/// q)enumerate["som"; 0]
/// `som$`a
/// ```
#[inline]
pub fn new_enum(source: &str, index: J) -> K {
let sym = unsafe { native::k(0, str_to_S!(source), KNULL) };
if unsafe { (*sym).qtype } == qtype::ERROR {
// Error. Specified sym does not exist
sym
} else if unsafe { (*sym).qtype } != qtype::SYMBOL_LIST {
// sym is not a symbol list
unsafe {
native::r0(sym);
native::krr(null_terminated_str_to_const_S(
"enum must be cast to symbol list\0",
))
}
} else if unsafe { (*sym).value.list.n } <= index {
// Index is out of sym range
unsafe {
native::r0(sym);
native::krr(null_terminated_str_to_const_S("index out of enum range\0"))
}
} else {
let function = format!("{{`{}${} x}}", source, source);
unsafe {
native::r0(sym);
native::k(0, str_to_S!(function.as_str()), native::kj(index), KNULL)
}
}
}
/// Constructor of q simple list.
/// # Example
/// See the example of [`new_dictionary`](fn.new_dictionary.html).
#[inline]
pub fn new_list(qtype: i8, length: J) -> K {
unsafe { native::ktn(qtype as I, length) }
}
/// Constructor of q string object.
/// # Example
/// ```no_run
/// use kdbplus::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 kdbplus::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 kdbplus::api::*;
/// use kdbplus::qtype;
///
/// #[no_mangle]
/// pub extern "C" fn create_dictionary() -> K{
/// let keys=new_list(qtype::INT_LIST, 2);
/// keys.as_mut_slice::<I>()[0..2].copy_from_slice(&[0, 1]);
/// let values=new_list(qtype::COMPOUND_LIST, 2);
/// let date_list=new_list(qtype::DATE_LIST, 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: `libapi_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 general null.
/// # Example
/// ```no_run
/// use kdbplus::qtype;
/// use kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn nullify(_: K) -> K{
/// let nulls=new_list(qtype::COMPOUND_LIST, 3);
/// let null_slice=nulls.as_mut_slice::<K>();
/// null_slice[0]=new_null();
/// null_slice[1]=new_string("null is not a general null");
/// null_slice[2]=new_null();
/// nulls
/// }
/// ```
/// ```q
/// q)void: `libapi_examples 2: (`nullify; 1);
/// q)void[]
/// ::
/// "null is not a general null"
/// ::
/// ```
#[inline]
pub fn new_null() -> K {
unsafe {
let null = native::ka(qtype::NULL as I);
(*null).value.byte = 0;
null
}
}
/// Constructor of q error. The input must be null-terminated.
/// # Example
/// ```no_run
/// use kdbplus::api::*;
///
/// pub extern "C" fn thai_kick(_: K) -> K{
/// new_error("Thai kick unconditionally!!\0")
/// }
/// ```
/// ```q
/// q)monstrous: `libapi_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 `symbol`.
/// # Example
/// ```no_run
/// use kdbplus::*;
/// use kdbplus::api::*;
///
/// extern "C" fn no_panick(func: K, args: K) -> K{
/// let result=error_to_string(apply(func, args));
/// if let Ok(error) = result.get_error_string(){
/// println!("FYI: {}", error);
/// // Decrement reference count of the error object which is no longer used.
/// decrement_reference_count(result);
/// KNULL
/// }
/// else{
/// result
/// }
/// }
/// ```
/// ```q
/// q)chill: `libapi_examples 2: (`no_panick; 2);
/// q)chill[$; ("J"; "42")]
/// success!
/// 42
/// q)chill[+; (1; `a)]
/// FYI: type
/// ```
/// # Note
/// If you intend to use the error string only in Rust side and not to return the value, you need
/// to decrement the reference count of the error object created by `error_to_string` as shown above.
/// If you want to propagate the error to q side after some operation, you can just return it (See the
/// example of [`is_error`](fn.is_error.html)).
///
/// # Warning
/// In q, an error is a 0 pointer. This causes a problem of false positive by `error_to_string`, i.e.,
/// `KNULL` is also catched as an error object and its type is set `qtype::ERROR`. In such a case you must NOT
/// return the catched object because it causes segmentation fault. If you want to check if the catched object
/// is an error and then return if it is, you should use [`is_error`](fn.is_error.html). If you want to use the
/// underlying error string of the catched object, you should use [`get_error_string`](trait.KUtility.html#tymethod.get_error_string).
#[inline]
pub fn error_to_string(error: K) -> K {
unsafe { native::ee(error) }
}
/// Judge if a catched object by [`error_to_string`](fn.error_to_string.html) is a genuine error object of type
/// `qtype::ERROR` (This means false positive of the `KNULL` case can be eliminated).
/// # Examples
/// ```no_run
/// use kdbplus::*;
/// use kdbplus::api::*;
///
/// fn love_even(arg: K) -> K{
/// if let Ok(int) = arg.get_int(){
/// if int % 2 == 0{
/// // Silent for even value
/// KNULL
/// }
/// else{
/// // Shout against odd value
/// new_error("great is the even value!!\0")
/// }
/// }
/// else{
/// // Pass through
/// increment_reference_count(arg)
/// }
/// }
///
/// #[no_mangle]
/// pub extern "C" fn propagate(arg: K) -> K{
/// let result=error_to_string(love_even(arg));
/// if is_error(result){
/// // Propagate the error
/// result
/// }
/// else if result.get_type() == qtype::ERROR{
/// // KNULL
/// println!("this is KNULL");
/// decrement_reference_count(result);
/// KNULL
/// }
/// else{
/// // Other
/// new_symbol("sonomama")
/// }
/// }
/// ```
/// ```q
/// q)convey: `libapi_examples 2: (`propagate; 1);
/// q)convey[7i]
/// 'great is the even value!!
/// q)convey[12i]
/// this is KNULL
/// q)convey[5.5]
/// `sonomama
/// ```
/// # Note
/// In this example `KNULL` is used as a returned value of the function called by another function to demonstrate
/// how `is_error` works. However, `KNULL` should not be used in such a way in order to avoid this kind of complexity.
/// To return a general null for inner functions, use [`new_null`](fn.new_null.html) instead.
#[inline]
pub fn is_error(catched: K) -> bool {
(unsafe { (*catched).qtype } == qtype::ERROR)
&& (unsafe { (*catched).value.symbol } != std::ptr::null_mut::<C>())
}
//%% Symbol %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
/// Extract the first `n` chars from a character array and enumerate it internally.
/// This function must be used to add a character array as a symbol value to a symbol list.
/// The returned value is the same character array as the input.
/// # Example
/// See the example of [`flip`](fn.flip.html).
/// # Note
/// The reason why this function must be used is to enumerate the character array before handling
/// it as a q symbol type value. q/kdb+ is enumerating all symbol values to optimize comparison
/// or memory usage. On the other hand [`new_symbol`] does the enumeration internally and
/// therefore it does not need this function.
#[inline]
pub fn enumerate_n(string: S, n: I) -> S {
unsafe { native::sn(string, n) }
}
/// Enumerate a null-terminated character array internally. This function must be used
/// to add a character array as a symbol value to a symbol list. The returned value is
/// the same character array as the input.
/// # Example
/// See the example of [`flip`](fn.flip.html).
/// # Note
/// The reason why this function must be used is to enumerate the character array before handling
/// it as a q symbol type value. q/kdb+ is enumerating all symbol values to optimize comparison
/// or memory usage. On the other hand [`new_symbol`] does the enumeration internally and
/// therefore it does not need this function.
#[inline]
pub fn enumerate(string: S) -> S {
unsafe { native::ss(string) }
}
//%% Table %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
/// 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
/// #[macro_use]
/// extern crate kdbplus;
/// use kdbplus::api::*;
/// use kdbplus::qtype;
///
/// #[no_mangle]
/// pub extern "C" fn create_table2(_: K) -> K{
/// // Build keys
/// let keys=new_list(qtype::SYMBOL_LIST, 2);
/// let keys_slice=keys.as_mut_slice::<S>();
/// keys_slice[0]=enumerate(str_to_S!("time"));
/// keys_slice[1]=enumerate_n(str_to_S!("temperature_and_humidity"), 11);
///
/// // Build values
/// let values=new_list(qtype::COMPOUND_LIST, 2);
/// let time=new_list(qtype::TIMESTAMP_LIST, 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_list(qtype::FLOAT_LIST, 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
/// #[macro_use]
/// extern crate kdbplus;
/// use kdbplus::api::*;
/// use kdbplus::qtype;
///
/// #[no_mangle]
/// pub extern "C" fn create_table2(_: K) -> K{
/// // Build keys
/// let keys=new_list(qtype::SYMBOL_LIST, 2);
/// let keys_slice=keys.as_mut_slice::<S>();
/// keys_slice[0]=enumerate(str_to_S!("time"));
/// keys_slice[1]=enumerate_n(str_to_S!("temperature_and_humidity"), 11);
///
/// // Build values
/// let values=new_list(qtype::COMPOUND_LIST, 2);
/// let time=new_list(qtype::TIMESTAMP_LIST, 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_list(qtype::FLOAT_LIST, 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
/// #[macro_use]
/// extern crate kdbplus;
/// use kdbplus::api::*;
/// use kdbplus::qtype;
///
/// #[no_mangle]
/// pub extern "C" fn create_table2(_: K) -> K{
/// // Build keys
/// let keys=new_list(qtype::SYMBOL_LIST, 2);
/// let keys_slice=keys.as_mut_slice::<S>();
/// keys_slice[0]=enumerate(str_to_S!("time"));
/// keys_slice[1]=enumerate_n(str_to_S!("temperature_and_humidity"), 11);
///
/// // Build values
/// let values=new_list(qtype::COMPOUND_LIST, 2);
/// let time=new_list(qtype::TIMESTAMP_LIST, 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_list(qtype::FLOAT_LIST, 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 %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvv/
/// 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 kdbplus::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: `libapi_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
/// #[macro_use]
/// extern crate kdbplus;
/// use kdbplus::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 %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
/// 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
/// #[macro_use]
/// extern crate kdbplus;
/// use kdbplus::api::*;
/// use kdbplus::qtype;
///
/// 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_list(qtype::SYMBOL_LIST, 3);
/// let precious_array=precious.as_mut_slice::<S>();
/// precious_array[0]=enumerate(null_terminated_str_to_S("belief\0"));
/// precious_array[1]=enumerate(null_terminated_str_to_S("love\0"));
/// precious_array[2]=enumerate(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 "C" fn(I) -> K) -> K {
unsafe { native::sd1(socket, function) }
}
//%% Miscellaneous %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
/// 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) }
}
/// Enable the remote threads to refer to the sym list in the main thread so that enumeration
/// of remotely created symbol values reain valid in the main thread after joining the
/// remote threads. This function must be used before starting any other threads if the
/// threads create symbol values. The previously set value is returned.
/// # Example
/// See the example of [`register_callback`](fn.register_callback.html).
#[inline]
pub fn pin_symbol() -> I {
unsafe { native::setm(1) }
}
/// Unlock the symbol list in the main thread. This function should be called after joining
/// 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 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
/// #[macro_use]
/// extern crate kdbplus;
/// use kdbplus::api::*;
/// use kdbplus::qtype;
///
/// #[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 mut foreign=new_list(qtype::COMPOUND_LIST, 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 kdbplus::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 kdbplus::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) }
}
/// Convert a simple list to a compound list. Expected usage is to concatinate a simple list
/// with a different type of list.
/// # Example
/// ```no_run
/// use kdbplus::*;
/// use kdbplus::api::*;
///
/// #[no_mangle]
/// pub extern "C" fn drift(_: K)->K{
/// let simple=new_list(qtype::INT_LIST, 2);
/// simple.as_mut_slice::<I>().copy_from_slice(&[12, 34]);
/// let extra=new_list(qtype::COMPOUND_LIST, 2);
/// extra.as_mut_slice::<K>().copy_from_slice(&[new_symbol("vague"), new_int(-3000)]);
/// // Convert an integer list into a compound list
/// let mut compound = simple_to_compound(simple, "");
/// compound.append(extra).unwrap()
/// }
///
/// #[no_mangle]
/// pub extern "C" fn drift2(_: K)->K{
/// let simple=new_list(qtype::ENUM_LIST, 2);
/// simple.as_mut_slice::<J>().copy_from_slice(&[0_i64, 1]);
/// // Convert an enum indices into a compound list while creating enum values from the indices which are tied with
/// // an existing enum variable named "enum", i.e., Enum indices [0, 1] in the code are cast into `(enum[0]; enum[1])`.
/// let mut compound = simple_to_compound(simple, "enum");
/// // Add `enum2[2]`.
/// compound.push(new_enum("enum2", 2)).unwrap();
/// compound.push(new_month(3)).unwrap();
/// compound
/// }
/// ```
/// ```q
/// q)drift: LIBPATH_ (`drift; 1);
/// q)drift2: LIBPATH_ (`drift2; 1);
/// q)drift[]
/// 12i
/// 34i
/// `vague
/// -3000i
/// q)enum: `mashroom`broccoli`cucumber
/// q)enum2: `mackerel`swordfish`tuna
/// q)drift2[]
/// `enum$`mashroom
/// `enum$`broccoli
/// `enum2$`tuna
/// 2000.04m
/// ```
/// # Note
/// - To convert a list provided externally (i.e., passed from a q process), apply
/// [`increment_reference_count`](fn.increment_reference_count.html) before converting the list.
/// - Enum elements from different enum sources must be contained in a compound list. Therefore
/// this function intentionally restricts the number of enum sources to one so that user switches
/// a simple list to a compound list when the second enum sources are provided.
pub fn simple_to_compound(simple: K, enum_source: &str) -> K {
let size = simple.len() as usize;
let compound = new_list(qtype::COMPOUND_LIST, size as J);
let compound_slice = compound.as_mut_slice::<K>();
match simple.get_type() {
qtype::BOOL_LIST => {
let simple_slice = simple.as_mut_slice::<G>();
for i in 0..size {
compound_slice[i] = new_bool(simple_slice[i] as I);
}
}
qtype::GUID_LIST => {
let simple_slice = simple.as_mut_slice::<U>();
for i in 0..size {
compound_slice[i] = new_guid(simple_slice[i].guid);
}
}
qtype::BYTE_LIST => {
let simple_slice = simple.as_mut_slice::<G>();
for i in 0..size {
compound_slice[i] = new_byte(simple_slice[i] as I);
}
}
qtype::SHORT_LIST => {
let simple_slice = simple.as_mut_slice::<H>();
for i in 0..size {
compound_slice[i] = new_short(simple_slice[i] as I);
}
}
qtype::INT_LIST => {
let simple_slice = simple.as_mut_slice::<I>();
for i in 0..size {
compound_slice[i] = new_int(simple_slice[i]);
}
}
qtype::LONG_LIST => {
let simple_slice = simple.as_mut_slice::<J>();
for i in 0..size {
compound_slice[i] = new_long(simple_slice[i]);
}
}
qtype::REAL_LIST => {
let simple_slice = simple.as_mut_slice::<E>();
for i in 0..size {
compound_slice[i] = new_real(simple_slice[i] as F);
}
}
qtype::FLOAT_LIST => {
let simple_slice = simple.as_mut_slice::<F>();
for i in 0..size {
compound_slice[i] = new_float(simple_slice[i]);
}
}
qtype::STRING => {
let simple_slice = simple.as_mut_slice::<G>();
for i in 0..size {
compound_slice[i] = new_char(simple_slice[i] as char);
}
}
qtype::SYMBOL_LIST => {
let simple_slice = simple.as_mut_slice::<S>();
for i in 0..size {
compound_slice[i] = new_symbol(S_to_str(simple_slice[i]));
}
}
qtype::TIMESTAMP_LIST => {
let simple_slice = simple.as_mut_slice::<J>();
for i in 0..size {
compound_slice[i] = new_timestamp(simple_slice[i]);
}
}
qtype::DATE_LIST => {
let simple_slice = simple.as_mut_slice::<I>();
for i in 0..size {
compound_slice[i] = new_date(simple_slice[i]);
}
}
qtype::TIME_LIST => {
let simple_slice = simple.as_mut_slice::<I>();
for i in 0..size {
compound_slice[i] = new_time(simple_slice[i]);
}
}
qtype::ENUM_LIST => {
let simple_slice = simple.as_mut_slice::<J>();
for i in 0..size {
compound_slice[i] = new_enum(enum_source, simple_slice[i]);
}
}
_ => {
decrement_reference_count(compound);
return new_error("not a simple list\0");
}
}
// Free simple list
decrement_reference_count(simple);
compound
}