tarantool 11.0.0

Tarantool rust bindings
Documentation
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
//! Error handling utils.
//!
//! The Tarantool error handling works most like libc's errno. All API calls
//! return -1 or `NULL` in the event of error. An internal pointer to
//! `box_error_t` type is set by API functions to indicate what went wrong.
//! This value is only significant if API call failed (returned -1 or `NULL`).
//!
//! Successful function can also touch the last error in some
//! cases. You don't have to clear the last error before calling
//! API functions. The returned object is valid only until next
//! call to **any** API function.
//!
//! You must set the last error using `set_error()` in your stored C
//! procedures if you want to return a custom error message.
//! You can re-throw the last API error to IPROTO client by keeping
//! the current value and returning -1 to Tarantool from your
//! stored procedure.

use std::collections::HashMap;
use std::ffi::CStr;
use std::fmt::{self, Display, Formatter};
use std::io;
use std::ptr::NonNull;
use std::str::Utf8Error;
use std::sync::Arc;

use crate::ffi::tarantool as ffi;
use crate::tlua::LuaError;
use crate::transaction::TransactionError;
use crate::tuple::Decode;
use crate::util::to_cstring_lossy;
use rmp::decode::{MarkerReadError, NumValueReadError, ValueReadError};
use rmp::encode::ValueWriteError;

/// A specialized [`Result`] type for the crate
pub type Result<T, E = Error> = std::result::Result<T, E>;

pub type TimeoutError<E> = crate::fiber::r#async::timeout::Error<E>;

////////////////////////////////////////////////////////////////////////////////
// Error
////////////////////////////////////////////////////////////////////////////////

/// Represents all error cases for all routines of crate (including Tarantool errors)
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    #[error("box error: {0}")]
    Tarantool(BoxError),

    #[error("io error: {0}")]
    IO(#[from] io::Error),

    #[error("failed to encode tuple: {0}")]
    Encode(#[from] EncodeError),

    #[error("failed to decode tuple: {error} when decoding msgpack {} into rust type {expected_type}", crate::util::DisplayAsHexBytes(.actual_msgpack))]
    Decode {
        error: rmp_serde::decode::Error,
        expected_type: String,
        actual_msgpack: Vec<u8>,
    },

    #[error("failed to decode tuple: {0}")]
    DecodeRmpValue(#[from] rmp_serde::decode::Error),

    #[error("unicode string decode error: {0}")]
    Unicode(#[from] Utf8Error),

    #[error("numeric value read error: {0}")]
    NumValueRead(#[from] NumValueReadError),

    #[error("msgpack read error: {0}")]
    ValueRead(#[from] ValueReadError),

    #[error("msgpack write error: {0}")]
    ValueWrite(#[from] ValueWriteError),

    /// Error returned from the Tarantool server.
    ///
    /// It represents an error with which Tarantool server
    /// answers to the client in case of faulty request or an error
    /// during request execution on the server side.
    #[error("server responded with error: {0}")]
    Remote(BoxError),

    #[error("{0}")]
    Protocol(#[from] crate::network::protocol::ProtocolError),

    /// The error is wrapped in a [`Arc`], because some libraries require
    /// error types to implement [`Sync`], which isn't implemented for [`Rc`].
    ///
    /// [`Rc`]: std::rc::Rc
    #[cfg(feature = "network_client")]
    #[error("{0}")]
    Tcp(Arc<crate::network::client::tcp::Error>),

    #[error("lua error: {0}")]
    LuaError(#[from] LuaError),

    #[error("space metadata not found")]
    MetaNotFound,

    #[error("msgpack encode error: {0}")]
    MsgpackEncode(#[from] crate::msgpack::EncodeError),

    #[error("msgpack decode error: {0}")]
    MsgpackDecode(#[from] crate::msgpack::DecodeError),

    /// A network connection was closed for the given reason.
    #[error("{0}")]
    ConnectionClosed(Arc<Error>),

    /// This should only be used if the error doesn't fall into one of the above
    /// categories.
    #[error("{0}")]
    Other(Box<dyn std::error::Error + Send + Sync>),
}

const _: () = {
    /// Assert Error implements Send + Sync
    const fn if_this_compiles_the_type_implements_send_and_sync<T: Send + Sync>() {}
    if_this_compiles_the_type_implements_send_and_sync::<Error>();
};

impl Error {
    #[inline(always)]
    pub fn other<E>(error: E) -> Self
    where
        E: Into<Box<dyn std::error::Error + Send + Sync>>,
    {
        Self::Other(error.into())
    }

    #[inline(always)]
    pub fn decode<T>(error: rmp_serde::decode::Error, data: Vec<u8>) -> Self {
        Error::Decode {
            error,
            expected_type: std::any::type_name::<T>().into(),
            actual_msgpack: data,
        }
    }

    /// Returns the name of the variant as it is spelled in the source code.
    pub const fn variant_name(&self) -> &'static str {
        match self {
            Self::Tarantool(_) => "Box",
            Self::IO(_) => "IO",
            Self::Encode(_) => "Encode",
            Self::Decode { .. } => "Decode",
            Self::DecodeRmpValue(_) => "DecodeRmpValue",
            Self::Unicode(_) => "Unicode",
            Self::NumValueRead(_) => "NumValueRead",
            Self::ValueRead(_) => "ValueRead",
            Self::ValueWrite(_) => "ValueWrite",
            Self::Remote(_) => "Remote",
            Self::Protocol(_) => "Protocol",
            #[cfg(feature = "network_client")]
            Self::Tcp(_) => "Tcp",
            Self::LuaError(_) => "LuaError",
            Self::MetaNotFound => "MetaNotFound",
            Self::MsgpackEncode(_) => "MsgpackEncode",
            Self::MsgpackDecode(_) => "MsgpackDecode",
            Self::ConnectionClosed(_) => "ConnectionClosed",
            Self::Other(_) => "Other",
        }
    }
}

impl From<rmp_serde::encode::Error> for Error {
    fn from(error: rmp_serde::encode::Error) -> Self {
        EncodeError::from(error).into()
    }
}

#[cfg(feature = "network_client")]
impl From<crate::network::client::tcp::Error> for Error {
    fn from(err: crate::network::client::tcp::Error) -> Self {
        Error::Tcp(Arc::new(err))
    }
}

impl From<MarkerReadError> for Error {
    fn from(error: MarkerReadError) -> Self {
        Error::ValueRead(error.into())
    }
}

impl<E> From<TransactionError<E>> for Error
where
    Error: From<E>,
{
    #[inline]
    #[track_caller]
    fn from(e: TransactionError<E>) -> Self {
        match e {
            TransactionError::FailedToCommit(e) => e.into(),
            TransactionError::FailedToRollback(e) => e.into(),
            TransactionError::RolledBack(e) => e.into(),
            TransactionError::AlreadyStarted => BoxError::new(
                TarantoolErrorCode::ActiveTransaction,
                "transaction has already been started",
            )
            .into(),
        }
    }
}

impl<E> From<TimeoutError<E>> for Error
where
    Error: From<E>,
{
    #[inline]
    #[track_caller]
    fn from(e: TimeoutError<E>) -> Self {
        match e {
            TimeoutError::Expired => BoxError::new(TarantoolErrorCode::Timeout, "timeout").into(),
            TimeoutError::Failed(e) => e.into(),
        }
    }
}

impl From<std::string::FromUtf8Error> for Error {
    #[inline(always)]
    fn from(error: std::string::FromUtf8Error) -> Self {
        // FIXME: we loose the data here
        error.utf8_error().into()
    }
}

////////////////////////////////////////////////////////////////////////////////
// BoxError
////////////////////////////////////////////////////////////////////////////////

/// Structured info about an error which can happen as a result of an internal
/// API or a remote procedure call.
///
/// Can also be used in user code to return structured error info from stored
/// procedures.
#[derive(Debug, Clone, Default)]
pub struct BoxError {
    pub(crate) code: u32,
    pub(crate) message: Option<Box<str>>,
    pub(crate) error_type: Option<Box<str>>,
    pub(crate) errno: Option<u32>,
    pub(crate) file: Option<Box<str>>,
    pub(crate) line: Option<u32>,
    pub(crate) fields: HashMap<Box<str>, rmpv::Value>,
    pub(crate) cause: Option<Box<BoxError>>,
}

// TODO mark this as deprecated
pub type TarantoolError = BoxError;

impl BoxError {
    /// Construct an error object with given error `code` and `message`. The
    /// resulting error will have `file` & `line` fields set from the caller's
    /// location.
    ///
    /// Use [`Self::with_location`] to override error location.
    #[inline(always)]
    #[track_caller]
    pub fn new(code: impl Into<u32>, message: impl Into<String>) -> Self {
        let location = std::panic::Location::caller();
        Self {
            code: code.into(),
            message: Some(message.into().into_boxed_str()),
            file: Some(location.file().into()),
            line: Some(location.line()),
            ..Default::default()
        }
    }

    /// Construct an error object with given error `code` and `message` and
    /// source location.
    ///
    /// Use [`Self::new`] to use the caller's location.
    #[inline(always)]
    pub fn with_location(
        code: impl Into<u32>,
        message: impl Into<String>,
        file: impl Into<String>,
        line: u32,
    ) -> Self {
        Self {
            code: code.into(),
            message: Some(message.into().into_boxed_str()),
            file: Some(file.into().into_boxed_str()),
            line: Some(line),
            ..Default::default()
        }
    }

    /// Tries to get the information about the last API call error. If error was not set
    /// returns `Ok(())`
    #[inline]
    pub fn maybe_last() -> std::result::Result<(), Self> {
        // This is safe as long as tarantool runtime is initialized
        let error_ptr = unsafe { ffi::box_error_last() };
        let Some(error_ptr) = NonNull::new(error_ptr) else {
            return Ok(());
        };

        // This is safe, because box_error_last returns a valid pointer
        Err(unsafe { Self::from_ptr(error_ptr) })
    }

    /// Create a `BoxError` from a poniter to the underlying struct.
    ///
    /// Use [`Self::maybe_last`] to automatically get the last error set by tarantool.
    ///
    /// # Safety
    /// The pointer must point to a valid struct of type `BoxError`.
    ///
    /// Also must only be called from the `tx` thread.
    pub unsafe fn from_ptr(error_ptr: NonNull<ffi::BoxError>) -> Self {
        let code = ffi::box_error_code(error_ptr.as_ptr());

        let message = CStr::from_ptr(ffi::box_error_message(error_ptr.as_ptr()));
        let message = message.to_string_lossy().into_owned().into_boxed_str();

        let error_type = CStr::from_ptr(ffi::box_error_type(error_ptr.as_ptr()));
        let error_type = error_type.to_string_lossy().into_owned().into_boxed_str();

        let mut file = None;
        let mut line = None;
        if let Some((f, l)) = error_get_file_line(error_ptr.as_ptr()) {
            file = Some(f.into());
            line = Some(l);
        }

        #[cfg(feature = "picodata")]
        // SAFETY: `error_ptr` points to a valid `ffi::BoxError` (`struct error`) object
        let fields = unsafe { get_error_fields(error_ptr.as_ptr()) };
        #[cfg(not(feature = "picodata"))]
        let fields = HashMap::new();

        Self {
            code,
            message: Some(message),
            error_type: Some(error_type),
            errno: None,
            file,
            line,
            fields,
            cause: None,
        }
    }

    /// Get the information about the last API call error.
    #[inline(always)]
    pub fn last() -> Self {
        Self::maybe_last().err().unwrap()
    }

    /// Set `self` as the last API call error.
    /// Useful when returning errors from stored prcoedures.
    #[inline(always)]
    #[track_caller]
    pub fn set_last(&self) {
        let mut loc = None;
        if let Some(f) = self.file() {
            debug_assert!(self.line().is_some());
            loc = Some((f, self.line().unwrap_or(0)));
        }
        let message = to_cstring_lossy(self.message());
        set_last_error(loc, self.error_code(), &message);

        #[cfg(feature = "picodata")]
        if !self.fields.is_empty() {
            set_last_error_fields(&self.fields);
        }
    }

    /// Stores a value into an extended error field.
    #[inline(always)]
    pub fn set_field(&mut self, field: &str, value: rmpv::Value) {
        self.fields.insert(field.into(), value);
    }

    /// Return IPROTO error code
    #[inline(always)]
    pub fn error_code(&self) -> u32 {
        self.code
    }

    /// Return the error type, e.g. "ClientError", "SocketError", etc.
    #[inline(always)]
    pub fn error_type(&self) -> &str {
        self.error_type.as_deref().unwrap_or("Unknown")
    }

    /// Return the error message
    #[inline(always)]
    pub fn message(&self) -> &str {
        self.message
            .as_deref()
            .unwrap_or("<error message is missing>")
    }

    /// Return the name of the source file where the error was created,
    /// if it's available.
    #[inline(always)]
    pub fn file(&self) -> Option<&str> {
        self.file.as_deref()
    }

    /// Return the source line number where the error was created,
    /// if it's available.
    #[inline(always)]
    pub fn line(&self) -> Option<u32> {
        self.line
    }

    /// Return the system `errno` value of the cause of this error,
    /// if it's available.
    ///
    /// You can use [`std::io::Error::from_raw_os_error`] to get more details
    /// for the returned error code.
    #[inline(always)]
    pub fn errno(&self) -> Option<u32> {
        self.errno
    }

    /// Return the error which caused this one, if it's available.
    #[inline(always)]
    pub fn cause(&self) -> Option<&Self> {
        self.cause.as_deref()
    }

    /// Return the map of all extended error fields.
    #[inline(always)]
    pub fn fields(&self) -> &HashMap<Box<str>, rmpv::Value> {
        &self.fields
    }
    /// Get a single extended error field.
    #[inline(always)]
    pub fn field(&self, field: &str) -> Option<&rmpv::Value> {
        self.fields.get(field)
    }

    /// Set a fallback [`std::fmt::Display`] implementation for `BoxError` which
    /// will be called if `BoxError` has unknown type and or error code.
    ///
    /// If `cb` returns `Err(e)` the error is passed along up the stack.
    /// If `cb` returns `Ok(false)` it's conisderred that the fallback didn't
    /// print the error and the default implementation is used.
    /// If `cb` returns `Ok(true)` the display is considerred successful.
    pub fn set_display_fallback(
        cb: impl Fn(&Self, &mut Formatter<'_>) -> Result<bool, std::fmt::Error> + 'static,
    ) -> Result<(), BoxError> {
        BOX_ERROR_FALLBACK_DISPLAY.with(|fallback| {
            if fallback.get().is_some() {
                return Err(BoxError::new(
                    TarantoolErrorCode::Unsupported,
                    "fallback callback is already set, cannot change it",
                ));
            }

            if fallback.set(Box::new(cb)).is_err() {
                unreachable!("already checked it's empty");
            }

            Ok(())
        })
    }
}

impl<'a> From<&'a BoxError> for std::borrow::Cow<'a, BoxError> {
    #[inline]
    fn from(e: &'a BoxError) -> Self {
        Self::Borrowed(e)
    }
}

impl From<BoxError> for std::borrow::Cow<'_, BoxError> {
    #[inline]
    fn from(e: BoxError) -> Self {
        Self::Owned(e)
    }
}

impl Display for BoxError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        // Vshard uses this error type and custom error codes which overlap with
        // tarantool error codes. So for Vshard errors we don't convert error
        // codes into names, as they would be wrong.
        if matches!(&self.error_type, Some(s) if &**s == "ShardingError") {
            return write!(f, "ShardingError #{}: {}", self.code, self.message());
        }

        if let Some(code) = TarantoolErrorCode::from_i64(self.code as _) {
            return write!(f, "{:?}: {}", code, self.message());
        }

        let res = BOX_ERROR_FALLBACK_DISPLAY.with(|fallback| fallback.get().map(|cb| cb(self, f)));
        if let Some(res) = res {
            if res? {
                return Ok(());
            }
        }

        write!(f, "box error #{}: {}", self.code, self.message())
    }
}

std::thread_local! {
    static BOX_ERROR_FALLBACK_DISPLAY: std::cell::OnceCell<BoxErrorFallbackDisplayImpl> = std::cell::OnceCell::new();
}
type BoxErrorFallbackDisplayImpl =
    Box<dyn Fn(&BoxError, &mut Formatter<'_>) -> Result<bool, std::fmt::Error>>;

impl From<BoxError> for Error {
    fn from(error: BoxError) -> Self {
        Error::Tarantool(error)
    }
}

impl std::error::Error for BoxError {
    #[inline]
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.cause.as_ref().map(|e| e as &dyn std::error::Error)
    }
}

impl<L> tlua::LuaRead<L> for BoxError
where
    L: tlua::AsLua,
{
    fn lua_read_at_position(lua: L, index: std::num::NonZeroI32) -> tlua::ReadResult<Self, L> {
        let l = lua.as_lua();
        let i = index.into();

        if unsafe { crate::ffi::has_box_error_from_lua() } {
            // SAFETY: lua pointer must be valid which it is because we only pass valid lua pointers
            let ptr = unsafe { crate::ffi::tarantool::luaL_iserror(l, i) };

            if let Some(ptr) = std::ptr::NonNull::new(ptr) {
                // SAFETY: tarantool guarantees that the pointer is valid
                let res = unsafe { Self::from_ptr(ptr) };
                return Ok(res);
            }
        } else {
            // TODO It's actually pretty simple to implement this in rust
            // without ffi, for example using helpers from tlua::cdata, but we
            // aren't going to use this code in picodata, so I'm not going to
            // waste my time
        }

        // Not a box_error pointer, let's try implicitly converting from something
        // SAFETY: lua pointer is valid
        let ty = unsafe { tlua::ffi::lua_type(l, i) };
        match ty {
            tlua::ffi::LUA_TSTRING => {
                let mut len = 0;
                // SAFETY: lua pointer is valid
                let ptr = unsafe { tlua::ffi::lua_tolstring(l, i, &mut len) };
                let mut s = std::borrow::Cow::Borrowed("<unexpected error>");
                // We already checked that lua_type is STRING, so lua_tolstring
                // will 100% return as non null, but we're being paranoid.
                if !ptr.is_null() {
                    // SAFETY: lua pointer is valid
                    let bytes = unsafe { std::slice::from_raw_parts(ptr as _, len as _) };
                    s = String::from_utf8_lossy(bytes);
                }

                return Ok(Self::new(TarantoolErrorCode::ProcLua, s));
            }

            // This is the format of vshard's errors. We don't care about other
            // formats for now.
            tlua::ffi::LUA_TTABLE => {
                let t = tlua::LuaTable::lua_read(lua)?;

                let error_type = match t.try_get::<_, String>("type") {
                    Ok(v) => v,
                    Err(e) => {
                        let e = to_wrong_type(e).expected("field 'type' of type string");
                        return Err((t.into_inner(), e));
                    }
                };

                let code = match t.try_get::<_, u32>("code") {
                    Ok(v) => v,
                    Err(e) => {
                        let e = to_wrong_type(e).expected("field 'code' of type u32");
                        return Err((t.into_inner(), e));
                    }
                };

                let message = match t.try_get::<_, String>("message") {
                    Ok(v) => v,
                    Err(e) => {
                        let e = to_wrong_type(e).expected("field 'message' of type string");
                        return Err((t.into_inner(), e));
                    }
                };

                let mut res = Self::new(code, message);
                res.error_type = Some(error_type.into());

                return Ok(res);
            }

            _ => {}
        }

        let e = tlua::WrongType::info("decoding BoxError")
            .expected_type::<Self>()
            .actual_single_lua(l, index);

        return Err((lua, e));

        fn to_wrong_type(e: tlua::LuaError) -> tlua::WrongType {
            match e {
                tlua::LuaError::WrongType(e) => e,
                other_error => {
                    tlua::WrongType::info("").actual(format!("thrown error: {other_error}"))
                }
            }
            .when("decoding error object")
        }
    }
}

/// # Safety
/// Only safe to be called from `tx` thread. Also `ptr` must point at a valid
/// instance of `ffi::BoxError`.
unsafe fn error_get_file_line(ptr: *const ffi::BoxError) -> Option<(String, u32)> {
    #[derive(Clone, Copy)]
    struct Failure;
    static mut FIELD_OFFSETS: Option<std::result::Result<(u32, u32), Failure>> = None;

    if (*std::ptr::addr_of!(FIELD_OFFSETS)).is_none() {
        let lua = crate::lua_state();
        let res = lua.eval::<(u32, u32)>(
            "ffi = require 'ffi'
            return
                ffi.offsetof('struct error', '_file'),
                ffi.offsetof('struct error', '_line')",
        );
        let (file_ofs, line_ofs) = crate::unwrap_ok_or!(res,
            Err(e) => {
                crate::say_warn!("failed getting struct error type info: {e}");
                FIELD_OFFSETS = Some(Err(Failure));
                return None;
            }
        );
        FIELD_OFFSETS = Some(Ok((file_ofs, line_ofs)));
    }
    let (file_ofs, line_ofs) = crate::unwrap_ok_or!(
        FIELD_OFFSETS.expect("always Some at this point"),
        Err(Failure) => {
            return None;
        }
    );

    let ptr = ptr.cast::<u8>();
    // TODO: check that struct error::_file is an array of bytes via lua-jit's ffi.typeinfo
    let file_ptr = ptr.add(file_ofs as _).cast::<std::ffi::c_char>();
    let file = CStr::from_ptr(file_ptr).to_string_lossy().into_owned();
    // TODO: check that struct error::_line has type u32 via lua-jit's ffi.typeinfo
    let line_ptr = ptr.add(line_ofs as _).cast::<u32>();
    let line = *line_ptr;

    Some((file, line))
}

/// Sets the last tarantool error. The `file_line` specifies source location to
/// be set for the error. If it is `None`, the location of the caller is used
/// (see [`std::panic::Location::caller`] for details on caller location).
#[inline]
#[track_caller]
pub fn set_last_error(file_line: Option<(&str, u32)>, code: u32, message: &CStr) {
    let (file, line) = crate::unwrap_or!(file_line, {
        let file_line = std::panic::Location::caller();
        (file_line.file(), file_line.line())
    });

    // XXX: we allocate memory each time this is called (sometimes even more
    // than once). This is very sad...
    let file = to_cstring_lossy(file);

    // Safety: this is safe, because all pointers point to nul-terimnated
    // strings, and the "%s" format works with any nul-terimnated string.
    unsafe {
        ffi::box_error_set(
            file.as_ptr(),
            line,
            code,
            crate::c_ptr!("%s"),
            message.as_ptr(),
        );
    }
}

/// Extracts all tarantool extended error fields from the error.
///
/// # Safety
///
/// `ptr` must point at a valid instance of `ffi::BoxError`.
#[cfg(feature = "picodata")]
unsafe fn get_error_fields(error: *const ffi::BoxError) -> HashMap<Box<str>, rmpv::Value> {
    // SAFETY: `error` points to a valid `ffi::BoxError` (`struct error`) object
    // The cast to `mut` pointer and back to a `const` one is sound
    //  since `error_get_payload` doesn't modify the contents of the structure.
    // It only does a structure projection.
    let payload = unsafe { ffi::error_get_payload(error as *mut ffi::BoxError) }
        as *const ffi::BoxErrorPayload;

    let mut result = HashMap::new();

    let mut iter = ffi::BoxErrorPayloadIter {
        next_position: 0,
        ..Default::default()
    };

    // SAFETY:
    // - `payload` points to a valid `ffi::BoxErrorPayload` (`struct error_payload`) object
    // - the `payload` is not mutated during iteration
    while unsafe { ffi::error_payload_iter_next(payload, &mut iter) } {
        // SAFETY:
        // - Since `error_payload_iter_next` returned `true`, `name` should point to a valid C string
        // - The C string reference does not outlive `payload`, which owns the underlying allocation
        //   (we copy the string via conversion to `Box<str>`)
        let name_cstr = unsafe { CStr::from_ptr(iter.name) };
        let Ok(name_str) = name_cstr.to_str() else {
            // ignore non UTF-8 named fields
            continue;
        };
        let name_str: Box<str> = name_str.into();

        // SAFETY:
        // - Since `error_payload_iter_next` returned `true`, `mp_value` and `mp_size` should
        //   define a valid byte slice.
        // - The slice reference does not outlive `payload`, which owns the underlying allocation
        //   (we copy the slice via `Value::decode`)
        let data_slice =
            unsafe { std::slice::from_raw_parts(iter.mp_value as *const u8, iter.mp_size) };
        let Ok(data_value) = rmpv::Value::decode(data_slice) else {
            // ignore unparseable fields
            continue;
        };

        result.insert(name_str, data_value);
    }

    result
}

/// Sets multiple tarantool extended error fields.
///
/// # Safety
///
/// - `ptr` must point at a valid instance of `ffi::BoxError`.
#[cfg(feature = "picodata")]
unsafe fn set_error_fields(error: *mut ffi::BoxError, fields: &HashMap<Box<str>, rmpv::Value>) {
    // SAFETY: `error` points to a valid `ffi::BoxError` (`struct error`) object
    let payload = unsafe { ffi::error_get_payload(error) };

    let mut encoded = Vec::new();

    for (name, value) in fields {
        let name = to_cstring_lossy(name);

        encoded.clear();

        // writing to a vector will never fail
        rmpv::encode::write_value(&mut encoded, value).unwrap();

        // SAFETY:
        // - `payload` points to a valid `ffi::BoxErrorPayload` (`struct error_payload`) object
        // - `name` stores a valid C string. This C string is only used for the duration
        //   of the function call (it is copied to the internal structure).
        // - The byte slice specified by `encoded.as_ptr()` and `encoded.len()` is only used
        //   for the duration of the function call (it is copied to the internal structure).
        unsafe {
            crate::ffi::tarantool::error_payload_set_mp(
                payload,
                name.as_ptr(),
                encoded.as_ptr() as *const std::ffi::c_char,
                encoded.len() as u32,
            )
        };
    }
}

/// Sets multiple tarantool extended error fields for the currently set last error.
///
/// # Panics
///
/// Will panic if there is no current last error.
#[cfg(feature = "picodata")]
#[inline]
pub fn set_last_error_fields(fields: &HashMap<Box<str>, rmpv::Value>) {
    {
        // SAFETY: `box_error_last` should always be safe when used in tarantool runtime.
        let error = unsafe { ffi::box_error_last() };
        assert_ne!(
            error,
            std::ptr::null_mut(),
            "Attempt to set fields of the last tarantool error while no error was set"
        );

        // SAFETY: the pointer returned by `box_error_last` should point to a valid `ffi::BoxError` object
        unsafe { set_error_fields(error, fields) };
    }
}

////////////////////////////////////////////////////////////////////////////////
// IntoBoxError
////////////////////////////////////////////////////////////////////////////////

/// Types implementing this trait represent an error which can be converted to
/// a structured tarantool internal error. In simple cases this may just be an
/// conversion into an error message, but may also add an error code and/or
/// additional custom fields. (custom fields not yet implemented).
///
/// All of the methods provide a default implementation for your convenience,
/// so if you don't have do define them explicitly if you don't care about
/// customizing the resulting `BoxError`'s fields. Your error type only needs
/// to implement `Display` (which it most likely already implements).
pub trait IntoBoxError: Sized + Display {
    /// Set `self` as the current fiber's last error.
    #[inline(always)]
    #[track_caller]
    fn set_last_error(self) {
        self.into_box_error().set_last();
    }

    /// Convert `self` to `BoxError`.
    #[track_caller]
    #[inline(always)]
    fn into_box_error(self) -> BoxError {
        BoxError::new(self.error_code(), self.to_string())
    }

    /// Get the error code which would be used for the corresponding BoxError.
    ///
    /// For your convenience the default implementation is provided which
    /// returns the `ER_PROC_C` error code (meaning the error originated from
    /// a native stored procedure).
    #[inline(always)]
    fn error_code(&self) -> u32 {
        TarantoolErrorCode::ProcC as _
    }
}

impl IntoBoxError for BoxError {
    #[inline(always)]
    #[track_caller]
    fn set_last_error(self) {
        self.set_last()
    }

    #[inline(always)]
    fn into_box_error(self) -> BoxError {
        self
    }

    #[inline(always)]
    fn error_code(&self) -> u32 {
        self.error_code()
    }
}

impl IntoBoxError for Error {
    #[inline(always)]
    #[track_caller]
    fn into_box_error(self) -> BoxError {
        let error_code = self.error_code();
        match self {
            Error::Tarantool(e) => e,
            Error::Remote(e) => {
                // TODO: maybe we want actually to set the last error to
                // something like ProcC, "server responded with error" and then
                // set `e` to be the `cause` of that error. But for now there's
                // no way to do that
                e
            }
            Error::Decode { .. } => BoxError::new(error_code, self.to_string()),
            Error::DecodeRmpValue(e) => BoxError::new(error_code, e.to_string()),
            Error::ValueRead(e) => BoxError::new(error_code, e.to_string()),
            _ => BoxError::new(error_code, self.to_string()),
        }
    }

    #[inline(always)]
    fn error_code(&self) -> u32 {
        match self {
            Error::Tarantool(e) => e.error_code(),
            Error::Remote(e) => e.error_code(),
            Error::Decode { .. } => TarantoolErrorCode::InvalidMsgpack as _,
            Error::DecodeRmpValue { .. } => TarantoolErrorCode::InvalidMsgpack as _,
            Error::ValueRead { .. } => TarantoolErrorCode::InvalidMsgpack as _,
            _ => TarantoolErrorCode::ProcC as _,
        }
    }
}

impl IntoBoxError for String {
    #[track_caller]
    fn into_box_error(self) -> BoxError {
        BoxError::new(self.error_code(), self)
    }

    #[inline(always)]
    fn error_code(&self) -> u32 {
        TarantoolErrorCode::ProcC as _
    }
}

impl IntoBoxError for &str {
    #[inline(always)]
    #[track_caller]
    fn into_box_error(self) -> BoxError {
        self.to_owned().into_box_error()
    }

    #[inline(always)]
    fn error_code(&self) -> u32 {
        TarantoolErrorCode::ProcC as _
    }
}

#[cfg(feature = "anyhow")]
impl IntoBoxError for anyhow::Error {
    fn into_box_error(self) -> BoxError {
        format!("{:#}", self).into_box_error()
    }
}

impl IntoBoxError for Box<dyn std::error::Error> {
    #[inline(always)]
    #[track_caller]
    fn into_box_error(self) -> BoxError {
        (&*self).into_box_error()
    }

    #[inline(always)]
    fn error_code(&self) -> u32 {
        TarantoolErrorCode::ProcC as _
    }
}

impl IntoBoxError for &dyn std::error::Error {
    #[inline(always)]
    #[track_caller]
    fn into_box_error(self) -> BoxError {
        let mut res = BoxError::new(self.error_code(), self.to_string());
        if let Some(cause) = self.source() {
            res.cause = Some(Box::new(cause.into_box_error()));
        }
        res
    }

    #[inline(always)]
    fn error_code(&self) -> u32 {
        TarantoolErrorCode::ProcC as _
    }
}

////////////////////////////////////////////////////////////////////////////////
// TarantoolErrorCode
////////////////////////////////////////////////////////////////////////////////

crate::define_enum_with_introspection! {
    /// Codes of Tarantool errors
    #[repr(u32)]
    #[non_exhaustive]
    pub enum TarantoolErrorCode {
        Unknown = 0,
        IllegalParams = 1,
        MemoryIssue = 2,
        TupleFound = 3,
        TupleNotFound = 4,
        Unsupported = 5,
        NonMaster = 6,
        Readonly = 7,
        Injection = 8,
        CreateSpace = 9,
        SpaceExists = 10,
        DropSpace = 11,
        AlterSpace = 12,
        IndexType = 13,
        ModifyIndex = 14,
        LastDrop = 15,
        TupleFormatLimit = 16,
        DropPrimaryKey = 17,
        KeyPartType = 18,
        ExactMatch = 19,
        InvalidMsgpack = 20,
        ProcRet = 21,
        TupleNotArray = 22,
        FieldType = 23,
        IndexPartTypeMismatch = 24,
        Splice = 25,
        UpdateArgType = 26,
        FormatMismatchIndexPart = 27,
        UnknownUpdateOp = 28,
        UpdateField = 29,
        FunctionTxActive = 30,
        KeyPartCount = 31,
        ProcLua = 32,
        NoSuchProc = 33,
        NoSuchTrigger = 34,
        NoSuchIndexID = 35,
        NoSuchSpace = 36,
        NoSuchFieldNo = 37,
        ExactFieldCount = 38,
        FieldMissing = 39,
        WalIo = 40,
        MoreThanOneTuple = 41,
        AccessDenied = 42,
        CreateUser = 43,
        DropUser = 44,
        NoSuchUser = 45,
        UserExists = 46,
        PasswordMismatch = 47,
        UnknownRequestType = 48,
        UnknownSchemaObject = 49,
        CreateFunction = 50,
        NoSuchFunction = 51,
        FunctionExists = 52,
        BeforeReplaceRet = 53,
        MultistatementTransaction = 54,
        TriggerExists = 55,
        UserMax = 56,
        NoSuchEngine = 57,
        ReloadCfg = 58,
        Cfg = 59,
        SavepointEmptyTx = 60,
        NoSuchSavepoint = 61,
        UnknownReplica = 62,
        ReplicasetUuidMismatch = 63,
        InvalidUuid = 64,
        ReplicasetUuidIsRo = 65,
        InstanceUuidMismatch = 66,
        ReplicaIDIsReserved = 67,
        InvalidOrder = 68,
        MissingRequestField = 69,
        Identifier = 70,
        DropFunction = 71,
        IteratorType = 72,
        ReplicaMax = 73,
        InvalidXlog = 74,
        InvalidXlogName = 75,
        InvalidXlogOrder = 76,
        NoConnection = 77,
        Timeout = 78,
        ActiveTransaction = 79,
        CursorNoTransaction = 80,
        CrossEngineTransaction = 81,
        NoSuchRole = 82,
        RoleExists = 83,
        CreateRole = 84,
        IndexExists = 85,
        SessionClosed = 86,
        RoleLoop = 87,
        Grant = 88,
        PrivGranted = 89,
        RoleGranted = 90,
        PrivNotGranted = 91,
        RoleNotGranted = 92,
        MissingSnapshot = 93,
        CantUpdatePrimaryKey = 94,
        UpdateIntegerOverflow = 95,
        GuestUserPassword = 96,
        TransactionConflict = 97,
        UnsupportedPriv = 98,
        LoadFunction = 99,
        FunctionLanguage = 100,
        RtreeRect = 101,
        ProcC = 102,
        UnknownRtreeIndexDistanceType = 103,
        Protocol = 104,
        UpsertUniqueSecondaryKey = 105,
        WrongIndexRecord = 106,
        WrongIndexParts = 107,
        WrongIndexOptions = 108,
        WrongSchemaVersion = 109,
        MemtxMaxTupleSize = 110,
        WrongSpaceOptions = 111,
        UnsupportedIndexFeature = 112,
        ViewIsRo = 113,
        NoTransaction = 114,
        System = 115,
        Loading = 116,
        ConnectionToSelf = 117,
        KeyPartIsTooLong = 118,
        Compression = 119,
        CheckpointInProgress = 120,
        SubStmtMax = 121,
        CommitInSubStmt = 122,
        RollbackInSubStmt = 123,
        Decompression = 124,
        InvalidXlogType = 125,
        AlreadyRunning = 126,
        IndexFieldCountLimit = 127,
        LocalInstanceIDIsReadOnly = 128,
        BackupInProgress = 129,
        ReadViewAborted = 130,
        InvalidIndexFile = 131,
        InvalidRunFile = 132,
        InvalidVylogFile = 133,
        CheckpointRollback = 134,
        VyQuotaTimeout = 135,
        PartialKey = 136,
        TruncateSystemSpace = 137,
        LoadModule = 138,
        VinylMaxTupleSize = 139,
        WrongDdVersion = 140,
        WrongSpaceFormat = 141,
        CreateSequence = 142,
        AlterSequence = 143,
        DropSequence = 144,
        NoSuchSequence = 145,
        SequenceExists = 146,
        SequenceOverflow = 147,
        NoSuchIndexName = 148,
        SpaceFieldIsDuplicate = 149,
        CantCreateCollation = 150,
        WrongCollationOptions = 151,
        NullablePrimary = 152,
        NoSuchFieldNameInSpace = 153,
        TransactionYield = 154,
        NoSuchGroup = 155,
        SqlBindValue = 156,
        SqlBindType = 157,
        SqlBindParameterMax = 158,
        SqlExecute = 159,
        Unused = 160,
        SqlBindNotFound = 161,
        ActionMismatch = 162,
        ViewMissingSql = 163,
        ForeignKeyConstraint = 164,
        NoSuchModule = 165,
        NoSuchCollation = 166,
        CreateFkConstraint = 167,
        DropFkConstraint = 168,
        NoSuchConstraint = 169,
        ConstraintExists = 170,
        SqlTypeMismatch = 171,
        RowidOverflow = 172,
        DropCollation = 173,
        IllegalCollationMix = 174,
        SqlNoSuchPragma = 175,
        SqlCantResolveField = 176,
        IndexExistsInSpace = 177,
        InconsistentTypes = 178,
        SqlSyntax = 179,
        SqlStackOverflow = 180,
        SqlSelectWildcard = 181,
        SqlStatementEmpty = 182,
        SqlKeywordIsReserved = 183,
        SqlUnrecognizedSyntax = 184,
        SqlUnknownToken = 185,
        SqlParserGeneric = 186,
        SqlAnalyzeArgument = 187,
        SqlColumnCountMax = 188,
        HexLiteralMax = 189,
        IntLiteralMax = 190,
        SqlParserLimit = 191,
        IndexDefUnsupported = 192,
        CkDefUnsupported = 193,
        MultikeyIndexMismatch = 194,
        CreateCkConstraint = 195,
        CkConstraintFailed = 196,
        SqlColumnCount = 197,
        FuncIndexFunc = 198,
        FuncIndexFormat = 199,
        FuncIndexParts = 200,
        NoSuchFieldNameInTuple = 201,
        FuncWrongArgCount = 202,
        BootstrapReadonly = 203,
        SqlFuncWrongRetCount = 204,
        FuncInvalidReturnType = 205,
        SqlParserGenericWithPos = 206,
        ReplicaNotAnon = 207,
        CannotRegister = 208,
        SessionSettingInvalidValue = 209,
        SqlPrepare = 210,
        WrongQueryId = 211,
        SequenceNotStarted = 212,
        NoSuchSessionSetting = 213,
        UncommittedForeignSyncTxns = 214,
        SyncMasterMismatch = 215,
        SyncQuorumTimeout = 216,
        SyncRollback = 217,
        TupleMetadataIsTooBig = 218,
        XlogGap = 219,
        TooEarlySubscribe = 220,
        SqlCantAddAutoinc = 221,
        QuorumWait = 222,
        InterferingPromote = 223,
        ElectionDisabled = 224,
        TxnRollback = 225,
        NotLeader = 226,
        SyncQueueUnclaimed = 227,
        SyncQueueForeign = 228,
        UnableToProcessInStream = 229,
        UnableToProcessOutOfStream = 230,
        TransactionTimeout = 231,
        ActiveTimer = 232,
        TupleFieldCountLimit = 233,
        CreateConstraint = 234,
        FieldConstraintFailed = 235,
        TupleConstraintFailed = 236,
        CreateForeignKey = 237,
        ForeignKeyIntegrity = 238,
        FieldForeignKeyFailed = 239,
        ComplexForeignKeyFailed = 240,
        WrongSpaceUpgradeOptions = 241,
        NoElectionQuorum = 242,
        Ssl = 243,
        SplitBrain = 244,
        OldTerm = 245,
        InterferingElections = 246,
        InvalidIteratorPosition = 247,
        InvalidDefaultValueType = 248,
        UnknownAuthMethod = 249,
        InvalidAuthData = 250,
        InvalidAuthRequest = 251,
        WeakPassword = 252,
        OldPassword = 253,
        NoSuchSession = 254,
        WrongSessionType = 255,
        PasswordExpired = 256,
        AuthDelay = 257,
        AuthRequired = 258,
        SqlSeqScan = 259,
        NoSuchEvent = 260,
        BootstrapNotUnanimous = 261,
        CantCheckBootstrapLeader = 262,
        BootstrapConnectionNotToAll = 263,
        NilUuid = 264,
        WrongFunctionOptions = 265,
        MissingSystemSpaces = 266,
        ExceededVdbeMaxSteps = 267,
        IllegalOptions = 268,
        IllegalOptionsFormat = 269,
        CantGenerateUuid = 270,
        SqlStatementBusy = 271,
        SchemaUpdateInProgress = 272,
        Unused7 = 273,
        Unconfigured = 274,
    }
}

#[allow(clippy::assertions_on_constants)]
const _: () = {
    assert!(TarantoolErrorCode::DISCRIMINANTS_ARE_SUBSEQUENT);
};

impl TarantoolErrorCode {
    pub fn try_last() -> Option<Self> {
        unsafe {
            let e_ptr = ffi::box_error_last();
            if e_ptr.is_null() {
                return None;
            }
            let u32_code = ffi::box_error_code(e_ptr);
            TarantoolErrorCode::from_i64(u32_code as _)
        }
    }

    pub fn last() -> Self {
        Self::try_last().unwrap()
    }
}

impl From<TarantoolErrorCode> for u32 {
    #[inline(always)]
    fn from(code: TarantoolErrorCode) -> u32 {
        code as _
    }
}

////////////////////////////////////////////////////////////////////////////////
// ...
////////////////////////////////////////////////////////////////////////////////

/// Clear the last error.
pub fn clear_error() {
    unsafe { ffi::box_error_clear() }
}

/// Set the last error.
///
/// # Example:
/// ```rust
/// # use tarantool::error::{TarantoolErrorCode, BoxError};
/// # fn foo() -> Result<(), tarantool::error::BoxError> {
/// let reason = "just 'cause";
/// tarantool::set_error!(TarantoolErrorCode::Unsupported, "this you cannot do, because: {reason}");
/// return Err(BoxError::last());
/// # }
/// ```
#[macro_export]
macro_rules! set_error {
    ($code:expr, $($msg_args:tt)+) => {{
        let msg = ::std::fmt::format(::std::format_args!($($msg_args)+));
        let msg = ::std::ffi::CString::new(msg).unwrap();
        $crate::error::set_last_error(None, $code as _, &msg);
    }};
}

/// Set the last tarantool error and return it immediately.
///
/// # Example:
/// ```rust
/// # use tarantool::set_and_get_error;
/// # use tarantool::error::TarantoolErrorCode;
/// # fn foo() -> Result<(), tarantool::error::BoxError> {
/// let reason = "just 'cause";
/// return Err(set_and_get_error!(TarantoolErrorCode::Unsupported, "this you cannot do, because: {reason}"));
/// # }
/// ```
#[macro_export]
#[deprecated = "use `BoxError::new` instead"]
macro_rules! set_and_get_error {
    ($code:expr, $($msg_args:tt)+) => {{
        $crate::set_error!($code, $($msg_args)+);
        $crate::error::BoxError::last()
    }};
}

////////////////////////////////////////////////////////////////////////////////
// EncodeError
////////////////////////////////////////////////////////////////////////////////

#[deprecated = "use `EncodeError` instead"]
pub type Encode = EncodeError;

/// Error that can happen when serializing a tuple
#[derive(Debug, thiserror::Error)]
pub enum EncodeError {
    #[error("{0}")]
    Rmp(#[from] rmp_serde::encode::Error),

    #[error("invalid msgpack value (expected array, found {:?})", crate::util::DebugAsMPValue(.0))]
    InvalidMP(Vec<u8>),
}

////////////////////////////////////////////////////////////////////////////////
// tests
////////////////////////////////////////////////////////////////////////////////

#[test]
fn tarantool_error_doesnt_depend_on_link_error() {
    let err = Error::from(rmp_serde::decode::Error::OutOfRange);
    // This test checks that tarantool::error::Error can be displayed without
    // the need for linking to tarantool symbols, because `#[test]` tests are
    // linked into a standalone executable without access to those symbols.
    assert!(!err.to_string().is_empty());
    assert!(!format!("{err}").is_empty());
}

#[cfg(feature = "internal_test")]
mod tests {
    use super::*;

    #[crate::test(tarantool = "crate")]
    fn set_error_expands_format() {
        let msg = "my message";
        set_error!(TarantoolErrorCode::Unknown, "{msg}");
        let e = BoxError::last();
        assert_eq!(e.to_string(), "Unknown: my message");
    }

    #[crate::test(tarantool = "crate")]
    fn set_error_format_sequences() {
        for c in b'a'..=b'z' {
            let c = c as char;
            set_error!(TarantoolErrorCode::Unknown, "%{c}");
            let e = BoxError::last();
            assert_eq!(e.to_string(), format!("Unknown: %{c}"));
        }
    }

    #[crate::test(tarantool = "crate")]
    fn set_error_caller_location() {
        //
        // If called in a function without `#[track_caller]`, the location of macro call is used
        //
        fn no_track_caller() {
            set_error!(TarantoolErrorCode::Unknown, "custom error");
        }
        let line_1 = line!() - 2; // line number where `set_error!` is called above

        no_track_caller();
        let e = BoxError::last();
        assert_eq!(e.file(), Some(file!()));
        assert_eq!(e.line(), Some(line_1));

        //
        // If called in a function with `#[track_caller]`, the location of the caller is used
        //
        #[track_caller]
        fn with_track_caller() {
            set_error!(TarantoolErrorCode::Unknown, "custom error");
        }

        with_track_caller();
        let line_2 = line!() - 1; // line number where `with_track_caller()` is called above

        let e = BoxError::last();
        assert_eq!(e.file(), Some(file!()));
        assert_eq!(e.line(), Some(line_2));

        //
        // If specified explicitly, the provided values are used
        //
        set_last_error(
            Some(("foobar", 420)),
            69,
            crate::c_str!("super custom error"),
        );
        let e = BoxError::last();
        assert_eq!(e.file(), Some("foobar"));
        assert_eq!(e.line(), Some(420));
    }

    #[crate::test(tarantool = "crate")]
    fn box_error_location() {
        //
        // If called in a function without `#[track_caller]`, the location where the error is constructed is used
        //
        fn no_track_caller() {
            let e = BoxError::new(69105_u32, "too many leaves");
            e.set_last();
        }
        let line_1 = line!() - 3; // line number where `BoxError` is constructed above

        no_track_caller();
        let e = BoxError::last();
        assert_eq!(e.file(), Some(file!()));
        assert_eq!(e.line(), Some(line_1));

        //
        // If called in a function with `#[track_caller]`, the location of the caller is used
        //
        #[track_caller]
        fn with_track_caller() {
            let e = BoxError::new(69105_u32, "too many leaves");
            e.set_last();
        }

        with_track_caller();
        let line_2 = line!() - 1; // line number where `with_track_caller()` is called above

        let e = BoxError::last();
        assert_eq!(e.file(), Some(file!()));
        assert_eq!(e.line(), Some(line_2));

        //
        // If specified explicitly, the provided values are used
        //
        BoxError::with_location(69105_u32, "too many leaves", "nice", 69).set_last();
        let e = BoxError::last();
        assert_eq!(e.file(), Some("nice"));
        assert_eq!(e.line(), Some(69));
    }

    #[crate::test(tarantool = "crate")]
    #[allow(clippy::let_unit_value)]
    fn set_error_with_no_semicolon() {
        // Basically you should always put double {{}} in your macros if there's
        // a let statement in it, otherwise it will suddenly stop compiling in
        // some weird context. And neither the compiler nor clippy will tell you
        // anything about this.
        () = set_error!(TarantoolErrorCode::Unknown, "idk");

        if true {
            set_error!(TarantoolErrorCode::Unknown, "idk")
        } else {
            unreachable!()
        }; // <- Look at this beauty
           // Also never put ; after the if statement (unless it's required
           // for example if it's nested in a let statement), you should always
           // put ; inside both branches instead.
    }

    #[crate::test(tarantool = "crate")]
    fn tarantool_error_use_after_free() {
        set_error!(TarantoolErrorCode::Unknown, "foo");
        let e = BoxError::last();
        assert_eq!(e.error_type(), "ClientError");
        clear_error();
        // This used to crash before the fix
        assert_eq!(e.error_type(), "ClientError");
    }

    #[crate::test(tarantool = "crate")]
    fn tarantool_error_fields_round_trip() {
        let mut error = BoxError::new(12345_u32, "complex error");
        error.set_field("igneous", "mystery".into());
        error.set_last();

        let error = BoxError::maybe_last().unwrap_err();

        assert_eq!(error.error_code(), 12345_u32);
        assert_eq!(error.message(), "complex error");

        if cfg!(feature = "picodata") {
            assert_eq!(error.field("igneous"), Some(&"mystery".into()));
        } else {
            assert!(error.fields().is_empty());
        }
    }
}