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
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,
}

/// Enum of feature flag
#[repr(i16)]
pub enum FeatureFlag {
    /// Support AND, OR, etc and bracketed subexpressions.
    FlagBoolean = 1,
    /// Support quoted phrases.
    FlagPhrase = 2,
    /// Support + and -.
    FlagLovehate = 4,
    /// Support AND, OR, etc even if they aren't in ALLCAPS.
    FlagBooleanAnyCase = 8,
    /** Support right truncation (e.g. Xap*).
     *
     *  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).
     *
     *  NB: You need to tell the QueryParser object which database to
     *  expand wildcards from by calling set_database.
     */
    FlagWildcard = 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.
     */
    FlagPureNot = 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.
     *
     *  NB: You need to tell the QueryParser object which database to
     *  expand wildcards from by calling set_database.
     */
    FlagPartial = 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.
     */
    FlagSpellingCorrection = 128,

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

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

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

    /** 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.
     */
    FlagDefault = FeatureFlag::FlagPhrase as i16 | FeatureFlag::FlagBoolean as i16 | FeatureFlag::FlagLovehate as i16,
}

//use cxx::CxxString;

#[cxx::bridge(namespace = org::example)]
pub(crate) mod ffi {

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

        pub(crate) type Database;
        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: &mut Database, err: &mut i8);
        pub(crate) fn database_close(db: &mut Database, err: &mut i8);
        pub(crate) fn new_enquire(db: &mut Database, err: &mut i8) -> UniquePtr<Enquire>;
        pub(crate) fn add_database(db: &mut Database, add_db: &mut Database, err: &mut i8);

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

        pub(crate) type WritableDatabase;
        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: &mut WritableDatabase, err: &mut i8);
        pub(crate) fn replace_document(db: &mut WritableDatabase, unique_term: &str, doc: &mut Document, err: &mut i8) -> u32;
        pub(crate) fn delete_document(db: &mut WritableDatabase, unique_term: &str, err: &mut i8);
        pub(crate) fn get_doccount(db: &mut WritableDatabase, err: &mut i8) -> i32;

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

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

        pub(crate) type MSet;
        pub(crate) fn get_matches_estimated(set: &mut MSet, err: &mut i8) -> i32;
        pub(crate) fn mset_size(set: &mut MSet, err: &mut i8) -> i32;
        pub(crate) fn get_doc_by_index(set: &mut MSet, index: i32, err: &mut i8) -> UniquePtr<Document>;

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

        pub(crate) type QueryParser;
        pub(crate) fn new_query_parser(err: &mut i8) -> UniquePtr<QueryParser>;
        pub(crate) fn set_max_wildcard_expansion(qp: &mut QueryParser, limit: i32, err: &mut i8);
        pub(crate) fn set_stemmer_to_qp(qp: &mut QueryParser, stem: &mut Stem, err: &mut i8);
        pub(crate) fn set_database(qp: &mut QueryParser, add_db: &mut Database, err: &mut i8);
        pub(crate) fn parse_query(qp: &mut QueryParser, query_string: &str, flags: i16, err: &mut i8) -> UniquePtr<Query>;
        pub(crate) fn parse_query_with_prefix(qp: &mut QueryParser, query_string: &str, flags: i16, prefix: &str, err: &mut i8) -> UniquePtr<Query>;

        pub(crate) type 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: &mut Query, op: i32, q: &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: &mut Query, err: &mut i8) -> bool;
        pub(crate) fn get_description(this_q: &mut Query) -> &CxxString;

        pub(crate) type MultiValueKeyMaker;
        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: &mut MultiValueKeyMaker, slot: u32, asc_desc: bool, 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(&mut self.cxxp, 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(&mut self.cxxp, op as i32, &mut q.cxxp, &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(&mut self.cxxp, &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(&mut self.cxxp);
                //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(&mut self.cxxp, limit, &mut err);

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

    pub fn set_stemmer(&mut self, stem: &mut Stem) -> Result<(), XError> {
        unsafe {
            let mut err = 0;
            ffi::set_stemmer_to_qp(&mut self.cxxp, &mut stem.cxxp, &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(&mut self.cxxp, &mut database.cxxp, &mut err);

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

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

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

impl<'a> MSetIterator<'a> {
    pub fn is_next(&mut self) -> Result<bool, XError> {
        #[allow(unused_unsafe)]
        unsafe {
            let mut err = 0;
            let res = ffi::mset_size(&mut self.mset.cxxp, &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(&mut self.mset.cxxp, &mut err) > self.index {
                self.index += 1;
            }

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

    pub fn get_document_data(&mut self) -> Result<String, XError> {
        #[allow(unused_unsafe)]
        unsafe {
            let mut err = 0;
            let mut doc = ffi::get_doc_by_index(&mut self.mset.cxxp, self.index, &mut err);

            if err == 0 {
                Ok(ffi::get_doc_data(&mut doc).to_string())
            } 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,
        })
    }

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

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

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)]
        unsafe {
            let mut err = 0;
            let obj = ffi::get_mset(&mut self.cxxp, 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)]
        unsafe {
            let mut err = 0;
            ffi::set_query(&mut self.cxxp, &mut query.cxxp, &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)]
        unsafe {
            let mut err = 0;
            ffi::set_sort_by_key(&mut self.cxxp, &mut sorter.cxxp, reverse, &mut err);
            self.sorter = Some(sorter);

            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> {
        unsafe {
            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> {
        unsafe {
            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> {
        unsafe {
            let mut err = 0;
            let obj = ffi::new_enquire(&mut self.cxxp, &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> {
        unsafe {
            let mut err = 0;
            ffi::add_database(&mut self.cxxp, &mut database.cxxp, &mut err);

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

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

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

    pub fn close(&mut self) -> Result<(), XError> {
        unsafe {
            let mut err = 0;
            ffi::database_close(&mut self.cxxp, &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> {
        unsafe {
            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> {
        unsafe {
            let mut err = 0;
            ffi::delete_document(&mut self.cxxp, 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> {
        unsafe {
            let mut err = 0;
            ffi::replace_document(&mut self.cxxp, unique_term, &mut doc.cxxp, &mut err);
            if err < 0 {
                return Err(XError::Xapian(err));
            }
        }
        Ok(())
    }

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

    pub fn get_doccount(&mut self) -> Result<i32, XError> {
        unsafe {
            let mut err = 0;
            let res = ffi::get_doccount(&mut self.cxxp, &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> {
        unsafe {
            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> {
        unsafe {
            let mut err = 0;

            ffi::add_string(&mut self.cxxp, 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> {
        unsafe {
            let mut err = 0;

            ffi::add_int(&mut self.cxxp, 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> {
        unsafe {
            let mut err = 0;

            ffi::add_long(&mut self.cxxp, 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> {
        unsafe {
            let mut err = 0;

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

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

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

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

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

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

            ffi::add_boolean_term(&mut self.cxxp, 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> {
        unsafe {
            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>,
}

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

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

            ffi::set_document(&mut self.cxxp, &mut doc.cxxp, &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> {
        unsafe {
            let mut err = 0;

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

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

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

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

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

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

            ffi::index_int(&mut self.cxxp, 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> {
        unsafe {
            let mut err = 0;

            ffi::index_long(&mut self.cxxp, 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> {
        unsafe {
            let mut err = 0;

            ffi::index_float(&mut self.cxxp, 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> {
        unsafe {
            let mut err = 0;

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

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

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()
    }
}