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
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::fmt::{self, Debug, Formatter};
use std::io::{Cursor, Write};
use std::os::raw::{c_char, c_int};
use std::ops::Range;
use std::ptr::{copy_nonoverlapping, NonNull};
use num_derive::ToPrimitive;
use num_traits::ToPrimitive;
use rmp::Marker;
use serde::{
de::DeserializeOwned,
Deserialize,
Serialize,
};
use crate::error::{Encode, Error, Result, TarantoolError};
use crate::ffi::tarantool as ffi;
use crate::tlua as tlua;
pub struct Tuple {
ptr: NonNull<ffi::BoxTuple>,
}
impl Debug for Tuple {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if let Ok(v) = self.as_struct::<rmpv::Value>() {
f.debug_tuple("Tuple").field(&v).finish()
} else {
f.debug_tuple("Tuple").field(&self.as_buffer()).finish()
}
}
}
impl Tuple {
pub fn from_struct<T>(value: &T) -> Result<Self>
where
T: AsTuple,
{
let buf = value.serialize_as_tuple()?;
Ok(Self::from(&buf))
}
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))
}
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))
}
pub fn try_from_slice(data: &[u8]) -> Result<Self> {
let data = validate_msgpack(data)?;
unsafe { Ok(Self::from_slice(data)) }
}
pub fn from_ptr(mut ptr: NonNull<ffi::BoxTuple>) -> Self {
unsafe { ffi::box_tuple_ref(ptr.as_mut()) };
Tuple { ptr }
}
pub fn try_from_ptr(ptr: *mut ffi::BoxTuple) -> Option<Self> {
NonNull::new(ptr).map(Self::from_ptr)
}
pub fn len(&self) -> u32 {
unsafe { ffi::box_tuple_field_count(self.ptr.as_ptr()) }
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn bsize(&self) -> usize {
unsafe { ffi::box_tuple_bsize(self.ptr.as_ptr()) }
}
pub fn format(&self) -> TupleFormat {
TupleFormat {
inner: unsafe { ffi::box_tuple_format(self.ptr.as_ptr()) },
}
}
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 })
}
}
pub fn field<'a, T>(&'a self, fieldno: u32) -> Result<Option<T>>
where
T: Deserialize<'a>,
{
unsafe {
let field_ptr = ffi::box_tuple_field(self.ptr.as_ptr(), fieldno);
self.field_from_ptr(field_ptr as _)
}
}
#[inline(always)]
pub fn try_get<'a, I, T>(&'a self, key: I) -> Result<Option<T>>
where
I: TupleIndex,
T: Deserialize<'a>,
{
key.get_field(self)
}
#[inline(always)]
pub fn get<'a, I, T>(&'a self, key: I) -> Option<T>
where
I: TupleIndex,
T: Deserialize<'a>,
{
self.try_get(key).expect("Error during getting tuple field")
}
pub fn as_struct<T>(&self) -> Result<T>
where
T: DeserializeOwned,
{
let raw_data = self.as_buffer();
Ok(rmp_serde::from_read::<_, T>(Cursor::new(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
}
pub fn into_struct<T>(self) -> Result<T>
where
T: DeserializeOwned,
{
self.as_struct()
}
pub(crate) fn into_ptr(self) -> *mut ffi::BoxTuple {
self.ptr.as_ptr()
}
unsafe fn field_from_ptr<'a, T>(&'a self, field_ptr: *const u8) -> Result<Option<T>>
where
T: Deserialize<'a>,
{
if field_ptr.is_null() {
return Ok(None)
}
let field_offset = field_ptr.offset_from(self.ptr.as_ref().data() as _);
let max_len = self.ptr.as_ref().bsize() - field_offset as u32;
let field_slice = std::slice::from_raw_parts(field_ptr, max_len as _);
Ok(Some(rmp_serde::from_slice(field_slice)?))
}
}
pub trait TupleIndex {
fn get_field<'a, T>(self, tuple: &'a Tuple) -> Result<Option<T>>
where
T: Deserialize<'a>;
}
impl TupleIndex for u32 {
#[inline(always)]
fn get_field<'a, T>(self, tuple: &'a Tuple) -> Result<Option<T>>
where
T: Deserialize<'a>,
{
tuple.field(self)
}
}
impl TupleIndex for &str {
#[inline(always)]
fn get_field<'a, T>(self, tuple: &'a Tuple) -> Result<Option<T>>
where
T: Deserialize<'a>,
{
unsafe {
let tuple_raw = tuple.ptr.as_ref();
let field_ptr = ffi::tuple_field_raw_by_full_path(
tuple.format().inner,
tuple_raw.data(),
tuple_raw.field_map(),
self.as_ptr() as _,
self.len() as _,
tlua::util::hash(self),
);
tuple.field_from_ptr(field_ptr as _)
}
}
}
impl From<&TupleBuffer> for Tuple {
fn from(buf: &TupleBuffer) -> Self {
unsafe {
Self::from_raw_data(buf.as_ptr() as _, buf.len() as _)
}
}
}
impl Drop for Tuple {
fn drop(&mut self) {
unsafe { ffi::box_tuple_unref(self.ptr.as_ptr()) };
}
}
impl Clone for Tuple {
fn clone(&self) -> Self {
unsafe { ffi::box_tuple_ref(self.ptr.as_ptr()) };
Tuple { ptr: self.ptr }
}
}
pub trait AsTuple: Serialize {
#[inline]
fn serialize_as_tuple(&self) -> Result<TupleBuffer> {
TupleBuffer::try_from(AsTuple::serialize(self)?)
}
#[inline]
fn serialize(&self) -> Result<Vec<u8>> {
let mut vec = Vec::with_capacity(128);
self.serialize_to(&mut vec)?;
Ok(vec)
}
fn serialize_to(&self, w: &mut impl Write) -> Result<()> {
rmp_serde::encode::write(w, self).map_err(Into::into)
}
}
impl<'a, T> AsTuple for &'a T
where
T: AsTuple,
{
fn serialize_to(&self, w: &mut impl Write) -> Result<()> {
T::serialize_to(*self, w)
}
}
impl AsTuple for () {
fn serialize_to(&self, w: &mut impl Write) -> Result<()> {
rmp_serde::encode::write(w, &Vec::<()>::new()).map_err(Into::into)
}
}
impl<T> AsTuple for [T] where T: Serialize {}
impl<T> AsTuple for Vec<T> where T: Serialize {}
macro_rules! impl_array {
($($n:literal)+) => {
$(
#[allow(clippy::zero_prefixed_literal)]
impl<T> AsTuple 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),*> AsTuple 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 }
pub enum TupleBuffer {
Vector(Vec<u8>),
TransactionScoped { ptr: NonNull<u8>, size: usize },
}
impl TupleBuffer {
pub fn as_ptr(&self) -> *const u8 {
match self {
TupleBuffer::Vector(vec) => vec.as_ptr(),
TupleBuffer::TransactionScoped { ptr, .. } => ptr.as_ptr(),
}
}
pub fn len(&self) -> usize {
match self {
TupleBuffer::Vector(vec) => vec.len(),
TupleBuffer::TransactionScoped { size, .. } => *size,
}
}
pub fn is_empty(&self) -> bool {
match self {
TupleBuffer::Vector(vec) => vec.is_empty(),
TupleBuffer::TransactionScoped { size, .. } => *size == 0,
}
}
pub unsafe fn from_vec_unchecked(buf: Vec<u8>) -> Self {
if ffi::box_txn() {
let size = buf.len();
let ptr = ffi::box_txn_alloc(size) as _;
copy_nonoverlapping(buf.as_ptr(), ptr, size);
let ptr = NonNull::new(ptr).expect("tarantool allocation failed");
Self::TransactionScoped { ptr, size }
} else {
Self::Vector(buf)
}
}
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 {
fn as_ref(&self) -> &[u8] {
match self {
Self::Vector(v) => v.as_ref(),
Self::TransactionScoped { ptr, size } => unsafe {
std::slice::from_raw_parts(ptr.as_ptr(), *size)
}
}
}
}
impl TryFrom<Vec<u8>> for TupleBuffer {
type Error = Error;
fn try_from(data: Vec<u8>) -> Result<Self> {
Self::try_from_vec(data)
}
}
impl From<Tuple> for TupleBuffer {
fn from(t: Tuple) -> Self {
Self::Vector(t.as_buffer())
}
}
impl Debug for TupleBuffer {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_tuple(
match self {
Self::Vector(_) => "TupleBuffer::Vector",
Self::TransactionScoped { .. } => "TupleBuffer::TransactionScoped",
}
)
.field(&Tuple::from(self))
.finish()
}
}
pub struct TupleFormat {
inner: *mut ffi::BoxTupleFormat,
}
impl Default for TupleFormat {
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()
}
}
}
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 {
pub fn position(&self) -> u32 {
unsafe { ffi::box_tuple_position(self.inner) }
}
pub fn rewind(&mut self) {
unsafe { ffi::box_tuple_rewind(self.inner) }
}
pub fn seek<T>(&mut self, fieldno: u32) -> Result<Option<T>>
where
T: DeserializeOwned,
{
unsafe {
field_value_from_ptr(ffi::box_tuple_seek(self.inner, fieldno) as _)
}
}
#[allow(clippy::should_implement_trait)]
pub fn next<T>(&mut self) -> Result<Option<T>>
where
T: DeserializeOwned,
{
unsafe {
field_value_from_ptr(ffi::box_tuple_next(self.inner) as _)
}
}
pub fn update(&mut self) {}
}
impl Drop for TupleIterator {
fn drop(&mut self) {
unsafe { ffi::box_tuple_iterator_free(self.inner) }
}
}
impl TupleIterator {}
#[repr(u32)]
#[derive(Debug, ToPrimitive, PartialEq, Eq, Hash)]
pub enum FieldType {
Any = 0,
Unsigned,
String,
Number,
Double,
Integer,
Boolean,
Varbinary,
Scalar,
Decimal,
Uuid,
Array,
Map,
}
#[derive(Debug)]
pub struct KeyDef {
inner: *mut ffi::BoxKeyDef,
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct KeyDefItem {
pub field_id: u32,
pub field_type: FieldType,
}
impl KeyDef {
pub fn new(items: Vec<KeyDefItem>) -> Self {
let size = items.len();
let mut ids = Vec::with_capacity(size);
let mut types = Vec::with_capacity(size);
for item in items {
ids.push(item.field_id);
types.push(item.field_type.to_u32().unwrap());
}
KeyDef {
inner: unsafe {
ffi::box_key_def_new(ids.as_mut_ptr(), types.as_mut_ptr(), size as u32)
},
}
}
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)
.cmp(&0)
}
}
pub fn compare_with_key<K>(&self, tuple: &Tuple, key: &K) -> Ordering
where
K: AsTuple,
{
let key_buf = key.serialize_as_tuple().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)
.cmp(&0)
}
}
}
impl Drop for KeyDef {
fn drop(&mut self) {
unsafe { ffi::box_key_def_delete(self.inner) }
}
}
unsafe fn field_value_from_ptr<T>(field_ptr: *mut u8) -> Result<Option<T>>
where
T: DeserializeOwned,
{
if field_ptr.is_null() {
return Ok(None);
}
let max_len = u32::MAX >> 1;
let value_slice = std::slice::from_raw_parts(field_ptr, max_len as _);
Ok(Some(rmp_serde::from_slice(value_slice)?))
}
#[repr(C)]
#[derive(Debug)]
pub struct FunctionCtx {
inner: *mut ffi::BoxFunctionCtx,
}
impl FunctionCtx {
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)
}
}
pub fn return_mp<T>(&self, value: &T) -> Result<c_int>
where
T: Serialize,
{
let buf = rmp_serde::to_vec_named(value)?;
let buf_ptr = buf.as_ptr() as *const c_char;
let result =
unsafe { ffi::box_return_mp(self.inner, buf_ptr, buf_ptr.add(buf.len())) };
if result < 0 {
Err(TarantoolError::last().into())
} else {
Ok(result)
}
}
}
#[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 {
fn from(args: FunctionArgs) -> Tuple {
Tuple::from(&args)
}
}
impl From<&FunctionArgs> for Tuple {
fn from(args: &FunctionArgs) -> Tuple {
unsafe {
Tuple::from_raw_data(
args.start as _,
args.end.offset_from(args.start) as _,
)
}
}
}
impl FunctionArgs {
pub fn as_struct<T>(&self) -> Result<T>
where
T: DeserializeOwned,
{
Tuple::from(self).as_struct()
}
}
pub fn session_push<T>(value: &T) -> Result<()>
where
T: AsTuple,
{
let buf = value.serialize_as_tuple().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(())
}
}
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(Encode::InvalidMP(data.into()).into())
}
Ok(data)
}
impl<L> tlua::Push<L> for Tuple
where
L: tlua::AsLua,
{
type Err = tlua::Void;
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::LuaRead<L> for Tuple
where
L: tlua::AsLua,
{
fn lua_read_at_position(lua: L, index: std::num::NonZeroI32) -> std::result::Result<Self, L> {
let ptr = unsafe {
ffi::luaT_istuple(tlua::AsLua::as_lua(&lua), index.get())
};
Self::try_from_ptr(ptr).ok_or(lua)
}
}
pub trait Decode: Sized {
fn decode(data: &[u8]) -> Result<Self>;
}
impl<T> Decode for T
where
T: for<'de> serde::Deserialize<'de>,
{
fn decode(data: &[u8]) -> Result<Self> {
Ok(rmp_serde::from_slice(data)?)
}
}
impl Decode for Tuple {
fn decode(data: &[u8]) -> Result<Self> {
Self::try_from_slice(data)
}
}