xapian 0.1.4

Rust bindings to Xapian
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
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
use std::error::Error as StdError;
use std::fmt::{self, Display};
use std::io;

use cxx::UniquePtr;

pub const BRASS: i8 = 1;
pub const CHERT: i8 = 2;
pub const IN_MEMORY: i8 = 3;
pub const UNKNOWN: i8 = 0;

/** Create database if it doesn't already exist.
 *
 *  If no opening mode is specified, this is the default.
 */
pub const DB_CREATE_OR_OPEN: i8 = 0x00;

/** Create database if it doesn't already exist, or overwrite if it does. */
pub const DB_CREATE_OR_OVERWRITE: i8 = 0x01;

/** Create a new database.
 *
 *  If the database already exists, an exception will be thrown.
 */
pub const DB_CREATE: i8 = 0x02;

/** Open an existing database.
 *
 *  If the database doesn't exist, an exception will be thrown.
 */
pub const DB_OPEN: i8 = 0x03;

/// Enum of possible query operations
/// #[repr(i32)]
pub enum XapianOp {
    /// Return iff both subqueries are satisfied
    OpAnd,

    /// Return if either subquery is satisfied
    OpOr,

    /// Return if left but not right satisfied
    OpAndNot,

    /// Return if one query satisfied, but not both
    OpXor,

    /// Return iff left satisfied, but use weights from both
    OpAndMaybe,

    /// As AND, but use only weights from left subquery
    OpFilter,

    /** Find occurrences of a list of terms with all the terms
     *  occurring within a specified window of positions.
     *
     *  Each occurrence of a term must be at a different position,
     *  but the order they appear in is irrelevant.
     *
     *  The window parameter should be specified for this operation,
     *  but will default to the number of terms in the list.
     */
    OpNear,

    /** Find occurrences of a list of terms with all the terms
     *  occurring within a specified window of positions, and all
     *  the terms appearing in the order specified.
     *
     *  Each occurrence of a term must be at a different position.
     *
     *  The window parameter should be specified for this operation,
     *  but will default to the number of terms in the list.
     */
    OpPhrase,

    /** Filter by a range test on a document value. */
    OpValueRange,

    /** Scale the weight of a subquery by the specified factor.
     *
     *  A factor of 0 means this subquery will contribute no weight to
     *  the query - it will act as a purely boolean subquery.
     *
     *  If the factor is negative, Xapian::InvalidArgumentError will
     *  be thrown.
     */
    OpScaleWeight,

    /** Pick the best N subqueries and combine with OP_OR.
     *
     *  If you want to implement a feature which finds documents
     *  similar to a piece of text, an obvious approach is to build an
     *  "OR" query from all the terms in the text, and run this query
     *  against a database containing the documents.  However such a
     *  query can contain a lots of terms and be quite slow to perform,
     *  yet many of these terms don't contribute usefully to the
     *  results.
     *
     *  The OP_ELITE_SET operator can be used instead of OP_OR in this
     *  situation.  OP_ELITE_SET selects the most important ''N'' terms
     *  and then acts as an OP_OR query with just these, ignoring any
     *  other terms.  This will usually return results just as good as
     *  the full OP_OR query, but much faster.
     *
     *  In general, the OP_ELITE_SET operator can be used when you have
     *  a large OR query, but it doesn't matter if the search
     *  completely ignores some of the less important terms in the
     *  query.
     *
     *  The subqueries don't have to be terms, but if they aren't then
     *  OP_ELITE_SET will look at the estimated frequencies of the
     *  subqueries and so could pick a subset which don't actually
     *  match any documents even if the full OR would match some.
     *
     *  You can specify a parameter to the query constructor which
     *  control the number of terms which OP_ELITE_SET will pick.  If
     *  not specified, this defaults to 10 (or
     *  <code>ceil(sqrt(number_of_subqueries))</code> if there are more
     *  than 100 subqueries, but this rather arbitrary special case
     *  will be dropped in 1.3.0).  For example, this will pick the
     *  best 7 terms:
     *
     *  <pre>
     *  Xapian::Query query(Xapian::Query::OP_ELITE_SET, subqs.begin(), subqs.end(), 7);
     *  </pre>
     *
     * If the number of subqueries is less than this threshold,
     * OP_ELITE_SET behaves identically to OP_OR.
     */
    OpEliteSet,

    /** Filter by a greater-than-or-equal test on a document value. */
    OpValueGe,

    /** Filter by a less-than-or-equal test on a document value. */
    OpValueLe,

    /** Treat a set of queries as synonyms.
     *
     *  This returns all results which match at least one of the
     *  queries, but weighting as if all the sub-queries are instances
     *  of the same term: so multiple matching terms for a document
     *  increase the wdf value used, and the term frequency is based on
     *  the number of documents which would match an OR of all the
     *  subqueries.
     *
     *  The term frequency used will usually be an approximation,
     *  because calculating the precise combined term frequency would
     *  be overly expensive.
     *
     *  Identical to OP_OR, except for the weightings returned.
     */
    OpSynonym,
}

/// Flags to OR together and pass to TermGenerator::set_flags().
#[allow(non_camel_case_types)]
#[repr(i32)]
pub enum TermGeneratorFlag {
    FLAG_DEFAULT = 0,
    /// Index data required for spelling correction.
    FLAG_SPELLING = 128, // Value matches QueryParser flag.

    /** Enable generation of n-grams from CJK text.
     *
     *  With this enabled, spans of CJK characters are split into unigrams
     *  and bigrams, with the unigrams carrying positional information.
     *  Non-CJK characters are split into words as normal.
     *
     *  The corresponding option needs to be passed to QueryParser.
     *
     *  Flag added in Xapian 1.3.4 and 1.2.22.  This mode can be
     *  enabled in 1.2.8 and later by setting environment variable
     *  XAPIAN_CJK_NGRAM to a non-empty value (but doing so was deprecated
     *  in 1.4.11).
     */
    FLAG_CJK_NGRAM = 2048, // Value matches QueryParser flag.
}

/// QueryParser::feature_flag
#[allow(non_camel_case_types)]
#[repr(i32)]
#[derive(Debug)]
pub enum QueryParserFeatureFlag {
    /// Support AND, OR, etc and bracketed subexpressions.
    FLAG_BOOLEAN = 1,
    /// Support quoted phrases.
    FLAG_PHRASE = 2,
    /// Support + and -.
    FLAG_LOVEHATE = 4,
    /// Support AND, OR, etc even if they aren't in ALLCAPS.
    FLAG_BOOLEAN_ANY_CASE = 8,
    /** Support wildcards.
     *
     *  At present only right truncation (e.g. Xap*) is supported.
     *
     *  Currently you can't use wildcards with boolean filter prefixes,
     *  or in a phrase (either an explicitly quoted one, or one implicitly
     *  generated by hyphens or other punctuation).
     *
     *  In Xapian 1.2.x, you needed to tell the QueryParser object which
     *  database to expand wildcards from by calling set_database().  In
     *  Xapian 1.3.3, OP_WILDCARD was added and wildcards are now
     *  expanded when Enquire::get_mset() is called, with the expansion
     *  using the database being searched.
     */
    FLAG_WILDCARD = 16,
    /** Allow queries such as 'NOT apples'.
     *
     *  These require the use of a list of all documents in the database
     *  which is potentially expensive, so this feature isn't enabled by
     *  default.
     */
    FLAG_PURE_NOT = 32,
    /** Enable partial matching.
     *
     *  Partial matching causes the parser to treat the query as a
     *  "partially entered" search.  This will automatically treat the
     *  final word as a wildcarded match, unless it is followed by
     *  whitespace, to produce more stable results from interactive
     *  searches.
     *
     *  Currently FLAG_PARTIAL doesn't do anything if the final word
     *  in the query has a boolean filter prefix, or if it is in a phrase
     *  (either an explicitly quoted one, or one implicitly generated by
     *  hyphens or other punctuation).  It also doesn't do anything if
     *  if the final word is part of a value range.
     *
     *  In Xapian 1.2.x, you needed to tell the QueryParser object which
     *  database to expand wildcards from by calling set_database().  In
     *  Xapian 1.3.3, OP_WILDCARD was added and wildcards are now
     *  expanded when Enquire::get_mset() is called, with the expansion
     *  using the database being searched.
     */
    FLAG_PARTIAL = 64,

    /** Enable spelling correction.
     *
     *  For each word in the query which doesn't exist as a term in the
     *  database, Database::get_spelling_suggestion() will be called and if
     *  a suggestion is returned, a corrected version of the query string
     *  will be built up which can be read using
     *  QueryParser::get_corrected_query_string().  The query returned is
     *  based on the uncorrected query string however - if you want a
     *  parsed query based on the corrected query string, you must call
     *  QueryParser::parse_query() again.
     *
     *  NB: You must also call set_database() for this to work.
     */
    FLAG_SPELLING_CORRECTION = 128,

    /** Enable synonym operator '~'.
     *
     *  NB: You must also call set_database() for this to work.
     */
    FLAG_SYNONYM = 256,

    /** Enable automatic use of synonyms for single terms.
     *
     *  NB: You must also call set_database() for this to work.
     */
    FLAG_AUTO_SYNONYMS = 512,

    /** Enable automatic use of synonyms for single terms and groups of
     *  terms.
     *
     *  NB: You must also call set_database() for this to work.
     */
    FLAG_AUTO_MULTIWORD_SYNONYMS = 1024,

    /** Enable generation of n-grams from CJK text.
     *
     *  With this enabled, spans of CJK characters are split into unigrams
     *  and bigrams, with the unigrams carrying positional information.
     *  Non-CJK characters are split into words as normal.
     *
     *  The corresponding option needs to have been used at index time.
     *
     *  Flag added in Xapian 1.3.4 and 1.2.22.  This mode can be
     *  enabled in 1.2.8 and later by setting environment variable
     *  XAPIAN_CJK_NGRAM to a non-empty value (but doing so was deprecated
     *  in 1.4.11).
     */
    FLAG_CJK_NGRAM = 2048,

    /** Accumulate unstem and stoplist results.
     *
     *  By default, the unstem and stoplist data is reset by a call to
     *  parse_query(), which makes sense if you use the same QueryParser
     *  object to parse a series of independent queries.
     *
     *  If you're using the same QueryParser object to parse several
     *  fields on the same query form, you may want to have the unstem
     *  and stoplist data combined for all of them, in which case you
     *  can use this flag to prevent this data from being reset.
     *
     *  @since Added in Xapian 1.4.18.
     */
    FLAG_ACCUMULATE = 65536,

    /** Produce a query which doesn't use positional information.
     *
     *  With this flag enabled, no positional information will be used
     *  and any query operations which would use it are replaced by
     *  the nearest equivalent which doesn't (so phrase searches, NEAR
     *  and ADJ will result in OP_AND).
     *
     *  @since Added in Xapian 1.4.19.
     */
    FLAG_NO_POSITIONS = 0x20000,

    /** The default flags.
     *
     *  Used if you don't explicitly pass any to @a parse_query().
     *  The default flags are FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE.
     *
     *  Added in Xapian 1.0.11.
     */
    FLAG_DEFAULT = Self::FLAG_PHRASE as i32 | Self::FLAG_BOOLEAN as i32 | Self::FLAG_LOVEHATE as i32,
}

/// Enum of possible query operations
#[allow(non_camel_case_types)]
/// #[repr(i32)]
pub enum RangeProcessorFlags {
    RP_PREFIX = 0,
    /// as a suffix
    RP_SUFFIX = 1,
    /// optionally allow str_ on both ends of the range - e.g. $1..$10 or 5m..50m.
    RP_REPEATED = 2,
    RP_DATE_PREFER_MDY = 4,
}

#[allow(non_camel_case_types)]
#[repr(i32)]
#[derive(Debug)]
pub enum SnippetFlags {
    /** Model the relevancy of non-query terms in MSet::snippet().
     *
     *  Non-query terms will be assigned a small weight, and the snippet
     *  will tend to prefer snippets which contain a more interesting
     *  background (where the query term content is equivalent).
     */
    SNIPPET_BACKGROUND_MODEL = 1,
    /** Exhaustively evaluate candidate snippets in MSet::snippet().
     *
     *  Without this flag, snippet generation will stop once it thinks
     *  it has found a "good enough" snippet, which will generally reduce
     *  the time taken to generate a snippet.
     */
    SNIPPET_EXHAUSTIVE = 2,
    /** Return the empty string if no term got matched.
     *
     *  If enabled, snippet() returns an empty string if not a single match
     *  was found in text. If not enabled, snippet() returns a (sub)string
     *  of text without any highlighted terms.
     */
    SNIPPET_EMPTY_WITHOUT_MATCH = 4,

    /** Enable generation of n-grams from CJK text.
     *
     *  This option highlights CJK searches made using the QueryParser
     *  FLAG_CJK_NGRAM flag.  Non-CJK characters are split into words as
     *  normal.
     *
     *  The TermGenerator FLAG_CJK_NGRAM flag needs to have been used at
     *  index time.
     *
     *  This mode can also be enabled by setting environment variable
     *  XAPIAN_CJK_NGRAM to a non-empty value (but doing so was deprecated
     *  in 1.4.11).
     *
     *  @since Added in Xapian 1.4.11.
     */
    SNIPPET_CJK_NGRAM = 2048,
}

#[cxx::bridge]
pub(crate) mod ffi {
    #[namespace = "Xapian"]
    extern "C++" {
        pub(crate) type Database;
        pub(crate) type Stem;
        pub(crate) type WritableDatabase;
        pub(crate) type TermGenerator;
        pub(crate) type Document;
        pub(crate) type MSet;
        pub(crate) type MSetIterator;
        pub(crate) type TermIterator;
        pub(crate) type Enquire;
        pub(crate) type QueryParser;
        pub(crate) type Query;
        pub(crate) type MultiValueKeyMaker;
        pub(crate) type RangeProcessor;
        pub(crate) type NumberRangeProcessor;
        pub(crate) type MatchSpy;
        pub(crate) type ValueCountMatchSpy;
    }

    unsafe extern "C++" {
        include!("xapian/xapian-bind.h");

        pub(crate) fn new_database(err: &mut i8) -> UniquePtr<Database>;
        pub(crate) fn new_database_with_path(path: &str, db_type: i8, err: &mut i8) -> UniquePtr<Database>;
        pub(crate) fn database_reopen(db: Pin<&mut Database>, err: &mut i8);
        pub(crate) fn database_close(db: Pin<&mut Database>, err: &mut i8);
        pub(crate) fn new_enquire(db: Pin<&mut Database>, err: &mut i8) -> UniquePtr<Enquire>;
        pub(crate) fn add_database(db: Pin<&mut Database>, add_db: Pin<&mut Database>, err: &mut i8);

        pub(crate) fn new_stem(lang: &str, err: &mut i8) -> UniquePtr<Stem>;

        pub(crate) fn new_writable_database_with_path(path: &str, action: i8, db_type: i8, err: &mut i8) -> UniquePtr<WritableDatabase>;
        pub(crate) fn commit(db: Pin<&mut WritableDatabase>, err: &mut i8);
        pub(crate) fn close(db: Pin<&mut WritableDatabase>, err: &mut i8);
        pub(crate) fn replace_document(db: Pin<&mut WritableDatabase>, unique_term: &str, doc: Pin<&mut Document>, err: &mut i8) -> u32;
        pub(crate) fn delete_document(db: Pin<&mut WritableDatabase>, unique_term: &str, err: &mut i8);
        pub(crate) fn get_doccount(db: Pin<&mut WritableDatabase>, err: &mut i8) -> i32;

        pub(crate) fn new_termgenerator(err: &mut i8) -> UniquePtr<TermGenerator>;
        pub(crate) fn set_stemmer(tg: Pin<&mut TermGenerator>, stem: Pin<&mut Stem>, err: &mut i8);
        pub(crate) fn set_flags(tg: Pin<&mut TermGenerator>, toggle: i32, mask: i32, err: &mut i8);
        pub(crate) fn set_document(tg: Pin<&mut TermGenerator>, doc: Pin<&mut Document>, err: &mut i8);
        pub(crate) fn index_text_with_prefix(tg: Pin<&mut TermGenerator>, data: &str, prefix: &str, err: &mut i8);
        pub(crate) fn index_text(tg: Pin<&mut TermGenerator>, data: &str, err: &mut i8);
        pub(crate) fn index_int(tg: Pin<&mut TermGenerator>, data: i32, prefix: &str, err: &mut i8);
        pub(crate) fn index_long(tg: Pin<&mut TermGenerator>, data: i64, prefix: &str, err: &mut i8);
        pub(crate) fn index_float(tg: Pin<&mut TermGenerator>, data: f32, prefix: &str, err: &mut i8);
        pub(crate) fn index_double(tg: Pin<&mut TermGenerator>, data: f64, prefix: &str, err: &mut i8);

        pub(crate) fn new_document(err: &mut i8) -> UniquePtr<Document>;
        pub(crate) fn add_string(doc: Pin<&mut Document>, slot: u32, data: &str, err: &mut i8);
        pub(crate) fn add_int(doc: Pin<&mut Document>, slot: u32, data: i32, err: &mut i8);
        pub(crate) fn add_long(doc: Pin<&mut Document>, slot: u32, data: i64, err: &mut i8);
        pub(crate) fn add_double(doc: Pin<&mut Document>, slot: u32, data: f64, err: &mut i8);
        pub(crate) fn set_data(doc: Pin<&mut Document>, data: &str, err: &mut i8);
        pub(crate) fn get_doc_data(doc: Pin<&mut Document>) -> &CxxString;
        pub(crate) fn add_boolean_term(doc: Pin<&mut Document>, data: &str, err: &mut i8);

        pub(crate) fn get_matches_estimated(set: Pin<&mut MSet>, err: &mut i8) -> i32;
        pub(crate) fn mset_size(set: Pin<&mut MSet>, err: &mut i8) -> i32;
        pub(crate) fn mset_snippet<'a>(
            set: Pin<&'a mut MSet>,
            text: &'a str,
            length: i32,
            stem: Pin<&'a mut Stem>,
            flags: i32,
            hi_start: &'a str,
            hi_end: &'a str,
            omit: &'a str,
            err: &'a mut i8,
        ) -> &'a CxxString;
        pub(crate) fn mset_iterator_get_document(iter: Pin<&mut MSetIterator>, err: &mut i8) -> UniquePtr<Document>;
        pub(crate) fn mset_iterator_eq(iter: Pin<&mut MSetIterator>, other: Pin<&mut MSetIterator>, err: &mut i8) -> bool;
        pub(crate) fn mset_iterator_next(iter: Pin<&mut MSetIterator>, err: &mut i8);

        pub(crate) fn mset_begin(set: Pin<&mut MSet>, err: &mut i8) -> UniquePtr<MSetIterator>;
        pub(crate) fn mset_end(set: Pin<&mut MSet>, err: &mut i8) -> UniquePtr<MSetIterator>;
        pub(crate) fn mset_back(set: Pin<&mut MSet>, err: &mut i8) -> UniquePtr<MSetIterator>;
        // pub(crate) fn get_doc_by_index(set: Pin<&mut MSet>, index: i32, err: &mut i8) -> UniquePtr<Document>;

        pub(crate) fn get_mset(en: Pin<&mut Enquire>, from: i32, size: i32, err: &mut i8) -> UniquePtr<MSet>;
        pub(crate) fn set_query(en: Pin<&mut Enquire>, query: Pin<&mut Query>, err: &mut i8);
        pub(crate) fn set_sort_by_key(en: Pin<&mut Enquire>, sorter: Pin<&mut MultiValueKeyMaker>, reverse: bool, err: &mut i8);
        pub(crate) fn add_matchspy_value_count(en: Pin<&mut Enquire>, vcms: Pin<&mut ValueCountMatchSpy>, err: &mut i8);

        pub(crate) fn new_query_parser(err: &mut i8) -> UniquePtr<QueryParser>;
        pub(crate) fn set_max_wildcard_expansion(qp: Pin<&mut QueryParser>, limit: i32, err: &mut i8);
        pub(crate) fn set_stemmer_to_qp(qp: Pin<&mut QueryParser>, stem: Pin<&mut Stem>, err: &mut i8);
        pub(crate) fn set_database(qp: Pin<&mut QueryParser>, add_db: Pin<&mut Database>, err: &mut i8);
        pub(crate) fn add_prefix(qp: Pin<&mut QueryParser>, field: &str, prefix: &str, err: &mut i8);
        pub(crate) fn add_boolean_prefix(qp: Pin<&mut QueryParser>, field: &str, prefix: &str, err: &mut i8);
        pub(crate) fn add_rangeprocessor(qp: Pin<&mut QueryParser>, range_proc: Pin<&mut RangeProcessor>, err: &mut i8);
        pub(crate) fn add_number_rangeprocessor(qp: Pin<&mut QueryParser>, range_proc: Pin<&mut NumberRangeProcessor>, err: &mut i8);
        pub(crate) fn parse_query(qp: Pin<&mut QueryParser>, query_string: &str, flags: i32, err: &mut i8) -> UniquePtr<Query>;
        pub(crate) fn parse_query_with_prefix(qp: Pin<&mut QueryParser>, query_string: &str, flags: i32, prefix: &str, err: &mut i8) -> UniquePtr<Query>;

        // pub(crate) fn new_query(err: &mut i8) -> UniquePtr<Query>;
        pub(crate) fn new_query_range(op: i32, slot: u32, begin: f64, end: f64, err: &mut i8) -> UniquePtr<Query>;
        pub(crate) fn add_right_query(this_q: Pin<&mut Query>, op: i32, q: Pin<&mut Query>, err: &mut i8) -> UniquePtr<Query>;
        pub(crate) fn new_query_double_with_prefix(prefix: &str, d: f64, err: &mut i8) -> UniquePtr<Query>;
        pub(crate) fn query_is_empty(this_q: Pin<&mut Query>, err: &mut i8) -> bool;
        pub(crate) fn get_description(this_q: Pin<&mut Query>) -> &CxxString;

        pub(crate) fn new_multi_value_key_maker(err: &mut i8) -> UniquePtr<MultiValueKeyMaker>;
        pub(crate) fn add_value_to_multi_value_key_maker(this_m: Pin<&mut MultiValueKeyMaker>, slot: u32, asc_desc: bool, err: &mut i8);

        pub(crate) fn new_value_count_match_spy(slot: u32, err: &mut i8) -> UniquePtr<ValueCountMatchSpy>;
        pub(crate) fn new_range_processor(slot: u32, prefix: &str, flags: i32, err: &mut i8) -> UniquePtr<RangeProcessor>;
        pub(crate) fn new_number_range_processor(slot: u32, prefix: &str, flags: i32, err: &mut i8) -> UniquePtr<NumberRangeProcessor>;

        pub(crate) fn value_count_matchspy_values_begin(vcms: Pin<&mut ValueCountMatchSpy>, err: &mut i8) -> UniquePtr<TermIterator>;
        pub(crate) fn value_count_matchspy_values_end(vcms: Pin<&mut ValueCountMatchSpy>, err: &mut i8) -> UniquePtr<TermIterator>;
        pub(crate) fn value_count_matchspy_get_total(vcms: Pin<&mut ValueCountMatchSpy>, err: &mut i8) -> i32;

        pub(crate) fn term_iterator_get_termfreq_value<'a>(titer: Pin<&'a mut TermIterator>, err: &'a mut i8) -> &'a CxxString;
        pub(crate) fn term_iterator_get_termfreq_freq(titer: Pin<&mut TermIterator>, err: &mut i8) -> i32;
        pub(crate) fn term_iterator_eq(titer: Pin<&mut TermIterator>, other: Pin<&mut TermIterator>, err: &mut i8) -> bool;
        pub(crate) fn term_iterator_next(titer: Pin<&mut TermIterator>, err: &mut i8);
    }
}

#[warn(unused_unsafe)]

pub struct MultiValueKeyMaker {
    pub cxxp: UniquePtr<ffi::MultiValueKeyMaker>,
}

impl MultiValueKeyMaker {
    pub fn new() -> Result<Self, XError> {
        #[allow(unused_unsafe)]
        unsafe {
            let mut err = 0;
            let obj = ffi::new_multi_value_key_maker(&mut err);

            if err == 0 {
                Ok(Self { cxxp: obj })
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn add_value(&mut self, slot: u32, asc_desc: bool) -> Result<(), XError> {
        #[allow(unused_unsafe)]
        unsafe {
            let mut err = 0;
            ffi::add_value_to_multi_value_key_maker(self.cxxp.pin_mut(), slot, asc_desc, &mut err);

            if err == 0 {
                Ok(())
            } else {
                Err(XError::Xapian(err))
            }
        }
    }
}

pub struct Query {
    pub cxxp: UniquePtr<ffi::Query>,
}

impl Query {
    pub fn new() -> Result<Self, XError> {
        Ok(Self { cxxp: UniquePtr::null() })
    }

    pub fn new_range(op: XapianOp, slot: u32, begin: f64, end: f64) -> Result<Self, XError> {
        #[allow(unused_unsafe)]
        unsafe {
            let mut err = 0;
            let obj = ffi::new_query_range(op as i32, slot, begin, end, &mut err);

            if err == 0 {
                Ok(Self { cxxp: obj })
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn add_right(&mut self, op: XapianOp, q: &mut Query) -> Result<Self, XError> {
        #[allow(unused_unsafe)]
        unsafe {
            let mut err = 0;
            let obj = ffi::add_right_query(self.cxxp.pin_mut(), op as i32, q.cxxp.pin_mut(), &mut err);

            if err == 0 {
                Ok(Self { cxxp: obj })
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn new_double_with_prefix(prefix: &str, d: f64) -> Result<Self, XError> {
        #[allow(unused_unsafe)]
        unsafe {
            let mut err = 0;
            let obj = ffi::new_query_double_with_prefix(prefix, d, &mut err);

            if err == 0 {
                Ok(Self { cxxp: obj })
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn is_empty(&mut self) -> bool {
        self.cxxp.is_null()
    }

    pub fn is_empty_content_query(&mut self) -> bool {
        if !self.cxxp.is_null() {
            #[allow(unused_unsafe)]
            unsafe {
                let mut err = 0;
                let res = ffi::query_is_empty(self.cxxp.pin_mut(), &mut err);
                if err == 0 {
                    return res;
                } else {
                    return true;
                }
            }
        }
        true
    }

    pub fn get_description(&mut self) -> String {
        if !self.cxxp.is_null() {
            #[allow(unused_unsafe)]
            unsafe {
                //let mut err = 0;
                let res = ffi::get_description(self.cxxp.pin_mut());
                //if err == 0 {
                return res.to_string();
                //} else {
                //    None
                //}
            }
        }
        String::default()
    }
}

pub struct QueryParser {
    pub cxxp: UniquePtr<ffi::QueryParser>,
}

#[allow(unused_unsafe)]
impl QueryParser {
    pub fn new() -> Result<Self, XError> {
        unsafe {
            let mut err = 0;
            let obj = ffi::new_query_parser(&mut err);

            if err == 0 {
                Ok(Self { cxxp: obj })
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn set_max_wildcard_expansion(&mut self, limit: i32) -> Result<(), XError> {
        unsafe {
            let mut err = 0;
            ffi::set_max_wildcard_expansion(self.cxxp.pin_mut(), limit, &mut err);

            if err == 0 {
                Ok(())
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn set_stemmer(&mut self, mut stem: Stem) -> Result<(), XError> {
        unsafe {
            let mut err = 0;
            ffi::set_stemmer_to_qp(self.cxxp.pin_mut(), stem.cxxp.pin_mut(), &mut err);
            if err < 0 {
                return Err(XError::Xapian(err));
            }
        }
        Ok(())
    }

    pub fn set_database(&mut self, database: &mut Database) -> Result<(), XError> {
        unsafe {
            let mut err = 0;
            ffi::set_database(self.cxxp.pin_mut(), database.cxxp.pin_mut(), &mut err);

            if err == 0 {
                Ok(())
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn add_prefix(&mut self, field: &str, prefix: &str) -> Result<(), XError> {
        unsafe {
            let mut err = 0;
            ffi::add_prefix(self.cxxp.pin_mut(), field, prefix, &mut err);

            if err == 0 {
                Ok(())
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn add_boolean_prefix(&mut self, field: &str, prefix: &str) -> Result<(), XError> {
        unsafe {
            let mut err = 0;
            ffi::add_boolean_prefix(self.cxxp.pin_mut(), field, prefix, &mut err);

            if err == 0 {
                Ok(())
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn add_rangeprocessor(&mut self, range_proc: &mut RangeProcessor) -> Result<(), XError> {
        unsafe {
            let mut err = 0;
            ffi::add_rangeprocessor(self.cxxp.pin_mut(), range_proc.cxxp.pin_mut(), &mut err);

            if err == 0 {
                Ok(())
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn add_number_rangeprocessor(&mut self, range_proc: &mut NumberRangeProcessor) -> Result<(), XError> {
        unsafe {
            let mut err = 0;
            ffi::add_number_rangeprocessor(self.cxxp.pin_mut(), range_proc.cxxp.pin_mut(), &mut err);

            if err == 0 {
                Ok(())
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn parse_query(&mut self, query: &str, flags: i32) -> Result<Query, XError> {
        unsafe {
            let mut err = 0;
            let obj = ffi::parse_query(self.cxxp.pin_mut(), query, flags, &mut err);
            if err == 0 {
                Ok(Query { cxxp: obj })
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn parse_query_with_prefix(&mut self, query: &str, flags: i32, prefix: &str) -> Result<Query, XError> {
        unsafe {
            let mut err = 0;
            let obj = ffi::parse_query_with_prefix(self.cxxp.pin_mut(), query, flags, prefix, &mut err);
            if err == 0 {
                Ok(Query { cxxp: obj })
            } else {
                Err(XError::Xapian(err))
            }
        }
    }
}

pub struct MSetIterator {
    // pub mset: &'a mut MSet,
    // pub index: i32,
    pub cxxp: UniquePtr<ffi::MSetIterator>,
}

impl MSetIterator {
    // pub fn is_next(&mut self) -> Result<bool, XError> {
    //     #[allow(unused_unsafe)]
    //     unsafe {
    //         let mut err = 0;
    //         let res = ffi::mset_size(self.mset.cxxp.pin_mut(), &mut err) > self.index;
    //
    //         if err == 0 {
    //             Ok(res)
    //         } else {
    //             Err(XError::Xapian(err))
    //         }
    //     }
    // }

    // pub fn next(&mut self) -> Result<(), XError> {
    //     #[allow(unused_unsafe)]
    //     unsafe {
    //         let mut err = 0;
    //         if ffi::mset_size(self.mset.cxxp.pin_mut(), &mut err) > self.index {
    //             self.index += 1;
    //         }
    //
    //         if err == 0 {
    //             Ok(())
    //         } else {
    //             Err(XError::Xapian(err))
    //         }
    //     }
    // }

    pub fn get_document(&mut self) -> Result<Document, XError> {
        #[allow(unused_unsafe)]
        unsafe {
            let mut err = 0;
            let doc = ffi::mset_iterator_get_document(self.cxxp.pin_mut(), &mut err);

            if err == 0 {
                Ok(Document { cxxp: doc })
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn eq(&mut self, other: &mut MSetIterator) -> Result<bool, XError> {
        #[allow(unused_unsafe)]
        unsafe {
            let mut err = 0;
            let res = ffi::mset_iterator_eq(self.cxxp.pin_mut(), other.cxxp.pin_mut(), &mut err);

            if err == 0 {
                Ok(res)
            } else {
                Err(XError::Xapian(err))
            }
        }
    }

    pub fn next(&mut self) -> Result<(), XError> {
        #[allow(unused_unsafe)]
        unsafe {
            let mut err = 0;

            ffi::mset_iterator_next(self.cxxp.pin_mut(), &mut err);

            if err == 0 {
                Ok(())
            } else {
                Err(XError::Xapian(err))
            }
        }
    }
}

pub struct MSet {
    pub cxxp: UniquePtr<ffi::MSet>,
}

impl MSet {
    // pub fn iterator(&mut self) -> Result<MSetIterator, i8> {
    //     Ok(MSetIterator {
    //         mset: self,
    //         index: 0,
    //         cxxp: self.cxxp.clone(),
    //     })
    // }

    // https://xapian.org/docs/sourcedoc/html/classXapian_1_1MSet.html#ad00d5e7f564fe0e5031cb5f89b829ffe
    pub fn begin(&mut self) -> Result<MSetIterator, XError> {
        let mut err = 0;
        let obj = ffi::mset_begin(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(MSetIterator { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn end(&mut self) -> Result<MSetIterator, XError> {
        let mut err = 0;
        let obj = ffi::mset_end(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(MSetIterator {
                // mset: self,
                // index: 0,
                cxxp: obj,
            })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn back(&mut self) -> Result<MSetIterator, XError> {
        let mut err = 0;
        let obj = ffi::mset_back(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(MSetIterator {
                // mset: self,
                // index: 0,
                cxxp: obj,
            })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn get_matches_estimated(&mut self) -> Result<i32, XError> {
        #[allow(unused_unsafe)]
        let mut err = 0;
        let res = ffi::get_matches_estimated(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(res)
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn size(&mut self) -> Result<i32, XError> {
        #[allow(unused_unsafe)]
        let mut err = 0;
        let res = ffi::mset_size(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(res)
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn snippet(&mut self, text: &str, length: i32, stem: &mut Stem, flags: i32, hi_start: &str, hi_end: &str, omit: &str) -> String {
        #[allow(unused_unsafe)]
        let mut err = 0;
        let res = ffi::mset_snippet(self.cxxp.pin_mut(), text, length, stem.cxxp.pin_mut(), flags, hi_start, hi_end, omit, &mut err);

        return res.to_string();
    }
}

pub struct Enquire {
    pub cxxp: UniquePtr<ffi::Enquire>,
    sorter: Option<MultiValueKeyMaker>,
}

impl Enquire {
    pub fn get_mset(&mut self, from: i32, size: i32) -> Result<MSet, XError> {
        #[allow(unused_unsafe)]
        let mut err = 0;
        let obj = ffi::get_mset(self.cxxp.pin_mut(), from, size, &mut err);

        if err == 0 {
            Ok(MSet { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn set_query(&mut self, query: &mut Query) -> Result<(), XError> {
        #[allow(unused_unsafe)]
        let mut err = 0;
        ffi::set_query(self.cxxp.pin_mut(), query.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(())
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn set_sort_by_key(&mut self, mut sorter: MultiValueKeyMaker, reverse: bool) -> Result<(), XError> {
        #[allow(unused_unsafe)]
        let mut err = 0;
        ffi::set_sort_by_key(self.cxxp.pin_mut(), sorter.cxxp.pin_mut(), reverse, &mut err);
        self.sorter = Some(sorter);

        if err == 0 {
            Ok(())
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn add_matchspy() {
        unimplemented!()
    }

    pub fn add_matchspy_value_count(&mut self, vcms: &mut ValueCountMatchSpy) -> Result<(), XError> {
        #[allow(unused_unsafe)]
        let mut err = 0;
        ffi::add_matchspy_value_count(self.cxxp.pin_mut(), vcms.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(())
        } else {
            Err(XError::Xapian(err))
        }
    }
}

pub struct Database {
    pub cxxp: UniquePtr<ffi::Database>,
}

#[allow(unused_unsafe)]
impl Database {
    pub fn new() -> Result<Self, XError> {
        let mut err = 0;
        let obj = ffi::new_database(&mut err);

        if err == 0 {
            Ok(Self { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn new_with_path(path: &str, db_type: i8) -> Result<Self, XError> {
        let mut err = 0;
        let obj = ffi::new_database_with_path(path, db_type, &mut err);

        if err == 0 {
            Ok(Self { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn new_enquire(&mut self) -> Result<Enquire, XError> {
        let mut err = 0;
        let obj = ffi::new_enquire(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(Enquire { cxxp: obj, sorter: None })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn add_database(&mut self, database: &mut Database) -> Result<(), XError> {
        let mut err = 0;
        ffi::add_database(self.cxxp.pin_mut(), database.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(())
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn reopen(&mut self) -> Result<(), XError> {
        let mut err = 0;
        ffi::database_reopen(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(())
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn close(&mut self) -> Result<(), XError> {
        let mut err = 0;
        ffi::database_close(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(())
        } else {
            Err(XError::Xapian(err))
        }
    }
}

pub struct WritableDatabase {
    cxxp: UniquePtr<ffi::WritableDatabase>,
}

#[allow(unused_unsafe)]
impl WritableDatabase {
    pub fn new(path: &str, action: i8, db_type: i8) -> Result<Self, XError> {
        let mut err = 0;
        let obj = ffi::new_writable_database_with_path(path, action, db_type, &mut err);

        if err == 0 {
            Ok(Self { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn delete_document(&mut self, unique_term: &str) -> Result<(), XError> {
        let mut err = 0;
        ffi::delete_document(self.cxxp.pin_mut(), unique_term, &mut err);
        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn replace_document(&mut self, unique_term: &str, doc: &mut Document) -> Result<(), XError> {
        let mut err = 0;
        ffi::replace_document(self.cxxp.pin_mut(), unique_term, doc.cxxp.pin_mut(), &mut err);
        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn commit(&mut self) -> Result<(), XError> {
        let mut err = 0;
        ffi::commit(self.cxxp.pin_mut(), &mut err);
        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn close(&mut self) -> Result<(), XError> {
        let mut err = 0;
        ffi::close(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(())
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn get_doccount(&mut self) -> Result<i32, XError> {
        let mut err = 0;
        let res = ffi::get_doccount(self.cxxp.pin_mut(), &mut err);
        if err < 0 {
            return Err(XError::Xapian(err));
        } else {
            Ok(res)
        }
    }
}

pub struct Document {
    cxxp: UniquePtr<ffi::Document>,
}

#[allow(unused_unsafe)]
impl Document {
    pub fn new() -> Result<Self, XError> {
        let mut err = 0;
        let obj = ffi::new_document(&mut err);
        if err == 0 {
            Ok(Self { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn add_string(&mut self, slot: u32, data: &str) -> Result<(), XError> {
        let mut err = 0;

        ffi::add_string(self.cxxp.pin_mut(), slot, data, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn add_int(&mut self, slot: u32, data: i32) -> Result<(), XError> {
        let mut err = 0;

        ffi::add_int(self.cxxp.pin_mut(), slot, data, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn add_long(&mut self, slot: u32, data: i64) -> Result<(), XError> {
        let mut err = 0;

        ffi::add_long(self.cxxp.pin_mut(), slot, data, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn add_double(&mut self, slot: u32, data: f64) -> Result<(), XError> {
        let mut err = 0;

        ffi::add_double(self.cxxp.pin_mut(), slot, data, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn set_data(&mut self, data: &str) -> Result<(), XError> {
        let mut err = 0;

        ffi::set_data(self.cxxp.pin_mut(), data, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn get_data(&mut self) -> String {
        let res = ffi::get_doc_data(self.cxxp.pin_mut());

        res.to_string()
    }

    pub fn add_boolean_term(&mut self, data: &str) -> Result<(), XError> {
        let mut err = 0;

        ffi::add_boolean_term(self.cxxp.pin_mut(), data, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }
}

pub struct Stem {
    cxxp: UniquePtr<ffi::Stem>,
}

#[allow(unused_unsafe)]
impl Stem {
    pub fn new(lang: &str) -> Result<Self, XError> {
        let mut err = 0;
        let obj = ffi::new_stem(lang, &mut err);
        if err == 0 {
            Ok(Self { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }
}

pub struct TermGenerator {
    cxxp: UniquePtr<ffi::TermGenerator>,
}

impl TermGenerator {
    pub fn new() -> Result<Self> {
        let mut err = 0;
        let obj = ffi::new_termgenerator(&mut err);
        if err == 0 {
            Ok(Self { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }
}

#[allow(unused_unsafe)]
impl TermGenerator {
    pub fn set_stemmer(&mut self, mut stem: Stem) -> Result<(), XError> {
        let mut err = 0;
        ffi::set_stemmer(self.cxxp.pin_mut(), stem.cxxp.pin_mut(), &mut err);
        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn set_flags(&mut self, toggle: i32, mask: i32) -> Result<(), XError> {
        let mut err = 0;
        ffi::set_flags(self.cxxp.pin_mut(), toggle as i32, mask as i32, &mut err);
        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn set_document(&mut self, doc: &mut Document) -> Result<(), XError> {
        let mut err = 0;

        ffi::set_document(self.cxxp.pin_mut(), doc.cxxp.pin_mut(), &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn index_text_with_prefix(&mut self, data: &str, prefix: &str) -> Result<(), XError> {
        let mut err = 0;

        ffi::index_text_with_prefix(self.cxxp.pin_mut(), data, prefix, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn index_text(&mut self, data: &str) -> Result<(), XError> {
        let mut err = 0;

        ffi::index_text(self.cxxp.pin_mut(), data, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn index_int(&mut self, data: i32, prefix: &str) -> Result<(), XError> {
        let mut err = 0;

        ffi::index_int(self.cxxp.pin_mut(), data, prefix, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn index_long(&mut self, data: i64, prefix: &str) -> Result<(), XError> {
        let mut err = 0;

        ffi::index_long(self.cxxp.pin_mut(), data, prefix, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn index_float(&mut self, data: f32, prefix: &str) -> Result<(), XError> {
        let mut err = 0;

        ffi::index_float(self.cxxp.pin_mut(), data, prefix, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }

    pub fn index_double(&mut self, data: f64, prefix: &str) -> Result<(), XError> {
        let mut err = 0;

        ffi::index_double(self.cxxp.pin_mut(), data, prefix, &mut err);

        if err < 0 {
            return Err(XError::Xapian(err));
        }
        Ok(())
    }
}

#[warn(unused_unsafe)]

pub struct ValueCountMatchSpy {
    pub cxxp: UniquePtr<ffi::ValueCountMatchSpy>,
}

impl ValueCountMatchSpy {
    pub fn new(slot: u32) -> Result<Self, XError> {
        let mut err = 0;
        let obj = ffi::new_value_count_match_spy(slot, &mut err);
        if err == 0 {
            Ok(Self { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }

    // https://xapian.org/docs/facets#toc-entry-5
    // return Xapian::TermIterator
    pub fn values_begin(&mut self) -> Result<TermIterator, XError> {
        let mut err = 0;
        let obj = ffi::value_count_matchspy_values_begin(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(TermIterator { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn values_end(&mut self) -> Result<TermIterator, XError> {
        let mut err = 0;
        let obj = ffi::value_count_matchspy_values_end(self.cxxp.pin_mut(), &mut err);

        if err == 0 {
            Ok(TermIterator { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }

    pub fn get_total(&mut self) -> i32 {
        let mut err = 0;
        let rs = ffi::value_count_matchspy_get_total(self.cxxp.pin_mut(), &mut err);

        return rs;
    }
}

pub struct RangeProcessor {
    pub cxxp: UniquePtr<ffi::RangeProcessor>,
}

impl RangeProcessor {
    pub fn new(slot: u32, prefix: &str, flags: RangeProcessorFlags) -> Result<Self, XError> {
        let mut err = 0;
        let obj = ffi::new_range_processor(slot, prefix, flags as i32, &mut err);
        if err == 0 {
            Ok(Self { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }
}

pub struct NumberRangeProcessor {
    pub cxxp: UniquePtr<ffi::NumberRangeProcessor>,
}

impl NumberRangeProcessor {
    pub fn new(slot: u32, prefix: &str, flags: RangeProcessorFlags) -> Result<Self, XError> {
        let mut err = 0;
        let obj = ffi::new_number_range_processor(slot, prefix, flags as i32, &mut err);
        if err == 0 {
            Ok(Self { cxxp: obj })
        } else {
            Err(XError::Xapian(err))
        }
    }
}

#[warn(unused_unsafe)]

pub struct TermIterator {
    pub cxxp: UniquePtr<ffi::TermIterator>,
}

// std::string &term_iterator_get_termfreq_value(TermIterator &titer, int8_t &err);
// int term_iterator_get_termfreq_freq(TermIterator &titer, int8_t &err);
// bool term_iterator_eq(TermIterator &titer, TermIterator &other, int8_t &err);
impl TermIterator {
    pub fn get_termfreq_value(&mut self) -> String {
        let mut err = 0;
        let rs = ffi::term_iterator_get_termfreq_value(self.cxxp.pin_mut(), &mut err);

        return rs.to_string();
    }

    pub fn get_termfreq_freq(&mut self) -> i32 {
        let mut err = 0;
        let rs = ffi::term_iterator_get_termfreq_freq(self.cxxp.pin_mut(), &mut err);

        return rs;
    }

    pub fn eq(&mut self, other: &mut TermIterator) -> bool {
        let mut err = 0;
        let rs = ffi::term_iterator_eq(self.cxxp.pin_mut(), other.cxxp.pin_mut(), &mut err);

        return rs;
    }

    pub fn next(&mut self) {
        let mut err = 0;
        ffi::term_iterator_next(self.cxxp.pin_mut(), &mut err);
    }
}

pub fn get_xapian_err_type(errcode: i8) -> &'static str {
    match errcode {
        0 => "AssertionError",
        -1 => "InvalidArgumentError",
        -2 => "InvalidOperationError",
        -3 => "UnimplementedError",
        -4 => "DatabaseError",
        -5 => "DatabaseCorruptError",
        -6 => "DatabaseCreateError",
        -7 => "DatabaseLockError",
        -10 => "DatabaseModifiedError",
        -11 => "DatabaseOpeningError",
        -12 => "DatabaseVersionError",
        -13 => "DocNotFoundError",
        -14 => "FeatureUnavailableError",
        -15 => "InternalError",
        -16 => "NetworkError",
        -17 => "NetworkTimeoutError",
        -20 => "QueryParserError",
        -21 => "SerialisationError",
        -22 => "RangeError",
        -23 => "WildcardError",
        -24 => "DatabaseNotFoundError",
        -25 => "DatabaseClosedError",
        _ => "Unknown",
    }
}

pub type Result<T, E = XError> = std::result::Result<T, E>;

#[derive(Debug)]
pub enum XError {
    Xapian(i8),
    Io(io::Error),
}

impl Display for XError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            XError::Xapian(err) => write!(f, "xapian err={}", err),
            XError::Io(err) => err.fmt(f),
        }
    }
}

impl StdError for XError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            XError::Io(err) => Some(err),
            _ => None,
        }
    }
}

impl From<io::Error> for XError {
    fn from(err: io::Error) -> Self {
        XError::Io(err)
    }
}

impl From<i8> for XError {
    fn from(err: i8) -> Self {
        XError::Xapian(err)
    }
}

impl From<XError> for i8 {
    fn from(err: XError) -> i8 {
        err.into()
    }
}