rlucene 0.1.0-alpha.3

A Rust port of Apache Lucene, a full-text search engine library
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
use crate::core::analysis::analyzer::{Analyzer, AnalyzerText};
use crate::core::analysis::reader::ReaderEnum;
use crate::core::analysis::token_attributes::packed_token_and_binary::BinaryTokenStreamAttributeImpl;
use crate::core::analysis::token_stream::{TokenStream, TokenStreamBase};
use crate::core::codecs::knn_field_vectors_writer::VectorValueEnum;
use crate::core::document::field_type::FieldType;
use crate::core::document::fields::FieldTokenStreamEnum;
use crate::core::document::invertable_field::InvertableType;
use crate::core::index::BinaryValueEnum;
use crate::core::index::BytesRef;
use crate::core::index::doc_values_type::DocValuesType;
use crate::core::index::index_options::IndexOptions;
use crate::core::index::indexable_field::{
  IndexableField, IndexingTokenStream, ReusedIndexingTokenStream,
};
use crate::core::index::indexable_field_type::IndexableFieldType;
use crate::core::util::attribute_source::{AttributeSource, Attributes};
use crate::core::util::close::Closeable;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::number::Number;
use crate::{either_token_stream, impl_from_for_enum};
use std::borrow::{Borrow, Cow};
use std::fmt;
use std::fmt::{Debug, Display};
use std::sync::Arc;

/// Expert: directly creates a field for a document. Most users should use one
/// of the convenience implementations:
///
/// - [`TextField`](crate::core::document::text_field::TextField):
///   [`Reader`](std::io::Read) or `String` indexed for full-text search.
/// - [`StringField`](crate::core::document::string_field::StringField): `String`
///   indexed verbatim as a single token.
/// - [`IntField`](crate::core::document::int_field::IntField): `i32` indexed for
///   exact/range queries.
/// - [`LongField`](crate::core::document::long_field::LongField): `i64` indexed for
///   exact/range queries.
/// - [`FloatField`](crate::core::document::float_field::FloatField): `f32` indexed
///   for exact/range queries.
/// - [`DoubleField`](crate::core::document::double_field::DoubleField): `f64` indexed
///   for exact/range queries.
/// - [`SortedDocValuesField`](crate::core::document::sorted_doc_values_field::SortedDocValuesField): `&[u8]` indexed column-wise for sorting/faceting.
/// - [`SortedSetDocValuesField`](crate::core::document::sorted_set_doc_values_field::SortedSetDocValuesField): `SortedSet<&[u8]>` indexed column-wise for sorting/faceting.
/// - [`NumericDocValuesField`](crate::core::document::numeric_doc_values_field::NumericDocValuesField): `i64` indexed column-wise for sorting/faceting.
/// - [`SortedNumericDocValuesField`](crate::core::document::sorted_numeric_doc_values_field::SortedNumericDocValuesField): `SortedSet<i64>` indexed column-wise for sorting/faceting.
/// - [`StoredField`](crate::core::document::stored_field::StoredField): Stored-only
///   value for retrieving in summary results.
///
/// Field constructors borrow static names and move owned strings. Convert a
/// non-static borrowed name to an owned string before passing it to a constructor.
///
/// A field is a section of a document. Each field has three parts: name, type,
/// and value. Values may be text (`String`, [`ReaderEnum`], or a pre-analyzed
/// [`TokenStream`]), binary (`&[u8]`), or numeric ([`Number`]). Fields are
/// optionally stored in the index so they can be returned with document hits.
///
/// # Note
/// The field type is an [`IndexableFieldType`]. Modifying the state of the
/// [`IndexableFieldType`] will affect any field using it. It is strongly
/// recommended not to make changes after field instantiation.
pub struct Field<FT = FieldType> {
  /// Field's type.
  indexable_field_type: FT,
  /// Static names are borrowed; owned names retain the former tight allocation.
  pub(crate) name: Cow<'static, str>,
  /// Field's value.
  pub(crate) fields_data: FieldDataEnum,
}
impl<FT: Borrow<FieldType>> Field<FT> {
  /// Expert: creates a field with no initial value. This is intended to be
  /// used by custom [`Field`] implementations with preconfigured
  /// [`IndexableFieldType`].
  ///
  /// # Parameters
  /// - `name`: Field name.
  /// - `field_type`: Field type.
  ///
  pub fn new<T, FD>(name: T, fields_data: FD, indexable_field_type: FT) -> Self
  where
    T: Into<Cow<'static, str>>,
    FD: Into<FieldDataEnum>,
  {
    Self {
      name: match name.into() {
        Cow::Owned(name) => Cow::Owned(name.into_boxed_str().into_string()),
        name => name,
      },
      fields_data: match fields_data.into() {
        FieldDataEnum::String(text)
          if indexable_field_type.borrow().tokenized()
            && *indexable_field_type.borrow().index_options() != IndexOptions::None =>
        {
          FieldDataEnum::SharedString(Arc::new(text))
        },
        value => value,
      },
      indexable_field_type,
    }
  }
  /// Creates a field with a [`ReaderEnum`] value.
  ///
  /// # Parameters
  /// - `name`: Field name.
  /// - `reader`: Reader value.
  /// - `field_type`: Field type.
  ///
  /// # Errors
  /// - Returns an error if the field's type is `stored()`, or if
  ///   `tokenized()` is `false`.
  pub fn from_reader<T, R>(name: T, reader: R, indexable_field_type: FT) -> Result<Self>
  where
    T: Into<Cow<'static, str>>,
    R: Into<ReaderEnum>,
  {
    if indexable_field_type.borrow().stored() {
      return Err(LuceneError::illegal_argument(
        "fields with a Reader value cannot be stored",
      ));
    }
    if !indexable_field_type.borrow().tokenized() {
      return Err(LuceneError::illegal_argument(
        "non-tokenized fields must use String values",
      ));
    }
    Ok(Field {
      indexable_field_type,
      name: match name.into() {
        Cow::Owned(name) => Cow::Owned(name.into_boxed_str().into_string()),
        name => name,
      },
      fields_data: reader.into().into(),
    })
  }
  /// Creates a field with a [`TokenStream`] value.
  ///
  /// # Parameters
  /// - `name`: Field name.
  /// - `token_stream`: [`TokenStream`] value.
  /// - `field_type`: Field type.
  ///
  /// # Errors
  /// - Returns an error if the field's type is `stored()`, `tokenized()` is
  ///   `false`, or `indexed()` is `false`.
  pub fn from_token_stream<T, V>(name: T, token_stream: V, indexable_field_type: FT) -> Result<Self>
  where
    T: Into<Cow<'static, str>>,
    V: Into<FieldTokenStreamEnum>,
  {
    if !indexable_field_type.borrow().tokenized()
      || indexable_field_type.borrow().index_options() == &IndexOptions::None
    {
      return Err(LuceneError::illegal_argument(
        "TokenStream fields must be indexed and tokenized",
      ));
    }
    if indexable_field_type.borrow().stored() {
      return Err(LuceneError::illegal_argument(
        "TokenStream fields cannot be stored",
      ));
    }
    let ts = token_stream.into();
    Ok(Field {
      indexable_field_type,
      name: match name.into() {
        Cow::Owned(name) => Cow::Owned(name.into_boxed_str().into_string()),
        name => name,
      },
      fields_data: ts.into(),
    })
  }
  /// Creates a field with a binary value.
  ///
  /// # Note
  /// An owned `Vec<u8>` is moved into the field without copying its contents.
  /// Borrowed slices are copied; arrays are moved into a new vector.
  ///
  /// # Parameters
  /// - `name`: Field name.
  /// - `value`: Binary content from a vector, array or slice.
  /// - `field_type`: Field type.
  ///
  /// # Errors
  /// - Returns an error if the field's type is `indexed()`.
  pub fn from_binary<T, V>(name: T, value: V, indexable_field_type: FT) -> Result<Self>
  where
    T: Into<Cow<'static, str>>,
    V: Into<Vec<u8>>,
  {
    let value = value.into();
    let len = value.len();
    Self::from_binary_range(name, value, 0, len, indexable_field_type)
  }
  /// Creates a field with a binary value.
  ///
  /// # Note
  /// An owned `Vec<u8>` is moved into the field without copying its contents.
  /// Borrowed slices are copied; arrays are moved into a new vector.
  ///
  /// # Parameters
  /// - `name`: Field name.
  /// - `value`: Binary content from a vector, array or slice.
  /// - `offset`: Starting position in the byte array.
  /// - `length`: Valid length of the byte array.
  /// - `field_type`: Field type.
  ///
  /// # Errors
  /// - Returns an error if the field's type is `indexed()`.
  pub fn from_binary_range<T, V>(
    name: T,
    value: V,
    offset: usize,
    length: usize,
    indexable_field_type: FT,
  ) -> Result<Self>
  where
    T: Into<Cow<'static, str>>,
    V: Into<Vec<u8>>,
  {
    let value = value.into();
    let value = BytesRef::from_slice(value, offset, length);
    Self::from_bytes_ref(name, value, indexable_field_type)
  }
  /// Creates a field with a binary value.
  ///
  /// # Note
  /// Owned bytes and `BytesRef` values are moved without cloning their buffers.
  /// Borrowed bytes are copied; existing `BytesRef` offsets are preserved.
  ///
  /// # Parameters
  /// - `name`: Field name.
  /// - `bytes`: Binary content convertible to `BytesRef<Vec<u8>>`.
  /// - `field_type`: Field type.
  ///
  /// # Errors
  /// - Returns an error if the field's type is `indexed()`.
  pub fn from_bytes_ref<T, B>(name: T, bytes: B, indexable_field_type: FT) -> Result<Self>
  where
    T: Into<Cow<'static, str>>,
    B: Into<BytesRef<Vec<u8>>>,
  {
    if indexable_field_type
      .borrow()
      .index_options()
      .cmp(&IndexOptions::DocsAndFreqsAndPositionsAndOffsets)
      != std::cmp::Ordering::Less
      || indexable_field_type.borrow().store_term_vector_offsets()
    {
      return Err(LuceneError::illegal_argument(
        "It doesn't make sense to index offsets on binary fields",
      ));
    }
    if indexable_field_type.borrow().index_options() != &IndexOptions::None
      && indexable_field_type.borrow().tokenized()
    {
      return Err(LuceneError::illegal_argument(
        "cannot set a BytesRef value on a tokenized field",
      ));
    }
    if indexable_field_type.borrow().index_options() == &IndexOptions::None
      && indexable_field_type.borrow().point_dimension_count() == 0
      && indexable_field_type.borrow().doc_values_type() == &DocValuesType::None
      && !indexable_field_type.borrow().stored()
    {
      return Err(LuceneError::illegal_argument(
        "it doesn't make sense to have a field that is neither indexed, nor doc-valued, nor stored",
      ));
    }
    Ok(Field {
      indexable_field_type,
      name: match name.into() {
        Cow::Owned(name) => Cow::Owned(name.into_boxed_str().into_string()),
        name => name,
      },
      fields_data: FieldDataEnum::Binary(bytes.into()),
    })
  }
  /// Creates a field with a `String` value.
  ///
  /// # Parameters
  /// - `name`: Field name.
  /// - `value`: Borrowed text or an owned string. Borrowed analyzed text uses
  ///   one immutable shared allocation; owned strings keep their buffer.
  /// - `field_type`: Field type.
  ///
  /// # Errors
  /// - Returns an error if the field's type is neither `indexed()` nor
  ///   `stored()`.
  /// - Returns an error if `indexed()` is `false` but `store_term_vectors()`
  ///   is `true`.
  pub fn from_string<'a, T1, T2>(name: T1, value: T2, indexable_field_type: FT) -> Result<Self>
  where
    T1: Into<Cow<'static, str>>,
    T2: Into<Cow<'a, str>>,
  {
    if !indexable_field_type.borrow().stored()
      && *indexable_field_type.borrow().index_options() == IndexOptions::None
    {
      return Err(LuceneError::illegal_argument(
        "it doesn't make sense to have a field that is neither indexed nor stored",
      ));
    }
    let shared_text = indexable_field_type.borrow().tokenized()
      && *indexable_field_type.borrow().index_options() != IndexOptions::None;
    Ok(Field {
      indexable_field_type,
      name: match name.into() {
        Cow::Owned(name) => Cow::Owned(name.into_boxed_str().into_string()),
        name => name,
      },
      fields_data: if shared_text {
        match value.into() {
          Cow::Borrowed(text) => FieldDataEnum::SharedText(Arc::from(text)),
          Cow::Owned(text) => FieldDataEnum::SharedString(Arc::new(text)),
        }
      } else {
        FieldDataEnum::String(value.into().into_owned())
      },
    })
  }
  /// Returns the [`TokenStream`] for this field to be used when indexing, or
  /// `None` if not set. If `None`, the [`ReaderEnum`] value or `String` value
  /// is analyzed to produce the indexed tokens.
  pub fn token_stream_value(&mut self) -> Result<Option<&mut FieldTokenStreamEnum>> {
    match self.fields_data {
      FieldDataEnum::TokenStream(ref mut token_stream) => Ok(Some(token_stream)),
      _ => Ok(None),
    }
  }
  /// Expert: changes the value of this field. This can be used during
  /// indexing to re-use a single [`Field`] instance to improve indexing
  /// speed by reducing GC overhead from creating and reclaiming
  /// [`Field`] instances. Typically, a single [`Document`](crate::core::document::document::Document) instance is also
  /// re-used, which is especially beneficial for small documents.
  ///
  /// # Note
  /// Each [`Field`] instance should only be used once within a single
  /// [`Document`](crate::core::document::document::Document) instance. See [ImproveIndexingSpeed](http://wiki.apache.org/lucene-java/ImproveIndexingSpeed) for details.
  ///
  /// Borrowed text reuses the current string's allocation. Owned strings are
  /// moved into the field. Custom inputs must convert to [`Cow<'a, str>`](Cow).
  pub fn set_string_value<'a, T>(&mut self, value: T) -> Result<()>
  where
    T: Into<Cow<'a, str>>,
  {
    match &mut self.fields_data {
      FieldDataEnum::String(current) => match value.into() {
        Cow::Borrowed(value) => value.clone_into(current),
        Cow::Owned(value) => *current = value,
      },
      FieldDataEnum::SharedText(_) => {
        // Mutable text retains the reusable String representation after this first update.
        let value = value.into();
        self.fields_data = FieldDataEnum::SharedString(Arc::new(value.into_owned()));
      },
      FieldDataEnum::SharedString(current) => {
        let value = value.into();
        if let Some(current) = Arc::get_mut(current) {
          match value {
            Cow::Borrowed(value) => value.clone_into(current),
            Cow::Owned(value) => *current = value,
          }
        } else {
          // A retained reader must continue to see the previous value.
          *current = Arc::new(value.into_owned());
        }
      },
      _ => {
        return Err(LuceneError::illegal_argument(format!(
          "cannot change value type from {:?} to String",
          self.fields_data
        )));
      },
    }
    Ok(())
  }
  /// Expert: changes the value of this field. See
  /// [`set_string_value`](Field::set_string_value).
  pub fn set_reader_value<R>(&mut self, value: R) -> Result<()>
  where
    R: Into<ReaderEnum>,
  {
    match &self.fields_data {
      FieldDataEnum::Reader(_) => {},
      _ => {
        return Err(LuceneError::illegal_argument(format!(
          "cannot change value type from {:?} to Reader",
          self.fields_data
        )));
      },
    }

    self.fields_data = FieldDataEnum::Reader(value.into());
    Ok(())
  }
  pub fn set_vec_value<V>(&mut self, value: V) -> Result<()>
  where
    V: Into<Vec<u8>>,
  {
    self.set_bytes_value(BytesRef::from_bytes(value.into()))
  }
  /// Expert: changes the value of this field. See
  /// [`set_string_value`](Field::set_string_value).
  ///
  /// Accepts text, byte arrays, vectors, slices, and `BytesRef` values.
  /// Owned buffers are moved; borrowed inputs reuse the current buffer. `BytesRef` offsets
  /// and lengths are preserved.
  pub fn set_bytes_value<'a, B>(&mut self, value: B) -> Result<()>
  where
    B: Into<BinaryValueEnum<'a>>,
  {
    match &mut self.fields_data {
      FieldDataEnum::Binary(current) => match value.into() {
        BinaryValueEnum::Owned(value) => *current = value,
        BinaryValueEnum::Borrowed(value) => {
          current.copy_from_slice(&value.bytes);
          current.offset = value.offset;
          current.length = value.length;
        },
        BinaryValueEnum::Slice(value) => {
          current.copy_from_slice(value.bytes);
          current.offset = value.offset;
          current.length = value.length;
        },
        BinaryValueEnum::Inline { bytes, length } => {
          current.copy_from_slice(&bytes[..length]);
        },
      },
      _ => {
        return Err(LuceneError::illegal_argument(format!(
          "cannot change value type from {:?} to BytesRef",
          self.fields_data
        )));
      },
    }
    Ok(())
  }
  /// Expert: changes the value of this field. See
  /// [`set_string_value`](Field::set_string_value).
  pub fn set_byte_value(&mut self, value: u8) -> Result<()> {
    match &self.fields_data {
      FieldDataEnum::Number(Number::U8(_)) => {},
      _ => {
        return Err(LuceneError::illegal_argument(format!(
          "cannot change value type from {:?} to Byte",
          self.fields_data
        )));
      },
    }
    self.fields_data = value.into();
    Ok(())
  }
  /// Expert: changes the value of this field. See
  /// [`set_string_value`](Field::set_string_value).
  pub fn set_short_value(&mut self, value: i16) -> Result<()> {
    match &self.fields_data {
      FieldDataEnum::Number(Number::I16(_)) => {},
      _ => {
        return Err(LuceneError::illegal_argument(format!(
          "cannot change value type from {:?} to Short",
          self.fields_data
        )));
      },
    }
    self.fields_data = FieldDataEnum::Number(Number::I16(value));
    Ok(())
  }
  /// Expert: changes the value of this field. See
  /// [`set_string_value`](Field::set_string_value).
  pub fn set_int_value(&mut self, value: i32) -> Result<()> {
    match &self.fields_data {
      FieldDataEnum::Number(Number::I32(_)) => {},
      _ => {
        return Err(LuceneError::illegal_argument(format!(
          "cannot change value type from {:?} to Integer",
          self.fields_data
        )));
      },
    }

    self.fields_data = FieldDataEnum::Number(Number::I32(value));
    Ok(())
  }
  /// Expert: changes the value of this field. See
  /// [`set_string_value`](Field::set_string_value).
  pub fn set_long_value(&mut self, value: i64) -> Result<()> {
    match &mut self.fields_data {
      FieldDataEnum::Number(Number::I64(current)) => *current = value,
      _ => {
        return Err(LuceneError::illegal_argument(format!(
          "cannot change value type from {:?} to Long",
          self.fields_data
        )));
      },
    }
    Ok(())
  }
  /// Expert: changes the value of this field. See
  /// [`set_string_value`](Field::set_string_value).
  pub fn set_float_value(&mut self, value: f32) -> Result<()> {
    match &self.fields_data {
      FieldDataEnum::Number(Number::F32(_)) => {},
      _ => {
        return Err(LuceneError::illegal_argument(format!(
          "cannot change value type from {:?} to Float",
          self.fields_data
        )));
      },
    }

    self.fields_data = FieldDataEnum::Number(Number::F32(value));
    Ok(())
  }
  /// Expert: changes the value of this field. See
  /// [`set_string_value`](Field::set_string_value).
  pub fn set_double_value(&mut self, value: f64) -> Result<()> {
    match &self.fields_data {
      FieldDataEnum::Number(Number::F64(_)) => {},
      _ => {
        return Err(LuceneError::illegal_argument(format!(
          "cannot change value type from {:?} to Double",
          self.fields_data
        )));
      },
    }

    self.fields_data = FieldDataEnum::Number(Number::F64(value));
    Ok(())
  }
  /// Expert: sets the token stream to be used for indexing.
  pub fn set_token_stream<S>(&mut self, token_stream: S) -> Result<()>
  where
    S: Into<FieldTokenStreamEnum>,
  {
    match &self.fields_data {
      FieldDataEnum::TokenStream(_) => {},
      _ => {
        return Err(LuceneError::illegal_argument(format!(
          "cannot change value type from {:?} to TokenStream",
          self.fields_data
        )));
      },
    }

    self.fields_data = FieldDataEnum::TokenStream(token_stream.into());
    Ok(())
  }
}
impl<FT: Borrow<FieldType>> IndexableField for Field<FT> {
  fn name(&self) -> &str {
    &self.name
  }

  type FieldType<'a>
    = &'a FieldType
  where
    Self: 'a;

  /// Returns the [`FieldType`] for this field.
  fn field_type(&self) -> Self::FieldType<'_> {
    self.indexable_field_type.borrow()
  }
  fn token_stream<'a, A>(
    &'a mut self,
    analyzer: &'a A,
    reuse_token_stream: &'a mut Option<ReusedIndexingTokenStream>,
  ) -> Result<IndexingTokenStream<'a>>
  where
    A: Analyzer,
  {
    if *self.field_type().index_options() == IndexOptions::None {
      return Ok(None);
    }

    if !self.field_type().tokenized() {
      if let Some(string_value) = self.string_value()? {
        if !matches!(
          reuse_token_stream.as_ref(),
          Some(ReusedIndexingTokenStream::B(_))
        ) {
          *reuse_token_stream = Some(ReusedIndexingTokenStream::B(StringTokenStream::new()));
        }

        let stream = reuse_token_stream
          .as_mut()
          .ok_or_else(|| LuceneError::illegal_state("should StringTokenStream here"))?;
        match stream {
          ReusedIndexingTokenStream::B(s) => s.set_value(string_value.as_ref())?,
          ReusedIndexingTokenStream::A(_) => {
            return Err(LuceneError::illegal_state("should StringTokenStream here"));
          },
        }

        return Ok(Some(IndexingTokenStreamEnum3::Reused(stream)));
      }

      if let Some(binary_value) = self.binary_value()?.map(|v| v.into_owned()) {
        if !matches!(
          reuse_token_stream.as_ref(),
          Some(ReusedIndexingTokenStream::A(_))
        ) {
          *reuse_token_stream = Some(ReusedIndexingTokenStream::A(BinaryTokenStream::new()?));
        }
        let stream = reuse_token_stream
          .as_mut()
          .ok_or_else(|| LuceneError::illegal_state("should BinaryTokenStream here"))?;
        match stream {
          ReusedIndexingTokenStream::A(s) => s.set_value(binary_value),
          ReusedIndexingTokenStream::B(_) => {
            return Err(LuceneError::illegal_state("should BinaryTokenStream here"));
          },
        }
        return Ok(Some(IndexingTokenStreamEnum3::Reused(stream)));
      }
      debug_assert!(reuse_token_stream.is_none());
    }

    debug_assert!(reuse_token_stream.is_none());
    if let FieldDataEnum::TokenStream(ref mut token_stream) = self.fields_data {
      return Ok(Some(IndexingTokenStreamEnum3::FieldTokenStream(
        token_stream,
      )));
    }

    if let Some(reader) = self.take_reader_value()? {
      Ok(Some(IndexingTokenStreamEnum3::AnalyzerTokenStream(
        analyzer.token_stream(self.name(), reader)?,
      )))
    } else if let FieldDataEnum::SharedText(text) = &self.fields_data {
      Ok(Some(IndexingTokenStreamEnum3::AnalyzerTokenStream(
        analyzer.token_stream_from_text(self.name(), AnalyzerText::SharedText(Arc::clone(text)))?,
      )))
    } else if let FieldDataEnum::SharedString(text) = &self.fields_data {
      Ok(Some(IndexingTokenStreamEnum3::AnalyzerTokenStream(
        analyzer.token_stream_from_text(self.name(), Arc::clone(text).into())?,
      )))
    } else if let Some(v) = self.string_value()? {
      let token_stream = match v {
        Cow::Borrowed(text) => analyzer.token_stream_from_text(self.name(), text.into())?,
        Cow::Owned(text) => analyzer.token_stream(self.name(), ReaderEnum::from(text))?,
      };
      Ok(Some(IndexingTokenStreamEnum3::AnalyzerTokenStream(
        token_stream,
      )))
    } else {
      Err(LuceneError::illegal_state(format!(
        "Field must have either TokenStream, String, Reader or Number value; got {}",
        self
      )))
    }
  }

  fn binary_value(&self) -> Result<Option<BinaryValueEnum<'_>>> {
    if let FieldDataEnum::Binary(bytes) = &self.fields_data {
      Ok(Some(BinaryValueEnum::Borrowed(bytes)))
    } else {
      Ok(None)
    }
  }

  fn take_binary_value(&mut self) -> Result<Option<BytesRef<Vec<u8>>>> {
    if !matches!(self.fields_data, FieldDataEnum::Binary(_)) {
      return Ok(None);
    }
    if let FieldDataEnum::Binary(binary) =
      std::mem::replace(&mut self.fields_data, FieldDataEnum::Dummy(()))
    {
      Ok(Some(binary))
    } else {
      Ok(None)
    }
  }

  /// Returns the value of the field as a `String`, or `None` if not set.
  /// If `None`, the [`ReaderEnum`] value or binary value is used.
  ///
  /// Exactly one of `string_value()`, `reader_value()`, or `binary_value()`
  /// must be set.
  fn string_value(&self) -> Result<Option<Cow<'_, str>>> {
    match &self.fields_data {
      FieldDataEnum::String(s) => Ok(Some(Cow::Borrowed(s))),
      FieldDataEnum::SharedString(s) => Ok(Some(Cow::Borrowed(s.as_str()))),
      FieldDataEnum::SharedText(s) => Ok(Some(Cow::Borrowed(s))),
      FieldDataEnum::Number(n) => Ok(Some(Cow::Owned(n.to_string()))),
      _ => Ok(None),
    }
  }

  fn take_string_value(&mut self) -> Result<Option<String>> {
    if !matches!(
      self.fields_data,
      FieldDataEnum::String(_) | FieldDataEnum::SharedString(_) | FieldDataEnum::SharedText(_)
    ) && !matches!(self.fields_data, FieldDataEnum::Number(_))
    {
      return Ok(None);
    }
    match std::mem::replace(&mut self.fields_data, FieldDataEnum::Dummy(())) {
      FieldDataEnum::String(s) => Ok(Some(s)),
      FieldDataEnum::SharedString(s) => Ok(Some(
        Arc::try_unwrap(s).unwrap_or_else(|s| s.as_ref().clone()),
      )),
      FieldDataEnum::SharedText(s) => Ok(Some(s.to_string())),
      FieldDataEnum::Number(n) => Ok(Some(n.to_string())),
      _ => Ok(None),
    }
  }

  fn get_char_sequence_value(&self) -> Result<Option<Cow<'_, str>>> {
    if let FieldDataEnum::String(s) = &self.fields_data {
      Ok(Some(Cow::Borrowed(s)))
    } else {
      self.string_value()
    }
  }

  /// Returns the value of the field as a [`ReaderEnum`], or `None` if not set.
  /// If `None`, the `String` value or binary value is used.
  ///
  /// Exactly one of `string_value()`, `reader_value()`, or `binary_value()`
  /// must be set.
  fn take_reader_value(&mut self) -> Result<Option<ReaderEnum>> {
    if !matches!(self.fields_data, FieldDataEnum::Reader(_)) {
      return Ok(None);
    }
    if let FieldDataEnum::Reader(reader) =
      std::mem::replace(&mut self.fields_data, FieldDataEnum::Dummy(()))
    {
      Ok(Some(reader))
    } else {
      Ok(None)
    }
  }

  fn numeric_value(&self) -> Result<Option<Number>> {
    if let FieldDataEnum::Number(n) = &self.fields_data {
      Ok(Some(n.clone()))
    } else {
      Ok(None)
    }
  }

  type StoredValue<'a>
    = &'a FieldDataEnum
  where
    Self: 'a;

  fn stored_value(&self) -> Result<Option<Self::StoredValue<'_>>> {
    if !self.indexable_field_type.borrow().stored() {
      return Ok(None);
    }

    match &self.fields_data {
      FieldDataEnum::Number(_)
      | FieldDataEnum::Binary(_)
      | FieldDataEnum::String(_)
      | FieldDataEnum::SharedString(_)
      | FieldDataEnum::SharedText(_) => Ok(Some(&self.fields_data)),
      _ => Err(LuceneError::illegal_state(
        "stored field data must be numeric, binary, or a string",
      )),
    }
  }

  fn invertable_type(&self) -> &InvertableType {
    &InvertableType::TokenStream
  }
  fn float_vector_value(&self) -> Result<&[f32]> {
    if let FieldDataEnum::VectorValue(v) = &self.fields_data {
      v.as_floats()
    } else {
      Err(LuceneError::unsupported_operation(""))
    }
  }
  fn byte_vector_value(&self) -> Result<&[u8]> {
    if let FieldDataEnum::VectorValue(v) = &self.fields_data {
      v.as_bytes()
    } else {
      Err(LuceneError::unsupported_operation(""))
    }
  }
}
impl<FT: Borrow<FieldType>> FieldBase for Field<FT> {}
impl<FT: Borrow<FieldType>> Display for Field<FT> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}<{}:", self.indexable_field_type.borrow(), self.name)?;

    write!(f, "{}", self.fields_data)?;

    write!(f, ">")
  }
}

pub trait FieldBase {
  /// Updates binary content from text, byte arrays, vectors, slices, or `BytesRef`.
  /// Supporting fields move owned buffers and reuse storage for borrowed inputs.
  fn set_bytes_value<'a, B>(&mut self, _value: B) -> Result<()>
  where
    B: Into<BinaryValueEnum<'a>>,
  {
    Err(LuceneError::not_implemented(
      "set_bytes_value not implement",
    ))
  }
  fn set_byte_value(&mut self, _value: u8) -> Result<()> {
    Err(LuceneError::not_implemented("set_byte_value not implement"))
  }
  fn set_short_value(&mut self, _value: i16) -> Result<()> {
    Err(LuceneError::not_implemented(
      "set_short_value not implement",
    ))
  }
  fn set_int_value(&mut self, _value: i32) -> Result<()> {
    Err(LuceneError::not_implemented("set_int_value not implement"))
  }
  fn set_long_value(&mut self, _value: i64) -> Result<()> {
    Err(LuceneError::not_implemented("set_long_value not implement"))
  }
  fn set_float_value(&mut self, _value: f32) -> Result<()> {
    Err(LuceneError::not_implemented(
      "set_float_value not implement",
    ))
  }
  fn set_double_value(&mut self, _value: f64) -> Result<()> {
    Err(LuceneError::not_implemented(
      "set_double_value not implement",
    ))
  }
  fn set_token_stream<S>(&mut self, _token_stream: S) -> Result<()>
  where
    S: Into<FieldTokenStreamEnum>,
  {
    Err(LuceneError::not_implemented(
      "set_token_stream not implement",
    ))
  }
  fn set_string_value<'a, T>(&mut self, _value: T) -> Result<()>
  where
    T: Into<Cow<'a, str>>,
  {
    Err(LuceneError::not_implemented(
      "set_string_value not implement",
    ))
  }
  /// Updates reader content from a concrete reader or another `ReaderEnum` input.
  fn set_reader_value<R>(&mut self, _value: R) -> Result<()>
  where
    R: Into<ReaderEnum>,
  {
    Err(LuceneError::not_implemented(
      "set_reader_value not implement",
    ))
  }
}
/// Specifies whether and how a field should be stored.
pub enum Store {
  /// Store the original field value in the index. This is useful for short
  /// texts like a document's title which should be displayed with the
  /// results. The value is stored in its original form, i.e. no analyzer
  /// is used before it is stored.
  Yes,

  /// Do not store the field value in the index.
  No,
}
impl From<Store> for bool {
  fn from(store: Store) -> bool {
    matches!(store, Store::Yes)
  }
}

pub enum FieldDataEnum {
  Number(Number),
  Binary(BytesRef<Vec<u8>>),
  String(String),
  /// Immutable string storage shared with readers by analyzed fields.
  SharedString(Arc<String>),
  /// Borrowed analyzed input copied into one reference-counted allocation.
  SharedText(Arc<str>),
  Reader(ReaderEnum),
  TokenStream(FieldTokenStreamEnum),
  // used to std::mem::replace(FieldDataEnum)
  Dummy(()),
  VectorValue(VectorValueEnum),
}
impl Debug for FieldDataEnum {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Number(v) => f.debug_tuple("Number").field(v).finish(),
      Self::Binary(v) => f.debug_tuple("Binary").field(v).finish(),
      Self::String(v) => f.debug_tuple("String").field(v).finish(),
      Self::SharedString(v) => f.debug_tuple("String").field(v.as_ref()).finish(),
      Self::SharedText(v) => f.debug_tuple("String").field(v).finish(),
      Self::Reader(v) => f.debug_tuple("Reader").field(v).finish(),
      Self::TokenStream(v) => f.debug_tuple("TokenStream").field(v).finish(),
      Self::Dummy(v) => f.debug_tuple("Dummy").field(v).finish(),
      Self::VectorValue(v) => f.debug_tuple("VectorValue").field(v).finish(),
    }
  }
}
impl FieldDataEnum {
  /// Clones field data when its value supports independent ownership.
  ///
  /// Token streams carry mutable iteration state and cannot be cloned.
  pub fn try_clone(&self) -> Result<Self> {
    match self {
      Self::Number(n) => Ok(Self::Number(n.clone())),
      Self::Binary(b) => Ok(Self::Binary(b.clone())),
      Self::String(s) => Ok(Self::String(s.clone())),
      Self::SharedString(s) => Ok(Self::SharedString(Arc::new(s.as_ref().clone()))),
      Self::SharedText(s) => Ok(Self::SharedText(Arc::from(s.as_ref()))),
      Self::Reader(r) => Ok(Self::Reader(r.clone())),
      Self::TokenStream(_) => Err(LuceneError::illegal_state("token stream cannot be cloned")),
      Self::Dummy(d) => {
        let _: () = *d;
        Ok(Self::Dummy(()))
      },
      Self::VectorValue(v) => Ok(Self::VectorValue(v.clone())),
    }
  }
}

impl From<i32> for FieldDataEnum {
  fn from(v: i32) -> Self {
    FieldDataEnum::Number(Number::I32(v))
  }
}

impl From<i64> for FieldDataEnum {
  fn from(v: i64) -> Self {
    FieldDataEnum::Number(Number::I64(v))
  }
}

impl From<u8> for FieldDataEnum {
  fn from(v: u8) -> Self {
    FieldDataEnum::Number(Number::U8(v))
  }
}

impl From<i16> for FieldDataEnum {
  fn from(v: i16) -> Self {
    FieldDataEnum::Number(Number::I16(v))
  }
}

impl From<f32> for FieldDataEnum {
  fn from(v: f32) -> Self {
    FieldDataEnum::Number(Number::F32(v))
  }
}

impl From<f64> for FieldDataEnum {
  fn from(v: f64) -> Self {
    FieldDataEnum::Number(Number::F64(v))
  }
}
impl_from_for_enum!(
    FieldDataEnum,
    BytesRef<Vec<u8>> => Binary,
    String => String,
    ReaderEnum => Reader,
    FieldTokenStreamEnum => TokenStream,
     VectorValueEnum => VectorValue,
);

impl From<&str> for FieldDataEnum {
  fn from(s: &str) -> Self {
    FieldDataEnum::String(s.to_string())
  }
}

impl Display for FieldDataEnum {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      FieldDataEnum::Number(n) => write!(f, "{}", n),
      FieldDataEnum::Binary(b) => write!(f, "{}", b),
      FieldDataEnum::String(s) => write!(f, "{}", s),
      FieldDataEnum::SharedString(s) => write!(f, "{}", s),
      FieldDataEnum::SharedText(s) => write!(f, "{}", s),
      FieldDataEnum::Reader(r) => write!(f, "{:?}", r),
      FieldDataEnum::TokenStream(t) => write!(f, "{:?}", t),
      FieldDataEnum::Dummy(s) => write!(f, "{:?}", s),
      FieldDataEnum::VectorValue(v) => write!(f, "{:?}", v),
    }
  }
}
/// Creates a new TokenStream that returns a BytesRef as single token
pub struct BinaryTokenStream {
  used: bool,
  value: Option<BytesRef<Vec<u8>>>,
  token_stream_base: TokenStreamBase,
}

impl BinaryTokenStream {
  /// Creates a new TokenStream that returns a BytesRef as single token.
  pub(crate) fn new() -> Result<Self> {
    Ok(Self {
      used: false,
      value: None,
      token_stream_base: TokenStreamBase::new(BinaryTokenStreamAttributeImpl::new()?.into()),
    })
  }

  /// Sets the bytes value.
  pub(crate) fn set_value(&mut self, value: BytesRef<Vec<u8>>) {
    self.value = Some(value);
  }
}

impl Drop for BinaryTokenStream {
  fn drop(&mut self) {
    let _ = self.close();
  }
}

impl Closeable for BinaryTokenStream {
  fn close(&mut self) -> Result<()> {
    let _ = self.value.take();
    Ok(())
  }
}

impl TokenStream for BinaryTokenStream {
  fn increment_token(&mut self) -> Result<bool> {
    if self.used {
      return Ok(false);
    }
    self.token_stream_base.att.clear_attributes()?;
    let value = self.value.take();
    self.token_stream_base.att.set_bytes_ref(value)?;
    self.used = true;
    Ok(true)
  }

  fn end(&mut self) -> Result<()> {
    self.default_end()
  }

  fn reset(&mut self) -> Result<()> {
    self.used = false;
    Ok(())
  }

  fn get_attribute_source(&self) -> &Attributes {
    &self.token_stream_base.att
  }

  fn get_attribute_source_mut(&mut self) -> &mut Attributes {
    &mut self.token_stream_base.att
  }
}

pub struct StringTokenStream {
  used: bool,
  value: String,
  has_value: bool,
  end_offset: i32,
  token_stream_base: TokenStreamBase,
}
impl StringTokenStream {
  /// Creates a new TokenStream that returns a String as single token.
  pub(crate) fn new() -> Self {
    Self {
      used: false,
      value: String::new(),
      has_value: false,
      end_offset: 0,
      token_stream_base: TokenStreamBase::new(Attributes::default()),
    }
  }
  pub(crate) fn set_value(&mut self, value: &str) -> Result<()> {
    let utf16_length = if value.is_ascii() {
      value.len()
    } else if value.len() <= char::MAX.len_utf8() {
      value.chars().map(char::len_utf16).sum()
    } else {
      // Rust strings already contain valid scalar values. Four-byte UTF-8
      // sequences contribute one extra unit to Java-compatible offsets.
      value.chars().count() + value.bytes().filter(|byte| *byte >= 0xF0).count()
    };
    self.end_offset = i32::try_from(utf16_length)
      .map_err(|_| LuceneError::illegal_argument("string UTF-16 length exceeds i32::MAX"))?;
    self.value.clear();
    self.value.push_str(value);
    self.has_value = true;
    Ok(())
  }
}

impl Drop for StringTokenStream {
  fn drop(&mut self) {
    let _ = self.close();
  }
}

impl Closeable for StringTokenStream {
  fn close(&mut self) -> Result<()> {
    self.has_value = false;
    Ok(())
  }
}

impl TokenStream for StringTokenStream {
  fn increment_token(&mut self) -> Result<bool> {
    if self.used {
      return Ok(false);
    }
    self.token_stream_base.att.clear_attributes()?;
    if !self.has_value {
      return Err(LuceneError::illegal_argument("set_value() not call?"));
    }
    self.token_stream_base.att.append_str(Some(&self.value))?;
    self.token_stream_base.att.set_offset(0, self.end_offset)?;
    self.used = true;
    Ok(true)
  }

  fn end(&mut self) -> Result<()> {
    self.default_end()?;
    if !self.has_value {
      return Err(LuceneError::illegal_state(
        "StringTokenStream value is not set",
      ));
    }
    let final_offset = self.end_offset;
    self
      .token_stream_base
      .att
      .set_offset(final_offset, final_offset)
  }

  fn reset(&mut self) -> Result<()> {
    self.used = false;
    Ok(())
  }

  fn get_attribute_source(&self) -> &Attributes {
    &self.token_stream_base.att
  }

  fn get_attribute_source_mut(&mut self) -> &mut Attributes {
    &mut self.token_stream_base.att
  }
}
either_token_stream!(pub IndexingTokenStreamEnum3 { AnalyzerTokenStream: A, Reused: B,FieldTokenStream:C });