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
//! Tuples
//!
//! The `tuple` submodule provides read-only access for the tuple userdata type.
//! It allows, for a single tuple: selective retrieval of the field contents, retrieval of information about size,
//! iteration over all the fields, and conversion from/to rust structures
//!
//! See also:
//! - [Tuples](https://www.tarantool.io/en/doc/2.2/book/box/data_model/#tuples)
//! - [Lua reference: Submodule box.tuple](https://www.tarantool.io/en/doc/2.2/reference/reference_lua/box_tuple/)
//! - [C API reference: Module tuple](https://www.tarantool.io/en/doc/2.2/dev_guide/reference_capi/tuple/)
use std::borrow::Cow;
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::ffi::{CStr, CString};
use std::fmt::{self, Debug, Formatter};
use std::io::Write;
use std::ops::Range;
use std::os::raw::{c_char, c_int};
use std::ptr::{null, NonNull};
use rmp::Marker;
use serde::Serialize;
use crate::error::{self, Error, Result, TarantoolError};
use crate::ffi::tarantool as ffi;
use crate::index;
use crate::tlua;
use crate::util::NumOrStr;
/// Tuple
pub struct Tuple {
ptr: NonNull<ffi::BoxTuple>,
}
impl Debug for Tuple {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if let Ok(v) = self.decode::<rmpv::Value>() {
f.debug_tuple("Tuple").field(&v).finish()
} else {
// Probably will never happen but better safe than sorry
f.debug_tuple("Tuple").field(&self.as_buffer()).finish()
}
}
}
impl Tuple {
/// Create a new tuple from `value` implementing [`ToTupleBuffer`].
#[inline]
pub fn new<T>(value: &T) -> Result<Self>
where
T: ToTupleBuffer + ?Sized,
{
Ok(Self::from(&value.to_tuple_buffer()?))
}
/// # Safety
/// `data` must point to a buffer containing `len` bytes representing a
/// valid messagepack array
#[inline(always)]
pub unsafe fn from_raw_data(data: *mut c_char, len: u32) -> Self {
let format = TupleFormat::default();
let tuple_ptr = ffi::box_tuple_new(format.inner, data as _, data.add(len as _) as _);
Self::from_ptr(NonNull::new_unchecked(tuple_ptr))
}
/// # Safety
/// `data` must represent a valid messagepack array
#[inline(always)]
pub unsafe fn from_slice(data: &[u8]) -> Self {
let format = TupleFormat::default();
let Range { start, end } = data.as_ptr_range();
let tuple_ptr = ffi::box_tuple_new(format.inner, start as _, end as _);
Self::from_ptr(NonNull::new_unchecked(tuple_ptr))
}
#[inline]
pub fn try_from_slice(data: &[u8]) -> Result<Self> {
let data = validate_msgpack(data)?;
unsafe { Ok(Self::from_slice(data)) }
}
#[inline(always)]
pub fn from_ptr(mut ptr: NonNull<ffi::BoxTuple>) -> Self {
unsafe { ffi::box_tuple_ref(ptr.as_mut()) };
Tuple { ptr }
}
#[inline(always)]
pub fn try_from_ptr(ptr: *mut ffi::BoxTuple) -> Option<Self> {
NonNull::new(ptr).map(Self::from_ptr)
}
/// Return the number of fields in tuple (the size of MsgPack Array).
#[inline(always)]
pub fn len(&self) -> u32 {
unsafe { ffi::box_tuple_field_count(self.ptr.as_ptr()) }
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Will return the number of bytes in the tuple.
///
/// With both the memtx storage engine and the vinyl storage engine the default maximum is one megabyte
/// (`memtx_max_tuple_size` or `vinyl_max_tuple_size`). Every field has one or more "length" bytes preceding the
/// actual contents, so `bsize()` returns a value which is slightly greater than the sum of the lengths of the
/// contents.
///
/// The value does not include the size of "struct tuple"
/// (for the current size of this structure look in the tuple.h file in Tarantool’s source code).
#[inline(always)]
pub fn bsize(&self) -> usize {
unsafe { self.ptr.as_ref().bsize() }
}
/// Return the associated format.
#[inline(always)]
pub fn format(&self) -> TupleFormat {
TupleFormat {
inner: unsafe { ffi::box_tuple_format(self.ptr.as_ptr()) },
}
}
/// Allocate and initialize a new `Tuple` iterator. The `Tuple` iterator
/// allow to iterate over fields at root level of MsgPack array.
///
/// Example:
/// ```no_run
/// # fn foo<T: serde::de::DeserializeOwned>(tuple: tarantool::tuple::Tuple) {
/// let mut it = tuple.iter().unwrap();
///
/// while let Some(field) = it.next::<T>().unwrap() {
/// // process data
/// }
///
/// // rewind iterator to first position
/// it.rewind();
/// assert!(it.position() == 0);
///
/// // rewind iterator to first position
/// let field = it.seek::<T>(3).unwrap();
/// assert!(it.position() == 4);
/// }
/// ```
#[inline]
pub fn iter(&self) -> Result<TupleIterator> {
let inner = unsafe { ffi::box_tuple_iterator(self.ptr.as_ptr()) };
if inner.is_null() {
Err(TarantoolError::last().into())
} else {
Ok(TupleIterator { inner })
}
}
/// Deserialize a tuple field specified by zero-based array index.
///
/// - `fieldno` - zero-based index in MsgPack array.
///
/// Returns:
/// - `Ok(None)` if `fieldno >= self.len()`
/// - `Err(e)` if deserialization failed
/// - `Ok(Some(field value))` otherwise
///
/// See also [`Tuple::try_get`], [`Tuple::get`].
#[inline(always)]
pub fn field<'a, T>(&'a self, fieldno: u32) -> Result<Option<T>>
where
T: Decode<'a>,
{
unsafe {
let field_ptr = ffi::box_tuple_field(self.ptr.as_ptr(), fieldno);
field_value_from_ptr(field_ptr as _)
}
}
/// Deserialize a tuple field specified by an index implementing
/// [`TupleIndex`] trait.
///
/// Currently 2 types of indexes are supported:
/// - `u32` - zero-based index in MsgPack array (See also [`Tuple::field`])
/// - `&str` - JSON path for tuples with non default formats
///
/// **NOTE**: getting tuple fields by JSON paths is not supported in all
/// tarantool versions. Use [`tarantool::ffi::has_tuple_field_by_path`] to
/// check whether it's supported in your case.
/// If `has_tuple_field_by_path` returns `false` this function will always
/// return `Err`.
///
/// Returns:
/// - `Ok(None)` if index wasn't found
/// - `Err(e)` if deserialization failed (or api not supported)
/// - `Ok(Some(field value))` otherwise
///
/// See also [`Tuple::get`].
///
/// [`tarantool::ffi::has_tuple_field_by_path`]:
/// crate::ffi::has_tuple_field_by_path
#[inline(always)]
pub fn try_get<'a, I, T>(&'a self, key: I) -> Result<Option<T>>
where
I: TupleIndex,
T: Decode<'a>,
{
key.get_field(self)
}
/// Deserialize a tuple field specified by an index implementing
/// [`TupleIndex`] trait.
///
/// Currently 2 types of indexes are supported:
/// - `u32` - zero-based index in MsgPack array (See also [`Tuple::field`])
/// - `&str` - JSON path for tuples with non default formats
///
/// **NOTE**: getting tuple fields by JSON paths is not supported in all
/// tarantool versions. Use [`tarantool::ffi::has_tuple_field_by_path`] to
/// check whether it's supported in your case.
/// If `has_tuple_field_by_path` returns `false` this function will always
/// **panic**.
///
/// Returns:
/// - `None` if index wasn't found
/// - **panics** if deserialization failed (or api not supported)
/// - `Some(field value)` otherwise
///
/// See also [`Tuple::get`].
///
/// [`tarantool::ffi::has_tuple_field_by_path`]:
/// crate::ffi::has_tuple_field_by_path
#[inline(always)]
#[track_caller]
pub fn get<'a, I, T>(&'a self, key: I) -> Option<T>
where
I: TupleIndex,
T: Decode<'a>,
{
self.try_get(key).expect("Error during getting tuple field")
}
/// Decode tuple contents as `T`.
///
/// **NOTE**: Because [`Tuple`] implements [`DecodeOwned`], you can do
/// something like this
/// ```no_run
/// use tarantool::tuple::{Decode, Tuple};
/// let tuple: Tuple;
/// # tuple = Tuple::new(&[1, 2, 3]).unwrap();
/// let deep_copy: Tuple = tuple.decode().unwrap();
/// let inc_ref_count: Tuple = tuple.clone();
/// ```
/// "Decoding" a `Tuple` into a `Tuple` will basically perform a **deep
/// copy** of its contents, while `tuple.clone()` will just increase tuple's
/// reference count. There's probably no use case for deep copying the
/// tuple, because there's actully no way to move data out of it, so keep
/// this in mind.
#[inline]
pub fn decode<T>(&self) -> Result<T>
where
T: DecodeOwned,
{
let raw_data = self.as_buffer();
Decode::decode(&raw_data)
}
#[inline]
pub(crate) fn as_buffer(&self) -> Vec<u8> {
let size = self.bsize();
let mut buf = Vec::with_capacity(size);
unsafe {
let actual_size = ffi::box_tuple_to_buf(self.ptr.as_ptr(), buf.as_ptr() as _, size);
buf.set_len(actual_size as usize);
}
buf
}
#[inline(always)]
pub(crate) fn into_ptr(self) -> *mut ffi::BoxTuple {
self.ptr.as_ptr()
}
}
////////////////////////////////////////////////////////////////////////////////
/// TupleIndex
////////////////////////////////////////////////////////////////////////////////
/// Types implementing this trait can be used as arguments for the
/// [`Tuple::get`] method.
///
/// This is a helper trait, so you don't want to use it directly.
pub trait TupleIndex {
fn get_field<'a, T>(self, tuple: &'a Tuple) -> Result<Option<T>>
where
T: Decode<'a>;
}
impl TupleIndex for u32 {
#[inline(always)]
fn get_field<'a, T>(self, tuple: &'a Tuple) -> Result<Option<T>>
where
T: Decode<'a>,
{
tuple.field(self)
}
}
impl TupleIndex for &str {
#[inline(always)]
fn get_field<'a, T>(self, tuple: &'a Tuple) -> Result<Option<T>>
where
T: Decode<'a>,
{
use once_cell::sync::Lazy;
use std::io::{Error as IOError, ErrorKind};
static API: Lazy<std::result::Result<Api, dlopen::Error>> = Lazy::new(|| unsafe {
let c_str = std::ffi::CStr::from_bytes_with_nul_unchecked;
let lib = dlopen::symbor::Library::open_self()?;
let err = match lib.symbol_cstr(c_str(ffi::TUPLE_FIELD_BY_PATH_NEW_API.as_bytes())) {
Ok(api) => return Ok(Api::New(*api)),
Err(e) => e,
};
if let Ok(api) = lib.symbol_cstr(c_str(ffi::TUPLE_FIELD_BY_PATH_OLD_API.as_bytes())) {
return Ok(Api::Old(*api));
}
Err(err)
});
return match API.as_ref() {
Ok(Api::New(api)) => unsafe {
let field_ptr = api(tuple.ptr.as_ptr(), self.as_ptr() as _, self.len() as _, 1);
field_value_from_ptr(field_ptr as _)
},
Ok(Api::Old(api)) => unsafe {
let data_offset = tuple.ptr.as_ref().data_offset() as _;
let data = tuple.ptr.as_ptr().cast::<c_char>().add(data_offset);
let field_ptr = api(
tuple.format().inner,
data,
data as _,
self.as_ptr() as _,
self.len() as _,
tlua::util::hash(self),
);
field_value_from_ptr(field_ptr as _)
},
Err(e) => Err(Error::IO(IOError::new(ErrorKind::Unsupported, e))),
};
enum Api {
/// Before 2.10 private api `tuple_field_raw_by_full_path`
Old(
extern "C" fn(
format: *const ffi::BoxTupleFormat,
tuple: *const c_char,
field_map: *const u32,
path: *const c_char,
path_len: u32,
path_hash: u32,
) -> *const c_char,
),
/// After 2.10 public api `box_tuple_field_by_path`
New(
extern "C" fn(
tuple: *const ffi::BoxTuple,
path: *const c_char,
path_len: u32,
index_base: i32,
) -> *const c_char,
),
}
}
}
impl From<&TupleBuffer> for Tuple {
#[inline(always)]
fn from(buf: &TupleBuffer) -> Self {
unsafe { Self::from_raw_data(buf.as_ptr() as _, buf.len() as _) }
}
}
impl Drop for Tuple {
#[inline(always)]
fn drop(&mut self) {
unsafe { ffi::box_tuple_unref(self.ptr.as_ptr()) };
}
}
impl Clone for Tuple {
#[inline(always)]
fn clone(&self) -> Self {
unsafe { ffi::box_tuple_ref(self.ptr.as_ptr()) };
Tuple { ptr: self.ptr }
}
}
////////////////////////////////////////////////////////////////////////////////
/// ToTupleBuffer
////////////////////////////////////////////////////////////////////////////////
/// Types implementing this trait can be converted to tarantool tuple (msgpack
/// array).
pub trait ToTupleBuffer {
#[inline]
fn to_tuple_buffer(&self) -> Result<TupleBuffer> {
let mut buf = Vec::with_capacity(128);
self.write_tuple_data(&mut buf)?;
TupleBuffer::try_from_vec(buf)
}
/// Returns a slice of bytes represeting the underlying tarantool tuple.
///
/// Returns `None` if `Self` doesn't contain the data, in which case the
/// [`ToTupleBuffer::to_tuple_buffer`] should be used.
///
/// This method exists as an optimization for wrapper types to eliminate
/// extra copies, in cases where the implementing type already contains the
/// tuple data (e.g. [`TupleBuffer`], [`RawBytes`], etc.).
#[inline(always)]
fn tuple_data(&self) -> Option<&[u8]> {
None
}
fn write_tuple_data(&self, w: &mut impl Write) -> Result<()>;
}
impl ToTupleBuffer for Tuple {
#[inline(always)]
fn to_tuple_buffer(&self) -> Result<TupleBuffer> {
Ok(TupleBuffer::from(self))
}
#[inline]
fn write_tuple_data(&self, w: &mut impl Write) -> Result<()> {
w.write_all(&self.as_buffer()).map_err(Into::into)
}
}
impl<T> ToTupleBuffer for T
where
T: ?Sized,
T: Encode,
{
#[inline(always)]
fn write_tuple_data(&self, w: &mut impl Write) -> Result<()> {
self.encode(w)
}
}
////////////////////////////////////////////////////////////////////////////////
/// Encode
////////////////////////////////////////////////////////////////////////////////
/// Types implementing this trait can be serialized into a valid tarantool tuple
/// (msgpack array).
// TODO: remove this trait when `specialization` feature is stabilized
// https://github.com/rust-lang/rust/issues/31844
pub trait Encode: Serialize {
#[inline(always)]
fn encode(&self, w: &mut impl Write) -> Result<()> {
rmp_serde::encode::write(w, self).map_err(Into::into)
}
}
impl<'a, T> Encode for &'a T
where
T: Encode,
{
#[inline(always)]
fn encode(&self, w: &mut impl Write) -> Result<()> {
T::encode(*self, w)
}
}
impl Encode for () {
#[inline(always)]
fn encode(&self, w: &mut impl Write) -> Result<()> {
rmp_serde::encode::write(w, &Vec::<()>::new()).map_err(Into::into)
}
}
impl<T> Encode for [T] where T: Serialize {}
impl<T> Encode for Vec<T> where T: Serialize {}
macro_rules! impl_array {
($($n:literal)+) => {
$(
#[allow(clippy::zero_prefixed_literal)]
impl<T> Encode for [T; $n] where T: Serialize {}
)+
}
}
impl_array! {
00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
}
macro_rules! impl_tuple {
() => {};
($h:ident $($t:ident)*) => {
impl<$h, $($t),*> Encode for ($h, $($t),*)
where
$h: Serialize,
$($t: Serialize,)*
{}
impl_tuple! { $($t)* }
}
}
impl_tuple! { A B C D E F G H I J K L M N O P }
////////////////////////////////////////////////////////////////////////////////
/// TupleBuffer
////////////////////////////////////////////////////////////////////////////////
/// Buffer containing tuple contents (MsgPack array)
#[derive(Clone, PartialEq, Eq)]
pub struct TupleBuffer(
// TODO(gmoshkin): previously TupleBuffer would use tarantool's transaction
// scoped memory allocator, but it would do so in a confusingly inefficient
// and error prone manner (redundant copies and use after free).
//
// This doesn't mean however that there's no point in using box_txn_alloc,
// but at this time I don't see an easy way to leave it within the current
// state of TupleBuffer.
//
// There might be a use for box_txn_alloc from within
// transaction::start_transaction, but a well thought through api is needed.
//
// TODO(gmoshkin): use smallvec::SmallVec instead
Vec<u8>,
);
impl TupleBuffer {
/// Get raw pointer to buffer.
#[inline(always)]
pub fn as_ptr(&self) -> *const u8 {
self.0.as_ptr()
}
/// Return the number of bytes used in memory by the tuple.
#[inline(always)]
pub fn len(&self) -> usize {
self.0.len()
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// # Safety
/// `buf` must be a valid message pack array
#[track_caller]
#[inline(always)]
pub unsafe fn from_vec_unchecked(buf: Vec<u8>) -> Self {
Self(buf)
}
#[inline]
pub fn try_from_vec(data: Vec<u8>) -> Result<Self> {
let data = validate_msgpack(data)?;
unsafe { Ok(Self::from_vec_unchecked(data)) }
}
}
impl AsRef<[u8]> for TupleBuffer {
#[inline(always)]
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl From<TupleBuffer> for Vec<u8> {
#[inline(always)]
fn from(b: TupleBuffer) -> Self {
b.0
}
}
impl TryFrom<Vec<u8>> for TupleBuffer {
type Error = Error;
#[inline(always)]
fn try_from(data: Vec<u8>) -> Result<Self> {
Self::try_from_vec(data)
}
}
impl From<Tuple> for TupleBuffer {
#[inline(always)]
fn from(t: Tuple) -> Self {
Self(t.as_buffer())
}
}
impl From<&Tuple> for TupleBuffer {
#[inline(always)]
fn from(t: &Tuple) -> Self {
Self(t.as_buffer())
}
}
impl Debug for TupleBuffer {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if let Ok(v) = rmpv::Value::decode(&self.0) {
f.debug_tuple("TupleBuffer").field(&v).finish()
} else {
f.debug_tuple("TupleBuffer").field(&self.0).finish()
}
}
}
impl ToTupleBuffer for TupleBuffer {
#[inline(always)]
fn to_tuple_buffer(&self) -> Result<TupleBuffer> {
Ok(self.clone())
}
#[inline(always)]
fn tuple_data(&self) -> Option<&[u8]> {
Some(&self.0)
}
#[inline(always)]
fn write_tuple_data(&self, w: &mut impl Write) -> Result<()> {
w.write_all(self.as_ref()).map_err(Into::into)
}
}
impl serde_bytes::Serialize for TupleBuffer {
#[inline(always)]
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serde_bytes::Serialize::serialize(&self.0, serializer)
}
}
impl<'de> serde_bytes::Deserialize<'de> for TupleBuffer {
#[inline]
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let tmp: Vec<u8> = serde_bytes::Deserialize::deserialize(deserializer)?;
Self::try_from(tmp).map_err(serde::de::Error::custom)
}
}
////////////////////////////////////////////////////////////////////////////////
/// TupleFormat
////////////////////////////////////////////////////////////////////////////////
/// Tuple format
///
/// Each Tuple has associated format (class). Default format is used to
/// create tuples which are not attach to any particular space.
pub struct TupleFormat {
inner: *mut ffi::BoxTupleFormat,
}
impl Default for TupleFormat {
#[inline(always)]
fn default() -> Self {
TupleFormat {
inner: unsafe { ffi::box_tuple_format_default() },
}
}
}
impl Debug for TupleFormat {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.inner == Self::default().inner {
f.write_str("TupleFormat::default()")
} else {
f.debug_tuple("TupleFormat").field(&self.inner).finish()
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// TupleIterator
////////////////////////////////////////////////////////////////////////////////
/// Tuple iterator
pub struct TupleIterator {
inner: *mut ffi::BoxTupleIterator,
}
impl Debug for TupleIterator {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("TupleIterator")
.field("position", &self.position())
.finish()
}
}
impl TupleIterator {
/// Return zero-based next position in iterator.
///
/// That is, this function return the field id of field that will be
/// returned by the next call to `box_tuple_next(it)`. Returned value is zero
/// after initialization or rewind and `box_tuple_field_count(Tuple)`
/// after the end of iteration.
#[inline(always)]
pub fn position(&self) -> u32 {
unsafe { ffi::box_tuple_position(self.inner) }
}
/// Rewind iterator to the initial position.
#[inline(always)]
pub fn rewind(&mut self) {
unsafe { ffi::box_tuple_rewind(self.inner) }
}
/// Seek the Tuple iterator.
///
/// Requested fieldno returned by next call to `box_tuple_next(it)`.
///
/// - `fieldno` - zero-based position in MsgPack array.
///
/// After call:
/// - `box_tuple_position(it) == fieldno` if returned value is not `None`
/// - `box_tuple_position(it) == box_tuple_field_count(Tuple)` if returned value is `None`.
#[inline]
pub fn seek<'t, T>(&'t mut self, fieldno: u32) -> Result<Option<T>>
where
T: Decode<'t>,
{
unsafe { field_value_from_ptr(ffi::box_tuple_seek(self.inner, fieldno) as _) }
}
/// Return the next Tuple field from Tuple iterator.
///
/// Returns:
/// - `None` if `i >= box_tuple_field_count(Tuple)` or if field has a non primitive type
/// - field value otherwise
///
/// After call:
/// - `box_tuple_position(it) == fieldno` if returned value is not `None`
/// - `box_tuple_position(it) == box_tuple_field_count(Tuple)` if returned value is `None`.
#[allow(clippy::should_implement_trait)]
#[inline]
pub fn next<'t, T>(&'t mut self) -> Result<Option<T>>
where
T: Decode<'t>,
{
unsafe { field_value_from_ptr(ffi::box_tuple_next(self.inner) as _) }
}
pub fn update(&mut self) {}
}
impl Drop for TupleIterator {
#[inline(always)]
fn drop(&mut self) {
unsafe { ffi::box_tuple_iterator_free(self.inner) }
}
}
impl TupleIterator {}
////////////////////////////////////////////////////////////////////////////////
// FieldType
////////////////////////////////////////////////////////////////////////////////
crate::define_str_enum! {
pub enum FieldType {
Any = "any",
Unsigned = "unsigned",
String = "string",
Number = "number",
Double = "double",
Integer = "integer",
Boolean = "boolean",
Varbinary = "varbinary",
Scalar = "scalar",
Decimal = "decimal",
Uuid = "uuid",
Datetime = "datetime",
Array = "array",
Map = "map",
}
}
impl Default for FieldType {
#[inline(always)]
fn default() -> Self {
Self::Any
}
}
impl From<index::FieldType> for FieldType {
#[rustfmt::skip]
fn from(t: index::FieldType) -> Self {
match t {
// "any" type is not supported as index part,
// that's the only reason we need 2 enums.
index::FieldType::Unsigned => Self::Unsigned,
index::FieldType::String => Self::String,
index::FieldType::Number => Self::Number,
index::FieldType::Double => Self::Double,
index::FieldType::Integer => Self::Integer,
index::FieldType::Boolean => Self::Boolean,
index::FieldType::Varbinary => Self::Varbinary,
index::FieldType::Scalar => Self::Scalar,
index::FieldType::Decimal => Self::Decimal,
index::FieldType::Uuid => Self::Uuid,
index::FieldType::Datetime => Self::Datetime,
index::FieldType::Array => Self::Array,
}
}
}
////////////////////////////////////////////////////////////////////////////////
// KeyDef
////////////////////////////////////////////////////////////////////////////////
/// An object which describes how to extract a key for a given tarantool index
/// from a tuple. Basically it contains information the parts of the key,
/// specifically location of the parts within the tuple, their types, their
/// nullability and collation.
///
/// Can be used to
/// - compare tuples ([`Self::compare`])
/// - extract a key from a tuple ([`Self::extract_key`])
/// - check if a tuple has the expected format ([`Self::validate_tuple`])
/// - etc.
///
/// You can construct one of these from an explicit list of key part definitions
/// using [`Self::new`], or automtically from an index's metadata like so:
/// ```no_run
/// # use tarantool::index::Index;
/// # use tarantool::space::Space;
/// # use tarantool::tuple::KeyDef;
/// let space = Space::find("some_space").unwrap();
/// let index = space.index("some_index").unwrap();
/// let meta = index.meta().unwrap();
/// let key_def: KeyDef = meta.to_key_def();
/// ```
#[derive(Debug)]
pub struct KeyDef {
inner: NonNull<ffi::BoxKeyDef>,
}
#[derive(Default, Debug, PartialEq, Eq, Hash)]
pub struct KeyDefPart<'a> {
pub field_no: u32,
pub field_type: FieldType,
pub collation: Option<Cow<'a, CStr>>,
pub is_nullable: bool,
pub path: Option<Cow<'a, CStr>>,
}
impl<'a> KeyDefPart<'a> {
fn as_tt(&self) -> ffi::box_key_part_def_t {
let flags = if self.is_nullable {
ffi::BoxKeyDefPartFlag::IS_NULLABLE.bits()
} else {
0
};
ffi::box_key_part_def_t {
meat: ffi::BoxKeyDefPart {
fieldno: self.field_no,
field_type: self.field_type.as_cstr().as_ptr(),
flags,
collation: self
.collation
.as_deref()
.map(CStr::as_ptr)
.unwrap_or(null()),
path: self.path.as_deref().map(CStr::as_ptr).unwrap_or(null()),
},
}
}
pub fn try_from_index_part(p: &'a index::Part) -> Option<Self> {
let field_no = match p.field {
NumOrStr::Num(field_no) => field_no,
NumOrStr::Str(_) => return None,
};
let collation = p.collation.as_deref().map(|s| {
CString::new(s)
.expect("it's your fault if you put '\0' in collation")
.into()
});
let path = p.path.as_deref().map(|s| {
CString::new(s)
.expect("it's your fault if you put '\0' in collation")
.into()
});
Some(Self {
field_no,
field_type: p.r#type.map(From::from).unwrap_or(FieldType::Any),
is_nullable: p.is_nullable.unwrap_or(false),
collation,
path,
})
}
}
impl KeyDef {
/// Create key definition with key fields with passed typed on passed positions.
/// May be used for tuple format creation and/or tuple comparison.
///
/// - `items` - array with key field identifiers and key field types (see [FieldType](struct.FieldType.html))
#[inline]
pub fn new<'a>(parts: impl IntoIterator<Item = &'a KeyDefPart<'a>>) -> Result<Self> {
let mut tt_parts = parts.into_iter().map(KeyDefPart::as_tt).collect::<Vec<_>>();
let ptr = unsafe { ffi::box_key_def_new_v2(tt_parts.as_mut_ptr(), tt_parts.len() as _) };
let inner = NonNull::new(ptr).ok_or_else(TarantoolError::last)?;
Ok(KeyDef { inner })
}
/// Compare tuples using the key definition.
///
/// - `tuple_a` - first tuple
/// - `tuple_b` - second tuple
///
/// Returns:
/// - `Ordering::Equal` if `key_fields(tuple_a) == key_fields(tuple_b)`
/// - `Ordering::Less` if `key_fields(tuple_a) < key_fields(tuple_b)`
/// - `Ordering::Greater` if `key_fields(tuple_a) > key_fields(tuple_b)`
#[inline(always)]
pub fn compare(&self, tuple_a: &Tuple, tuple_b: &Tuple) -> Ordering {
unsafe {
ffi::box_tuple_compare(
tuple_a.ptr.as_ptr(),
tuple_b.ptr.as_ptr(),
self.inner.as_ptr(),
)
.cmp(&0)
}
}
/// Compare tuple with key using the key definition.
///
/// - `tuple` - tuple
/// - `key` - key with MessagePack array header
///
/// Returns:
/// - `Ordering::Equal` if `key_fields(tuple) == parts(key)`
/// - `Ordering::Less` if `key_fields(tuple) < parts(key)`
/// - `Ordering::Greater` if `key_fields(tuple) > parts(key)`
#[inline]
pub fn compare_with_key<K>(&self, tuple: &Tuple, key: &K) -> Ordering
where
K: ToTupleBuffer + ?Sized,
{
let key_buf = key.to_tuple_buffer().unwrap();
let key_buf_ptr = key_buf.as_ptr() as _;
unsafe {
ffi::box_tuple_compare_with_key(tuple.ptr.as_ptr(), key_buf_ptr, self.inner.as_ptr())
.cmp(&0)
}
}
/// Checks if `tuple` satisfies the key definition's format, i.e. do the
/// tuple's fields described the `self`'s key parts have the same types.
/// Note that the tuple may still not satisfy the full format of the space,
/// this function only checks if it contains a part which could be used as
/// a key of an index.
///
/// There's currently no good way of checking if the tuple satisfies the
/// format of the space other than trying to insert into that space.
///
/// This function is used internally by [`Self::extract_key`] to check if
/// it's safe to extract the key described by this `KeyDef` from a given tuple.
#[inline]
pub fn validate_tuple(&self, tuple: &Tuple) -> Result<()> {
// SAFETY: safe as long as both pointers are valid.
let rc =
unsafe { ffi::box_key_def_validate_tuple(self.inner.as_ptr(), tuple.ptr.as_ptr()) };
if rc != 0 {
return Err(TarantoolError::last().into());
}
Ok(())
}
/// Extracts the key described by this `KeyDef` from `tuple`.
/// Returns an error if `tuple` doesn't satisfy this `KeyDef`.
#[inline]
pub fn extract_key(&self, tuple: &Tuple) -> Result<TupleBuffer> {
self.validate_tuple(tuple)?;
let res;
// SAFETY: safe, because we only truncate the region to where it was
// before the call to this function.
unsafe {
let used_before = ffi::box_region_used();
let data = self.extract_key_raw(tuple, -1)?;
res = TupleBuffer::from_vec_unchecked(data.into());
ffi::box_region_truncate(used_before);
}
Ok(res)
}
/// Extracts the key described by this `KeyDef` from `tuple`.
///
/// TODO: what is `multikey_idx`? Pass a `-1` as the default value.
///
/// Returns an error in case memory runs out.
///
/// # Safety
/// `tuple` must satisfy the key definition's format.
/// Use [`Self::extract_key`] if you want the tuple to be validated automatically,
/// or use [`Self::validate_tuple`] to validate the tuple explicitly.
#[inline]
pub unsafe fn extract_key_raw<'box_region>(
&self,
tuple: &Tuple,
multikey_idx: i32,
) -> Result<&'box_region [u8]> {
let slice;
// SAFETY: safe as long as both pointers are valid.
unsafe {
let mut size = 0;
let data = ffi::box_key_def_extract_key(
self.inner.as_ptr(),
tuple.ptr.as_ptr(),
multikey_idx,
&mut size,
);
if data.is_null() {
return Err(TarantoolError::last().into());
}
slice = std::slice::from_raw_parts(data as _, size as _);
}
Ok(slice)
}
/// Calculate a tuple hash for a given key definition.
/// At the moment 32-bit murmur3 hash is used but it may
/// change in future.
///
/// - `tuple` - tuple
///
/// Returns:
/// - 32-bit murmur3 hash value
#[cfg(feature = "picodata")]
pub fn hash(&self, tuple: &Tuple) -> u32 {
unsafe { ffi::box_tuple_hash(tuple.ptr.as_ptr(), self.inner.as_ptr()) }
}
}
impl Drop for KeyDef {
#[inline(always)]
fn drop(&mut self) {
unsafe { ffi::box_key_def_delete(self.inner.as_ptr()) }
}
}
impl std::convert::TryFrom<&index::Metadata<'_>> for KeyDef {
type Error = index::FieldMustBeNumber;
#[inline(always)]
fn try_from(meta: &index::Metadata<'_>) -> std::result::Result<Self, Self::Error> {
meta.try_to_key_def()
}
}
unsafe fn field_value_from_ptr<'de, T>(field_ptr: *mut u8) -> Result<Option<T>>
where
T: Decode<'de>,
{
if field_ptr.is_null() {
return Ok(None);
}
// Theoretically this is an exploit point, which would allow reading up to
// 2gigs of memory in case `value_ptr` happens to point to memory which
// isn't a field of a tuple, but is a valid messagepack value
let max_len = u32::MAX >> 1;
let rough_slice = std::slice::from_raw_parts(field_ptr, max_len as _);
let mut cursor = std::io::Cursor::new(rough_slice);
let start = cursor.position() as usize;
// There's overhead for iterating over the whole msgpack value, but this is
// necessary.
crate::msgpack::skip_value(&mut cursor)?;
let value_range = start..(cursor.position() as usize);
let rough_slice = cursor.into_inner();
let value_slice = &rough_slice[value_range];
Ok(Some(T::decode(value_slice)?))
}
////////////////////////////////////////////////////////////////////////////////
/// FunctionCtx
////////////////////////////////////////////////////////////////////////////////
#[repr(C)]
#[derive(Debug)]
pub struct FunctionCtx {
inner: *mut ffi::BoxFunctionCtx,
}
impl FunctionCtx {
/// Return a Tuple from stored procedure.
///
/// Returned Tuple is automatically reference counted by Tarantool.
///
/// - `tuple` - a Tuple to return
#[inline]
pub fn return_tuple(&self, tuple: &Tuple) -> Result<c_int> {
let result = unsafe { ffi::box_return_tuple(self.inner, tuple.ptr.as_ptr()) };
if result < 0 {
Err(TarantoolError::last().into())
} else {
Ok(result)
}
}
/// Return a value encoded as MessagePack from a stored procedure.
///
/// MessagePack is not validated, for the sake of speed. It is
/// expected to be a single encoded object. An attempt to encode
/// and return multiple objects without wrapping them into an
/// `MP_ARRAY` or `MP_MAP` is undefined behaviour.
///
/// - `value` - value to be encoded to MessagePack
#[inline]
pub fn return_mp<T>(&self, value: &T) -> Result<c_int>
where
T: Serialize + ?Sized,
{
let buf = rmp_serde::to_vec_named(value)?;
self.return_bytes(&buf)
}
/// Return raw bytes representing a MessagePack value from a stored
/// procedure.
///
/// MessagePack is not validated, for the sake of speed. It is
/// expected to be a single encoded object. An attempt to encode
/// and return multiple objects without wrapping them into an
/// `MP_ARRAY` or `MP_MAP` is undefined behaviour.
///
/// - `bytes` - raw msgpack bytes to be returned
#[inline]
pub fn return_bytes(&self, bytes: &[u8]) -> Result<c_int> {
let Range { start, end } = bytes.as_ptr_range();
let result = unsafe { ffi::box_return_mp(self.inner, start as _, end as _) };
if result < 0 {
Err(TarantoolError::last().into())
} else {
Ok(result)
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// FunctionArgs
////////////////////////////////////////////////////////////////////////////////
#[repr(C)]
pub struct FunctionArgs {
pub start: *const u8,
pub end: *const u8,
}
impl Debug for FunctionArgs {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_tuple("FunctionArgs")
.field(&Tuple::from(self))
.finish()
}
}
impl From<FunctionArgs> for Tuple {
#[inline(always)]
fn from(args: FunctionArgs) -> Tuple {
Tuple::from(&args)
}
}
impl From<&FunctionArgs> for Tuple {
#[inline(always)]
fn from(args: &FunctionArgs) -> Tuple {
unsafe { Tuple::from_raw_data(args.start as _, args.end.offset_from(args.start) as _) }
}
}
impl FunctionArgs {
/// Decode the msgpack value represented by the function args.
#[inline(always)]
pub fn decode<'a, T>(&'a self) -> Result<T>
where
T: Decode<'a>,
{
let slice = unsafe {
std::slice::from_raw_parts(self.start, self.end.offset_from(self.start) as _)
};
T::decode(slice)
}
}
/// Push MessagePack data into a session data channel - socket,
/// console or whatever is behind the session. Note, that
/// successful push does not guarantee delivery in case it was sent
/// into the network. Just like with `write()`/`send()` system calls.
#[inline]
pub fn session_push<T>(value: &T) -> Result<()>
where
T: ToTupleBuffer + ?Sized,
{
let buf = value.to_tuple_buffer().unwrap();
let buf_ptr = buf.as_ptr() as *const c_char;
if unsafe { ffi::box_session_push(buf_ptr, buf_ptr.add(buf.len())) } < 0 {
Err(TarantoolError::last().into())
} else {
Ok(())
}
}
#[inline]
fn validate_msgpack<T>(data: T) -> Result<T>
where
T: AsRef<[u8]> + Into<Vec<u8>>,
{
let mut slice = data.as_ref();
let m = rmp::decode::read_marker(&mut slice)?;
if !matches!(m, Marker::FixArray(_) | Marker::Array16 | Marker::Array32) {
return Err(error::Encode::InvalidMP(data.into()).into());
}
Ok(data)
}
impl<L> tlua::Push<L> for Tuple
where
L: tlua::AsLua,
{
type Err = tlua::Void;
#[inline(always)]
fn push_to_lua(&self, lua: L) -> tlua::PushResult<L, Self> {
unsafe {
ffi::luaT_pushtuple(tlua::AsLua::as_lua(&lua), self.ptr.as_ptr());
Ok(tlua::PushGuard::new(lua, 1))
}
}
}
impl<L> tlua::PushOne<L> for Tuple where L: tlua::AsLua {}
impl<L> tlua::PushInto<L> for Tuple
where
L: tlua::AsLua,
{
type Err = tlua::Void;
#[inline(always)]
fn push_into_lua(self, lua: L) -> tlua::PushResult<L, Self> {
unsafe {
ffi::luaT_pushtuple(tlua::AsLua::as_lua(&lua), self.ptr.as_ptr());
Ok(tlua::PushGuard::new(lua, 1))
}
}
}
impl<L> tlua::PushOneInto<L> for Tuple where L: tlua::AsLua {}
impl<L> tlua::LuaRead<L> for Tuple
where
L: tlua::AsLua,
{
fn lua_read_at_position(lua: L, index: std::num::NonZeroI32) -> tlua::ReadResult<Self, L> {
let lua_ptr = tlua::AsLua::as_lua(&lua);
let mut ptr = unsafe { ffi::luaT_istuple(lua_ptr, index.get()) };
if ptr.is_null() {
let format = TupleFormat::default();
ptr = unsafe { ffi::luaT_tuple_new(lua_ptr, index.get(), format.inner) };
}
Self::try_from_ptr(ptr).ok_or_else(|| {
let e = tlua::WrongType::info("reading tarantool tuple")
.expected_type::<Self>()
.actual_single_lua(&lua, index);
(lua, e)
})
}
}
impl<L> tlua::LuaRead<L> for TupleBuffer
where
L: tlua::AsLua,
{
fn lua_read_at_position(lua: L, index: std::num::NonZeroI32) -> tlua::ReadResult<Self, L> {
unsafe {
let svp = ffi::box_region_used();
let lua_ptr = tlua::AsLua::as_lua(&lua);
let ptr = ffi::luaT_istuple(lua_ptr, index.get());
if let Some(tuple) = Tuple::try_from_ptr(ptr) {
return Ok(Self::from(tuple));
}
let mut len = 0;
let data = ffi::luaT_tuple_encode(lua_ptr, index.get(), &mut len);
if data.is_null() {
let e = tlua::WrongType::info("converting Lua value to tarantool tuple")
.expected("msgpack array")
.actual(format!("error: {}", TarantoolError::last().message()));
return Err((lua, e));
}
let data = std::slice::from_raw_parts(data, len);
let data = Vec::from(data);
ffi::box_region_truncate(svp);
Ok(Self::from_vec_unchecked(data))
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Decode
////////////////////////////////////////////////////////////////////////////////
/// Types implementing this trait can be decoded from msgpack.
///
/// [`Tuple`] also implements [`Decode`] with an implementation which just
/// copies the bytes as is (and validates them).
pub trait Decode<'de>: Sized {
fn decode(data: &'de [u8]) -> Result<Self>;
}
impl<'de, T> Decode<'de> for T
where
T: serde::Deserialize<'de>,
{
#[inline(always)]
fn decode(data: &'de [u8]) -> Result<Self> {
rmp_serde::from_slice(data).map_err(|e| Error::decode::<T>(e, data.into()))
}
}
impl Decode<'_> for Tuple {
#[inline(always)]
fn decode(data: &[u8]) -> Result<Self> {
Self::try_from_slice(data)
}
}
/// Types implementing this trait can be decoded from msgpack by value.
///
/// `DecodeOwned` is to [`Decode`] what [`DeserializeOwned`] is to
/// [`Deserialize`].
///
/// [`Deserialize`]: serde::Deserialize
/// [`DeserializeOwned`]: serde::de::DeserializeOwned
pub trait DecodeOwned: for<'de> Decode<'de> {}
impl<T> DecodeOwned for T where T: for<'de> Decode<'de> {}
////////////////////////////////////////////////////////////////////////////////
/// RawBytes
////////////////////////////////////////////////////////////////////////////////
/// A wrapper type for reading raw bytes from a tuple.
///
/// Can be used to read a field of a tuple as raw bytes:
/// ```no_run
/// use tarantool::{tuple::Tuple, tuple::RawBytes};
/// let tuple = Tuple::new(&(1, (2, 3, 4), 5)).unwrap();
/// let second_field: &RawBytes = tuple.get(1).unwrap();
/// assert_eq!(&**second_field, &[0x93, 2, 3, 4]);
/// ```
///
/// This type also implements [`ToTupleBuffer`] such that `to_tuple_buffer`
/// returns `Ok` only if the underlying bytes represent a valid tuple (msgpack
/// array).
#[derive(Debug)]
#[repr(transparent)]
pub struct RawBytes(pub [u8]);
impl RawBytes {
/// Convert a slice of bytes `data` into a `&RawBytes`.
#[inline(always)]
pub fn new(data: &[u8]) -> &Self {
// SAFETY: this is safe, because `RawBytes` has `#[repr(transparent)]`
unsafe { &*(data as *const [u8] as *const RawBytes) }
}
}
impl<'a> From<&'a [u8]> for &'a RawBytes {
#[inline(always)]
fn from(data: &'a [u8]) -> Self {
RawBytes::new(data)
}
}
impl<'de> Decode<'de> for &'de RawBytes {
#[inline(always)]
fn decode(data: &'de [u8]) -> Result<Self> {
// TODO: only read msgpack bytes
Ok(RawBytes::new(data))
}
}
impl ToTupleBuffer for RawBytes {
#[inline(always)]
fn write_tuple_data(&self, w: &mut impl Write) -> Result<()> {
let data = &**self;
validate_msgpack(data)?;
w.write_all(data).map_err(Into::into)
}
#[inline(always)]
fn tuple_data(&self) -> Option<&[u8]> {
let data = &**self;
validate_msgpack(data).ok()?;
Some(data)
}
}
impl std::ops::Deref for RawBytes {
type Target = [u8];
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::borrow::ToOwned for RawBytes {
type Owned = RawByteBuf;
#[inline(always)]
fn to_owned(&self) -> Self::Owned {
self.0.to_vec().into()
}
}
////////////////////////////////////////////////////////////////////////////////
/// RawByteBuf
////////////////////////////////////////////////////////////////////////////////
/// A wrapper type for reading raw bytes from a tuple.
///
/// The difference between [`TupleBuffer`] and `RawByteBuf` is that the former
/// can only contain a valid tarantool tuple (msgpack array), while the latter
/// can contain any sequence of bytes.
///
/// This type also implements [`ToTupleBuffer`] such that `to_tuple_buffer`
/// returns `Ok` only if the underlying bytes represent a valid tuple.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct RawByteBuf(pub Vec<u8>);
impl serde_bytes::Serialize for RawByteBuf {
#[inline(always)]
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serde_bytes::Serialize::serialize(&self.0, serializer)
}
}
impl<'de> serde_bytes::Deserialize<'de> for RawByteBuf {
#[inline(always)]
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
serde_bytes::Deserialize::deserialize(deserializer).map(Self)
}
}
impl From<Vec<u8>> for RawByteBuf {
#[inline(always)]
fn from(b: Vec<u8>) -> Self {
Self(b)
}
}
impl Decode<'_> for RawByteBuf {
#[inline(always)]
fn decode(data: &[u8]) -> Result<Self> {
// TODO: only read msgpack bytes
Ok(Self(data.into()))
}
}
impl ToTupleBuffer for RawByteBuf {
#[inline(always)]
fn write_tuple_data(&self, w: &mut impl Write) -> Result<()> {
let data = self.as_slice();
validate_msgpack(data)?;
w.write_all(data).map_err(Into::into)
}
#[inline(always)]
fn tuple_data(&self) -> Option<&[u8]> {
let data = self.as_slice();
validate_msgpack(data).ok()?;
Some(data)
}
}
impl std::ops::Deref for RawByteBuf {
type Target = Vec<u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for RawByteBuf {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl std::borrow::Borrow<RawBytes> for RawByteBuf {
#[inline(always)]
fn borrow(&self) -> &RawBytes {
RawBytes::new(self.0.as_slice())
}
}
#[cfg(feature = "picodata")]
mod picodata {
use crate::tuple::{Tuple, TupleFormat};
use crate::Result;
use std::ffi::CStr;
use std::io::{Cursor, Write};
use std::marker::PhantomData;
use std::os::raw::c_char;
impl Tuple {
/// Returns messagepack encoded tuple with named fields (messagepack map).
///
/// Returned map has only numeric keys if tuple has default tuple format (see [TupleFormat](struct.TupleFormat.html)),
/// for example when tuple dont belongs to any space. If tuple has greater fields than named
/// fields in tuple format - then additional fields are presents in the map with numeric keys.
///
/// This function is useful if there is no information about tuple fields in program runtime.
pub fn as_named_buffer(&self) -> Result<Vec<u8>> {
let format = self.format();
let buff = self.as_buffer();
let field_count = self.len();
let mut named_buffer = Vec::with_capacity(buff.len());
let mut cursor = Cursor::new(&buff);
rmp::encode::write_map_len(&mut named_buffer, field_count)?;
rmp::decode::read_array_len(&mut cursor)?;
format.names().try_for_each(|field_name| -> Result<()> {
let value_start = cursor.position() as usize;
crate::msgpack::skip_value(&mut cursor)?;
let value_end = cursor.position() as usize;
rmp::encode::write_str(&mut named_buffer, field_name)?;
Ok(named_buffer.write_all(&buff[value_start..value_end])?)
})?;
for i in 0..field_count - format.name_count() {
let value_start = cursor.position() as usize;
crate::msgpack::skip_value(&mut cursor)?;
let value_end = cursor.position() as usize;
rmp::encode::write_u32(&mut named_buffer, i)?;
named_buffer.write_all(&buff[value_start..value_end])?;
}
Ok(named_buffer)
}
}
impl TupleFormat {
/// Return tuple field names count.
pub fn name_count(&self) -> u32 {
unsafe { (*(*self.inner).dict).name_count }
}
/// Return tuple field names.
pub fn names(&self) -> impl Iterator<Item = &str> {
let ptr = unsafe { (*(*self.inner).dict).names };
NameIterator {
ptr,
len: self.name_count() as usize,
pos: 0,
_p: PhantomData,
}
}
}
pub(crate) struct NameIterator<'a> {
ptr: *const *const c_char,
len: usize,
pos: usize,
_p: PhantomData<&'a ()>,
}
impl<'a> Iterator for NameIterator<'a> {
type Item = &'a str;
#[track_caller]
fn next(&mut self) -> Option<Self::Item> {
if self.pos >= self.len {
return None;
}
unsafe {
let str_ptr = self.ptr.add(self.pos);
self.pos += 1;
Some(
CStr::from_ptr(*str_ptr)
.to_str()
.expect("invalid utf-8 string"),
)
}
}
}
}
#[cfg(feature = "internal_test")]
mod test {
use super::*;
use crate::space;
use crate::space::Space;
#[crate::test(tarantool = "crate")]
fn tuple_buffer_from_lua() {
let svp = unsafe { ffi::box_region_used() };
let lua = crate::lua_state();
let t: TupleBuffer = lua
.eval("return { 3, 'foo', { true, box.NIL, false } }")
.unwrap();
#[derive(::serde::Deserialize, PartialEq, Eq, Debug)]
struct S {
i: i32,
s: String,
t: [Option<bool>; 3],
}
let s = S::decode(t.as_ref()).unwrap();
assert_eq!(
s,
S {
i: 3,
s: "foo".into(),
t: [Some(true), None, Some(false)]
}
);
let res = lua.eval::<TupleBuffer>("return 1, 2, 3");
assert_eq!(
res.unwrap_err().to_string(),
"failed converting Lua value to tarantool tuple: msgpack array expected, got error: A tuple or a table expected, got number
while reading value(s) returned by Lua: tarantool::tuple::TupleBuffer expected, got (number, number, number)"
);
let res = lua.eval::<TupleBuffer>("return { 1, 2, foo = 'bar' }");
assert_eq!(
res.unwrap_err().to_string(),
"failed converting Lua value to tarantool tuple: msgpack array expected, got error: Tuple/Key must be MsgPack array
while reading value(s) returned by Lua: tarantool::tuple::TupleBuffer expected, got table"
);
let res = lua.eval::<TupleBuffer>(
"ffi = require 'ffi';
local cdata = ffi.new('struct { int x; int y; }', { x = -1, y = 2 })
return { 1, cdata }",
);
assert_eq!(
res.unwrap_err().to_string(),
"failed converting Lua value to tarantool tuple: msgpack array expected, got error: unsupported Lua type 'cdata'
while reading value(s) returned by Lua: tarantool::tuple::TupleBuffer expected, got table"
);
assert_eq!(svp, unsafe { ffi::box_region_used() });
}
#[crate::test(tarantool = "crate")]
fn decode_error() {
use super::*;
let buf = (1, 2, 3).to_tuple_buffer().unwrap();
let err = <(String, String)>::decode(buf.as_ref()).unwrap_err();
assert_eq!(
err.to_string(),
r#"failed to decode tuple: invalid type: integer `1`, expected a string when decoding msgpack b"\x93\x01\x02\x03" into rust type (alloc::string::String, alloc::string::String)"#
);
let buf = ("hello", [1, 2, 3], "goodbye").to_tuple_buffer().unwrap();
let err = <(String, (i32, String, i32), String)>::decode(buf.as_ref()).unwrap_err();
assert_eq!(
err.to_string(),
r#"failed to decode tuple: invalid type: integer `2`, expected a string when decoding msgpack b"\x93\xa5\x68\x65\x6c\x6c\x6f\x93\x01\x02\x03\xa7\x67\x6f\x6f\x64\x62\x79\x65" into rust type (alloc::string::String, (i32, alloc::string::String, i32), alloc::string::String)"#
)
}
#[crate::test(tarantool = "crate")]
fn key_def_extract_key() {
let space = Space::builder(&crate::temp_space_name!())
.field(("id", space::FieldType::Unsigned))
.field(("not-key", space::FieldType::Array))
.field(("s", space::FieldType::String))
.field(("nested", space::FieldType::Any))
.create()
.unwrap();
let index = space
.index_builder("pk")
.part("id")
.part("s")
.part(
index::Part::field("nested")
.field_type(index::FieldType::Unsigned)
.path("[2].blabla"),
)
.create()
.unwrap();
let key_def = index.meta().unwrap().to_key_def();
let tuple = Tuple::new(&["foo"]).unwrap();
let e = key_def.extract_key(&tuple).unwrap_err();
assert_eq!(e.to_string(), "tarantool error: KeyPartType: Supplied key type of part 0 does not match index part type: expected unsigned");
let tuple = Tuple::new(&[1]).unwrap();
let e = key_def.extract_key(&tuple).unwrap_err();
// XXX: notice how this error message shows the 1-based index, but the
// previous one showed the 0-based index. You can thank tarantool devs
// for that.
assert_eq!(
e.to_string(),
"tarantool error: FieldMissing: Tuple field [3] required by space format is missing"
);
let tuple = Tuple::new(&(1, [1, 2, 3], "foo")).unwrap();
let e = key_def.extract_key(&tuple).unwrap_err();
assert_eq!(
e.to_string(),
"tarantool error: FieldMissing: Tuple field [4][2].blabla required by space format is missing"
);
let raw_data = b"\x94\x69\x93\x01\x02\x03\xa3foo\x93\xc0\x81\xa6blabla\x42\x07"; // [0x69, [1, 2, 3], "foo", [null, {blabla: 0x42}, 7]]
let tuple = Tuple::new(RawBytes::new(raw_data)).unwrap();
let key = key_def.extract_key(&tuple).unwrap();
assert_eq!(key.as_ref(), b"\x93\x69\xa3foo\x42"); // [0x69, "foo", 0x42]
let raw_data = b"\x94\x13\xa9not-array\xa3bar\x92\xc0\x81\xa6blabla\x37"; // [0x13, "not-array", "bar", [null, {blabla: 0x37}]]
// Even though the tuple doesn't actually satisfy the space's format,
// the key def only know about the locations & types of the key parts,
// so it doesn't care.
let tuple = Tuple::new(RawBytes::new(raw_data)).unwrap();
let key = key_def.extract_key(&tuple).unwrap();
assert_eq!(key.as_ref(), b"\x93\x13\xa3bar\x37");
// This tuple can't be inserted into the space.
let e = space.insert(&tuple).unwrap_err();
assert_eq!(e.to_string(), "tarantool error: FieldType: Tuple field 2 (not-key) type does not match one required by operation: expected array, got string");
}
}