Skip to main content

field_collex/
collex.rs

1pub mod iter;
2pub mod se;
3
4use span_core::Span;
5use std::mem;
6use std::ops::Range;
7use std::vec::Vec;
8use thiserror::Error;
9use crate::*;
10
11fn dist_cmp<T: FieldValue>(target:T, a:T, b:T) -> std::cmp::Ordering {
12    let dist_a = if a > target { a - target } else { target - a };
13    let dist_b = if b > target { b - target } else { target - b };
14    dist_a.cmp(&dist_b)
15}
16
17type FieldIn<E,V> = Field<E,FieldCollex<E,V>>;
18type CollexField<E,V> = RawField<Field<E,FieldCollex<E,V>>>;
19
20pub(crate) type NewResult<T,V> = Result<T, NewFieldCollexError<V>>;
21
22#[derive(Error, Debug, Clone)]
23pub enum NewFieldCollexError<V>{
24    #[error("提供的 span 为空(大小为0)")]
25    EmptySpan(Span<V>, V),
26    #[error("提供的 unit 为0")]
27    NonPositiveUnit(Span<V>, V),
28}
29
30impl<V> NewFieldCollexError<V>{
31    pub fn unwrap(self) -> (Span<V>, V) {
32        match self {
33            Self::NonPositiveUnit(span, unit)
34            | Self::EmptySpan(span, unit)
35            => (span, unit)
36        }
37    }
38}
39
40
41pub(crate) type WithCapacityResult<T,V> = Result<T, WithCapacityFieldCollexError<V>>;
42
43#[derive(Error, Debug, Clone)]
44pub enum WithCapacityFieldCollexError<V>{
45    #[error("提供的 span 为空(大小为0)")]
46    EmptySpan(Span<V>, V),
47    #[error("提供的 unit <= 0")]
48    NonPositiveUnit(Span<V>, V),
49    #[error("提供的 capacity 超过最大块数量")]
50    OutOfSize(Span<V>, V),
51}
52
53impl<V> From<WithCapacityFieldCollexError<V>> for WithElementsFieldCollexError<V> {
54    fn from(value: WithCapacityFieldCollexError<V>) -> Self {
55        match value {
56            WithCapacityFieldCollexError::EmptySpan(s, u) => {Self::EmptySpan(s,u)}
57            WithCapacityFieldCollexError::NonPositiveUnit(s, u) => {Self::NonPositiveUnit(s,u)}
58            WithCapacityFieldCollexError::OutOfSize(..) => {unreachable!()}
59        }
60    }
61}
62
63impl<V> From<NewFieldCollexError<V>> for WithElementsFieldCollexError<V> {
64    fn from(value: NewFieldCollexError<V>) -> Self {
65        match value {
66            NewFieldCollexError::EmptySpan(s, u) => {Self::EmptySpan(s,u)}
67            NewFieldCollexError::NonPositiveUnit(s, u) => {Self::NonPositiveUnit(s,u)}
68        }
69    }
70}
71
72pub(crate) type WithElementsResult<T,V> = Result<T, WithElementsFieldCollexError<V>>;
73
74#[derive(Error, Debug, Clone)]
75pub enum WithElementsFieldCollexError<V>{
76    #[error("提供的 span 为空(大小为0)")]
77    EmptySpan(Span<V>, V),
78    #[error("提供的 unit <= 0")]
79    NonPositiveUnit(Span<V>, V),
80}
81
82impl<V> WithCapacityFieldCollexError<V>{
83    pub fn unwrap(self) -> (Span<V>, V) {
84        match self {
85            Self::NonPositiveUnit(span, unit)
86            | Self::EmptySpan(span, unit)
87            | Self::OutOfSize(span, unit)
88            => (span, unit)
89        }
90    }
91}
92
93
94pub(crate) type GetIndexResult<T> = Result<T, GetIndexFieldCollexError>;
95
96#[derive(Error, Debug, Clone)]
97pub enum GetIndexFieldCollexError {
98    #[error("目标值超出了当前FieldCollex的span范围")]
99    OutOfSpan,
100    #[error("当前无数据可查询")]
101    Empty,
102}
103
104macro_rules! impl_from_get_index_err {
105    ($err: ident) => {
106        impl From<GetIndexFieldCollexError> for $err{
107            fn from(value: GetIndexFieldCollexError) -> Self {
108                match value {
109                    GetIndexFieldCollexError::OutOfSpan => {Self::OutOfSpan}
110                    GetIndexFieldCollexError::Empty => {Self::Empty}
111                }
112            }
113        }
114    };
115    ($err: ident, $empty: ident) => {
116        impl From<GetIndexFieldCollexError> for $err{
117            fn from(value: GetIndexFieldCollexError) -> Self {
118                match value {
119                    GetIndexFieldCollexError::OutOfSpan => {Self::OutOfSpan}
120                    GetIndexFieldCollexError::Empty => {Self::$empty}
121                }
122            }
123        }
124    };
125}
126
127impl_from_get_index_err!(RemoveFieldCollexError, NotExist);
128
129pub(crate) type RemoveResult<T> = Result<T, RemoveFieldCollexError>;
130
131#[derive(Error, Debug, Clone)]
132pub enum RemoveFieldCollexError {
133    #[error("目标值超出了当前FieldCollex的span范围")]
134    OutOfSpan,
135    #[error("无匹配的数据")]
136    NotExist,
137}
138
139
140pub(crate) type InsertResult<E> = Result<(), InsertFieldCollexError<E>>;
141#[derive(Error, Debug, Clone)]
142pub enum InsertFieldCollexError<E> {
143    #[error("提供值超出了当前FieldCollex的span范围")]
144    OutOfSpan(E),
145    #[error("已存在此元素")]
146    AlreadyExist(E)
147}
148
149impl<E> InsertFieldCollexError<E> {
150    pub fn unwrap(self) -> E {
151        match self {
152            Self::AlreadyExist(e) => e,
153            Self::OutOfSpan(e) => e,
154        }
155    }
156    
157    pub fn map<F,N>(self, f: F) -> InsertFieldCollexError<N>
158    where
159        F: FnOnce(E) -> N
160    {
161        use InsertFieldCollexError::*;
162        match self {
163            AlreadyExist(e) => AlreadyExist(f(e)),
164            OutOfSpan(e) => OutOfSpan(f(e)),
165        }
166    }
167}
168
169
170#[derive(Debug, Clone)]
171pub struct TryExtendResult<V> {
172    pub out_of_span: Vec<V>,
173    pub already_exist: Vec<V>
174}
175
176pub(crate) type ModifyResult<R,T> = Result<R,ModifyFieldCollexError<T>>;
177#[derive(Error, Clone, Debug)]
178pub enum ModifyFieldCollexError<T> {
179    #[error("找不到对应元素")]
180    CannotFind,
181    #[error("刷新元素位置失败")]
182    InsertError(InsertFieldCollexError<T>),
183}
184
185impl<T> ModifyFieldCollexError<T> {
186    pub fn map<F,N>(self, f: F) -> ModifyFieldCollexError<N>
187    where
188        F: FnOnce(T) -> N
189    {
190        use ModifyFieldCollexError::*;
191        match self {
192            CannotFind => CannotFind,
193            InsertError(err) => InsertError(err.map(f)),
194        }
195    }
196}
197
198pub trait Collexetable<V> {
199    fn collexate(&self) -> V;
200    fn collexate_ref(&self) -> &V;
201    fn collexate_mut(&mut self) -> &mut V;
202    
203    fn collex_cmp<O>(&self, other: &O) -> std::cmp::Ordering
204    where
205        O: Collexetable<V>,
206        V: Ord
207    {
208        self.collexate_ref().cmp(other.collexate_ref())
209    }
210    
211    fn collex_eq<O>(&self, other: &O) -> bool
212    where
213        O: Collexetable<V>,
214        V: Eq
215    {
216        self.collexate_ref().eq(other.collexate_ref())
217    }
218    
219    fn collex_mut_eq<O>(&mut self, other: &mut O) -> bool
220    where
221        O: Collexetable<V>,
222        V: Eq
223    {
224        self.collexate_ref().eq(other.collexate_ref())
225    }
226}
227
228/// 每个块可以存多个内容(通过递归结构实现)
229/// 非空块可为单个元素或一个FieldCollex,以[`Field`]类型存储。
230///
231/// 实际存入E,计算时通过Collexetable<V>中的方法得到V,剩余与FieldSet完全一致
232#[derive(Debug, Clone)]
233pub struct FieldCollex<E,V>
234where
235    E: Collexetable<V>,
236    V: FieldValue,
237{
238    pub(crate) span: Span<V>,
239    pub(crate) unit: V,
240    pub(crate) items: Vec<CollexField<E,V>>,
241}
242
243impl<E,V> FieldCollex<E,V>
244where
245    E: Collexetable<V>,
246    V: FieldValue
247{
248    const SUB_FACTOR: usize = 64;
249    /// 提供span与unit,构建一个FieldCollex
250    ///
251    /// span为Key的范围,unit为每个块的大小,同时也是每个块之间的间隔
252    ///
253    /// 若unit为0 或 span为空,通过返回Err返还提供的数据
254    pub fn new(span: Span<V>, unit: V) -> NewResult<Self,V> {
255        use NewFieldCollexError::*;
256        
257        if unit <= V::zero() {
258            Err(NonPositiveUnit(span, unit))
259        } else if span.is_empty() {
260            Err(EmptySpan(span, unit))
261        } else {
262            Ok(Self {
263                span,
264                unit,
265                items: Vec::new()
266            })
267        }
268    }
269    
270    /// 提供span与unit,构建一个FieldCollex
271    ///
272    /// span为Key的范围,unit为每个块的大小,同时也是每个块之间的间隔
273    ///
274    /// 若unit为0、span为空、capacity大于最大块数量,通过返回Err返还提供的数据
275    pub fn with_capacity(span: Span<V>, unit: V, capacity: usize) -> WithCapacityResult<Self,V> {
276        use WithCapacityFieldCollexError::*;
277        if unit <= V::zero() {
278            Err(NonPositiveUnit(span, unit))
279        } else if span.is_empty() {
280            Err(EmptySpan(span, unit))
281        } else if match span.size(){
282            Ok(Some(size)) => {
283                capacity > (size / unit).ceil().into_usize()
284            },
285            Ok(None) => {false}
286            // is_empty为真时,永远不可能出现Err,因为它绝对有长度
287            _ => unreachable!()
288        } {
289            Err(OutOfSize(span, unit))
290        } else {
291            Ok(Self {
292                span,
293                unit,
294                items: Vec::with_capacity(capacity),
295            })
296        }
297    }
298    
299    /// 根据Vec快速构造FieldCollex,忽略非法值
300    pub fn with_elements(span: Span<V>, unit: V, mut other: Vec<E>) -> WithElementsResult<Self,V> {
301        other.sort_by(Collexetable::collex_cmp);
302        other.dedup_by(Collexetable::collex_mut_eq);
303        
304        let mut new = Self::new(span, unit)?;
305        // 第一个非法值的索引
306        let first_oob_idx = other.iter().enumerate().rev().try_for_each(
307            |(idx,e)|
308                if new.span.contains(e.collexate_ref()) {
309                    Err(idx+1)
310                } else {
311                    Ok(())
312                }
313        ).err().unwrap_or(0);
314        let vec = &other[0..first_oob_idx];
315        if vec.len()==0 {
316            // do nothing
317        } else if vec.len()==1 {
318            let _ = new.insert(other.into_iter().next().unwrap());
319        } else {
320            let cap = new.idx_of(vec[first_oob_idx-1].collexate_ref()) + 1;
321            // 预分配
322            let items = &mut new.items;
323            items.reserve(cap);
324            
325            // 提前插入第一个的内容
326            let mut last_idx = index_of!(new,vec[0].collexate_ref());
327            // 存在前置空块(自己为起点(==0)就是不存在)
328            if last_idx != 0 {
329                items.resize_with(last_idx ,|| RawField::Next(last_idx));
330            }
331            let _ = other.split_off(first_oob_idx);
332            let mut vec = other.into_iter();
333            items.push(RawField::Thing((last_idx,Field::Elem(vec.next().unwrap()))));
334            
335            // 遍历插入。0在上面
336            for elem in vec {
337                // 与上一个完全相同的情况不存在,已经用了dedup。
338                
339                let this_idx = index_of!(new,elem.collexate_ref());
340                // 若此与上一个处于同一个区间,转为Collex
341                if this_idx == last_idx {
342                    // 确保至少存在一个元素。见上
343                    match items[this_idx]
344                        // 有序集合顺序push导致idx相同时最后一个必定是上一个插入的Thing
345                        .as_thing_mut().1
346                    {
347                        Field::Elem(_) => {
348                            let span = Span::Finite({
349                                let start = *new.span.start() + new.unit * V::from_usize(this_idx);
350                                start..start + new.unit
351                            });
352                            let mut unit = new.unit/V::from_usize(Self::SUB_FACTOR);
353                            if unit.is_zero() {
354                                unit = V::min_positive();
355                            }
356                            let collex =
357                                FieldCollex::with_capacity(
358                                    span,
359                                    unit,
360                                    2
361                                ).unwrap_or_else(|err|
362                                    panic!("Called `FieldCollex::with_capacity` in `FieldCollex::with_elements` to make a new sub FieldSet, but get a error {err}")
363                                );
364                            
365                            let old =
366                                match mem::replace(&mut items[this_idx], RawField::Thing((this_idx ,Field::Collex(collex)))).unwrap() {
367                                    Field::Elem(e) => e,
368                                    Field::Collex(_) => unreachable!(),
369                                };
370                            let collex =
371                                match items[this_idx]
372                                    .as_thing_mut().1 {
373                                    Field::Elem(_) => unreachable!(),
374                                    Field::Collex(collex) => collex,
375                                };
376                            // TODO:改掉这个insert
377                            if let Err(_) = collex.insert(old) {
378                                panic!("Called `FieldCollex::insert` in `FieldCollex::with_elements` but get an unexpected error");
379                            }
380                            if let Err(_) = collex.insert(elem) {
381                                panic!("Called `FieldCollex::insert` in `FieldCollex::with_elements` but get an unexpected error");
382                            }
383                        }
384                        Field::Collex(collex) => {
385                            // TODO:改掉这个insert
386                            if let Err(_) = collex.insert(elem) {
387                                panic!("Called `FieldCollex::insert` in `FieldCollex::with_elements` but get an unexpected error");
388                            }
389                        }
390                    };
391                } else { // 与上一个处于不同区间,先填充Among再push自己
392                    items.resize_with(this_idx, ||RawField::Among(last_idx, this_idx));
393                    items.push(RawField::Thing((this_idx, Field::Elem(elem))))
394                }
395                last_idx = this_idx;
396            }
397        }
398        Ok(new)
399    }
400    
401    pub fn span(&self) -> &Span<V> {
402        &self.span
403    }
404    
405    pub fn unit(&self) -> &V {
406        &self.unit
407    }
408    
409    /// 返回最大块数量
410    ///
411    /// 若Span是无限区间,返回None
412    pub fn size(&self) -> Option<usize> {
413        // 确保在创建时就不可能为空区间。详见那些构造函数
414        match self.span.size(){
415            Ok(Some(size)) => Some((size / self.unit).ceil().into_usize()),
416            _ => None
417        }
418    }
419    
420    /// 返回已存在的块的数量
421    ///
422    /// 此值应小于等于最大块数量
423    #[inline(always)]
424    pub fn len(&self) -> usize {
425        self.items.len()
426    }
427    
428    /// Returns the total number of elements the inner vector can hold without reallocating.
429    ///
430    /// 此值应小于等于最大块数量
431    pub fn capacity(&self) -> usize {
432        self.items.capacity()
433    }
434    
435    /// 判断对应块是非空
436    pub(crate) fn is_thing(&self, idx: usize) -> bool {
437        if idx < self.items.len() {
438            matches!(self.items[idx], RawField::Thing(_))
439        } else { false }
440    }
441    
442    /// 计算指定值对应的块索引
443    ///
444    /// 此无任何前置检查,只会机械地返回目标相对于初始位置(区间的左端点)可能处于第几个块,但不确保这个块是否合法。<br>
445    /// 包含前置检查的版本是[`get_index`]
446    #[inline(always)]
447    pub(crate) fn idx_of(&self, target: &V) -> usize {
448        target.sub(*self.span.start()).div(self.unit).into_usize()
449    }
450    
451    /// 将内部Vec大小扩大到 idx+1
452    ///
453    /// 自动填充后继元素
454    ///
455    /// 返回值意味着是否进行了大小修改: <br>
456    /// 当前大小已达标时,没有进行大小修改,返回false
457    pub(crate) fn expand_to_idx(&mut self, idx: usize) -> bool {
458        let filler = match self.items.last() {
459            None =>
460                RawField::Void,
461            Some(last) => {
462                if let RawField::Thing(t) = last {
463                    RawField::prev_from(t)
464                } else {
465                    // 上面确保不是thing
466                    last.unchecked_clone()
467                }
468            }
469        };
470        self.expand_to(idx + 1, filler)
471    }
472    
473    /// 将内部Vec大小扩大到 new_size
474    ///
475    /// 返回值意味着是否进行了大小修改: <br>
476    /// 当前大小已达标时,没有进行大小修改,返回false
477    pub(crate) fn expand_to_with(&mut self, new_size: usize, maker: impl Fn() -> CollexField<E,V>) -> bool {
478        if self.items.len() < new_size {
479            self.items.resize_with(new_size, maker);
480            true
481        } else { false }
482    }
483    
484    pub(crate) fn expand_to(&mut self, new_size: usize, filler: CollexField<E,V>) -> bool {
485        if self.items.len() < new_size {
486            self.items.resize_with(new_size, ||filler.unchecked_clone());
487            true
488        } else { false }
489    }
490    
491    #[inline(always)]
492    #[must_use]
493    pub(crate) fn contains_idx(&self, idx: usize) -> bool {
494        idx < self.items.len()
495    }
496    
497    /// 查找对应是否存在与其collexate()值相同的元素
498    ///
499    pub fn contains(&self, elem: &E) -> bool {
500        let idx = self.idx_of(elem.collexate_ref());
501        if self.contains_idx(idx) {
502            match &self.items[idx] {
503                RawField::Thing((_, k)) =>
504                    match k {
505                        Field::Elem(e) => { elem.collex_eq(e) }
506                        Field::Collex(collex) => { collex.contains(elem) }
507                    }
508                _ => false
509            }
510        } else { false }
511    }
512    
513    /// 查找对应值是否存在
514    ///
515    pub fn contains_value(&self, value: V) -> bool {
516        let idx = self.idx_of(&value);
517        if self.contains_idx(idx) {
518            match &self.items[idx] {
519                RawField::Thing((_, k)) =>
520                    match k {
521                        Field::Elem(e) => { value.eq(e.collexate_ref())}
522                        Field::Collex(collex) => { collex.contains_value(value) }
523                    }
524                _ => false
525            }
526        } else { false }
527    }
528    
529    /// 通过索引返回块引用
530    ///
531    /// 索引对应块是非空则返回Some,带边界检查,越界视为None
532    pub(crate) fn get_field(&self, idx: usize) -> Option<&FieldIn<E, V>> {
533        if idx < self.items.len() {
534            match self.items[idx] {
535                RawField::Thing(ref v) => Some(&v.1),
536                _ => None
537            }
538        } else { None }
539    }
540    
541    
542    /// 通过索引得到当前或上一个非空块的(索引,块引用)
543    ///
544    /// 若块不为空,返回自己 <br>
545    /// 若块为空且有前一个非空块,返回该块 <br>
546    /// 若块为空且没有前一个非空块,返回None <br>
547    /// 提供的索引大于最后一个块,相当于最后一个块 <br>
548    pub(crate) fn get_prev_field(&self, idx: usize) -> Option<(usize,&FieldIn<E, V>)> {
549        Some(self.items[self.get_prev_index(idx)?].as_thing())
550    }
551    
552    /// 通过索引得到当前或下一个非空块的(索引,块引用)
553    ///
554    /// 若块不为空,返回自己 <br>
555    /// 若块为空且有后一个非空块,返回该块 <br>
556    /// 若块为空且没有后一个非空块,返回None <br>
557    /// 提供的索引大于最后一个块,返回None <br>
558    pub(crate) fn get_next_field(&self,idx: usize) -> Option<(usize,&FieldIn<E, V>)> {
559        Some(self.items[self.get_next_index(idx)?].as_thing())
560    }
561    
562    
563    /// 通过索引得到当前或上一个非空块的索引
564    ///
565    /// 若块不为空,返回自己 <br>
566    /// 若块为空且有前一个非空块,返回该块 <br>
567    /// 若块为空且没有前一个非空块,返回None <br>
568    /// 提供的索引大于最后一个块,相当于最后一个块 <br>
569    pub(crate) fn get_prev_index(&self, idx: usize) -> Option<usize> {
570        if idx < self.items.len() {
571            self.items[idx].thing_prev()
572        } else {
573            self.items.last()?.thing_prev()
574        }
575        
576    }
577    
578    /// 通过索引得到当前或下一个非空块的索引
579    ///
580    /// 若块不为空,返回自己 <br>
581    /// 若块为空且有后一个非空块,返回该块 <br>
582    /// 若块为空且没有后一个非空块,返回None <br>
583    /// 提供的索引大于最后一个块,返回None <br>
584    pub(crate) fn get_next_index(&self,idx: usize) -> Option<usize> {
585        if idx < self.items.len() {
586            self.items[idx].thing_next()
587        } else { None }
588    }
589    
590    
591    /// 找到第一个值的引用
592    pub fn first(&self) -> Option<&E> {
593        Some(self.first_field()?.1.first())
594    }
595    
596    /// 找最后一个值的引用
597    pub fn last(&self) -> Option<&E> {
598        Some(self.last_field()?.1.last())
599    }
600    
601    
602    /// 找到第一个非空块的(键,块引用)
603    pub(crate) fn first_field(&self) -> Option<(usize,&FieldIn<E, V>)> {
604        Some(self.items[self.first_index()?].as_thing())
605    }
606    
607    /// 找到最后一个非空块的(键,块引用)
608    pub(crate) fn last_field(&self) -> Option<(usize,&FieldIn<E, V>)> {
609        Some(self.items[self.last_index()?].as_thing())
610    }
611    
612    
613    /// 找到第一个非空块的索引
614    pub(crate) fn first_index(&self) -> Option<usize> {
615        let first = self.items.first()?;
616        first.thing_next()
617    }
618    
619    /// 找到最后一个非空块的索引
620    pub(crate) fn last_index(&self) -> Option<usize> {
621        self.items.last()?.thing_prev()
622    }
623    
624    /// target是否可置入idx
625    pub(crate) fn is_in_index(&self, idx: usize, target: &V) -> bool {
626        self.index_range(idx).contains(target)
627    }
628    
629    /// idx块的范围
630    pub(crate) fn index_range(&self, idx: usize) -> Range<V> {
631        let start = *self.span.start() + self.unit * V::from_usize(idx);
632        start..start + self.unit
633    }
634    
635    /// 批量插入元素,忽略错误值。
636    pub fn extend(&mut self, mut vec: Vec<E>) {
637        vec.sort_by(Collexetable::collex_cmp);
638        // 逐个插入
639        
640        for v in vec {
641            match self.insert(v) {
642                Err(err) => {
643                    match err {
644                        InsertFieldCollexError::OutOfSpan(_) => {
645                            break;
646                        }
647                        InsertFieldCollexError::AlreadyExist(_) => {}
648                    }
649                }
650                _ => {}
651            }
652        }
653    }
654    
655    /// 批量插入元素,返回插入的情况。
656    pub fn try_extend(&mut self, mut vec: Vec<E>) -> TryExtendResult<E> {
657        vec.sort_by(Collexetable::collex_cmp);
658        // 逐个检查并插入
659        
660        let mut out_of_span: Vec<E> = Vec::new();
661        let mut already_exist = Vec::new();
662        let mut vec = vec.into_iter();
663        while let Some(v) = vec.next() {
664            match self.insert(v) {
665                Ok(_) => {
666                }
667                Err(err) => {
668                    match err {
669                        InsertFieldCollexError::OutOfSpan(e) => {
670                            out_of_span.push(e);
671                            out_of_span.extend(vec);
672                            break;
673                        }
674                        InsertFieldCollexError::AlreadyExist(e) => {
675                            already_exist.push(e);
676                        }
677                    }
678                }
679            }
680        }
681        TryExtendResult {
682            out_of_span, already_exist
683        }
684    }
685    
686    pub(crate) fn insert_in_ib(&mut self, idx: usize, elem: E) -> (bool, InsertResult<E>) {
687        use InsertFieldCollexError::*;
688        let items = &mut self.items;
689        
690        let mut need_fill = false;
691        // 插入处
692            match &items[idx] {
693                RawField::Thing((_,t)) => {
694                    match t {
695                        Field::Elem(e) => {
696                            if e.collex_eq(&elem){
697                                return (false,Err(AlreadyExist(elem)));
698                            }
699                            let span = Span::Finite({
700                                let start = *self.span.start() + self.unit * V::from_usize(idx);
701                                start..start + self.unit
702                            });
703                            let mut unit = self.unit/V::from_usize(Self::SUB_FACTOR);
704                            if unit.is_zero() {
705                                unit = V::min_positive();
706                            }
707                            let collex =
708                                FieldCollex::with_capacity(
709                                    span,
710                                    unit,
711                                    2
712                                ).unwrap_or_else(|err|
713                                    panic!("Called `FieldCollex::with_capacity` in `FieldCollex::insert_in_ib` to make a new sub FieldSet, but get a error {err}")
714                                );
715                            let old =
716                                match mem::replace(&mut items[idx], RawField::Thing((idx ,Field::Collex(collex)))).unwrap() {
717                                    Field::Elem(e) => e,
718                                    Field::Collex(_) => unreachable!(),
719                                };
720                            let collex =
721                                match items[idx]
722                                    .as_thing_mut().1 {
723                                    Field::Elem(_) => unreachable!(),
724                                    Field::Collex(collex) => collex,
725                                };
726                            // 此处不用传递,因为二者都必然插入成功:属于span且不相等
727                            if let Err(_) = collex.insert(old){
728                                panic!("Called `FieldCollex::insert` in `FieldCollex::insert_in_ib` but get an unexpected error");
729                            }
730                            if let Err(_) = collex.insert(elem) {
731                                panic!("Called `FieldCollex::insert` in `FieldCollex::insert_in_ib` but get an unexpected error");
732                            }
733                        }
734                        Field::Collex(_) => {
735                            match &mut items[idx] {
736                                RawField::Thing((_,t)) => {
737                                    match t {
738                                        Field::Collex(collex) => {
739                                            let ans = collex.insert(elem);
740                                            match &ans {
741                                                Ok(_) => {}
742                                                Err(_) => {
743                                                    return (false,ans)
744                                                }
745                                            }
746                                        }
747                                        _ => unreachable!()
748                                    }
749                                }
750                                _ => unreachable!()
751                            }
752                        }
753                    }
754                }
755                _ => {
756                    need_fill = true;
757                    let _ = mem::replace(
758                        &mut items[idx],
759                        RawField::Thing((idx,Field::Elem(elem)))
760                    );
761                }
762            }
763        (need_fill,Ok(()))
764    }
765    
766    pub(crate) fn insert_in_ob(&mut self, idx: usize, elem: E) -> InsertResult<E> {
767        let items = &mut self.items;
768        let len = items.len();
769        
770        // 修改未越界部分
771        let prev =
772            if len != 0{
773                match &items[len - 1]{
774                    RawField::Thing(t) => {
775                        debug_assert_eq!(t.0, len-1);
776                        RawField::Among(t.0,idx)
777                    }
778                    _ => {
779                        // 计算前导填充物与填充端点
780                        let (first_idx,prev) = match items[len - 1] {
781                            RawField::Prev(prev) | RawField::Among(prev, _) => (prev+1, RawField::Among(prev, idx)),
782                            RawField::Void => (0,RawField::Next(idx)),
783                            RawField::Next(_) | RawField::Thing(_) => unreachable!()
784                        };
785                        
786                        items[first_idx..len].fill_with(||prev.unchecked_clone());
787                        prev
788                    }
789                }
790            } else {
791                RawField::Next(idx)
792            }
793            ;
794        
795        // 补充越界部分
796        // reserve expand push
797        let need_cap  = idx + 1 - len;
798        items.reserve(need_cap);
799        items.resize_with(idx, || prev.unchecked_clone());
800        items.push(RawField::Thing((idx, Field::Elem(elem))));
801        Ok(())
802    }
803    
804    /// 插入值
805    ///
806    pub fn insert(&mut self, elem: E) -> InsertResult<E> {
807        use InsertFieldCollexError::*;
808        let span = self.span();
809        if !span.contains(elem.collexate_ref()) { return Err(OutOfSpan(elem)) }
810        
811        let idx = self.idx_of(elem.collexate_ref());
812        // 目标索引越界 -> 根据当前最后一个非空块计算前导 -> reserve expand push
813        // 目标索引不越界 -> 填充
814        let len = self.len();
815        // 未越界(这里同时杜绝了len==0的情况)
816        if idx < len {
817            let (need_fill,ans) = self.insert_in_ib(idx, elem);
818            if need_fill {
819                let items = &mut self.items;
820                // 当前为Thing时,并不需要修改其他块,因为他们存储的索引正常指向当前位置,不需要修改
821                // 非第一且前一个非Thing
822                if idx != 0 && !matches!(items[idx-1], RawField::Thing(_)) {
823                    // 计算前导填充物与填充端点
824                    let (first_idx, prev) = match items[idx - 1] {
825                        RawField::Prev(prev) | RawField::Among(prev, _) => (prev + 1, RawField::Among(prev, idx)),
826                        RawField::Next(_) | RawField::Void => (0, RawField::Next(idx)),
827                        RawField::Thing(_) => unreachable!()
828                    };
829                    
830                    items[first_idx..idx].fill_with(||prev.unchecked_clone());
831                }
832                // 非最后且后一个非Thing
833                if idx != len - 1 && !matches!(items[idx+1], RawField::Thing(_)) {
834                    // 计算前导填充物与填充端点
835                    let (last_idx, next) = match items[idx + 1] {
836                        RawField::Next(next) | RawField::Among(_, next) => (next, RawField::Among(idx, next)),
837                        RawField::Prev(_) | RawField::Void => (len, RawField::Prev(idx)),
838                        RawField::Thing(_) => unreachable!()
839                    };
840                    
841                    items[idx+1..last_idx].fill_with(||next.unchecked_clone());
842                }
843            }
844            ans
845        } else { // 越界
846            self.insert_in_ob(idx, elem)
847        }
848    }
849    
850    /// 返回(是否置空当前块,删除的块)
851    pub(crate) fn remove_in(this: &mut Self, idx: usize ) -> (bool, RemoveResult<CollexField<E,V>>) {
852        // 删除的逻辑
853        let len = this.items.len();
854        // 根据上一个元素与下一个元素,生成填充元素
855        let next =
856            if idx == len-1 {
857                None
858            } else {
859                match &this.items[idx + 1] {
860                    RawField::Thing(thing) => Some(thing.0),
861                    RawField::Prev(_)
862                    | RawField::Void => None,
863                    RawField::Among(_, next)
864                    | RawField::Next(next) => Some(*next),
865                }
866            };
867        
868        let prev =
869            if idx == 0 {
870                None
871            } else {
872                match &this.items[idx - 1] {
873                    RawField::Thing(thing) => Some(thing.0),
874                    RawField::Next(_)
875                    | RawField::Void => None,
876                    RawField::Among(prev, _)
877                    | RawField::Prev(prev) => Some(*prev),
878                }
879            };
880        
881        let filler =
882            match next {
883                None =>
884                    match prev {
885                        None => return (true, Ok(mem::replace(&mut this.items[idx], RawField::Void))),
886                        Some(prev) => RawField::Prev(prev),
887                    },
888                Some(next) =>
889                    match prev {
890                        None => RawField::Next(next),
891                        Some(prev) => RawField::Among(prev, next),
892                    },
893            };
894        
895        // 向前更新
896        this.items[0..idx].iter_mut().rev()
897            .take_while(|v| !matches!(v, RawField::Thing(_)) )
898            .for_each(|v| {
899                *v = filler.unchecked_clone();
900            });
901        
902        // 向后更新
903        this.items[idx+1..len].iter_mut()
904            .take_while(|v| !matches!(v, RawField::Thing(_)) )
905            .for_each(|v| {
906                *v = filler.unchecked_clone();
907            });
908        
909        // 更新自己
910        let old = mem::replace(&mut this.items[idx], filler);
911        
912        (false, Ok(old))
913    }
914    
915    /// (需要清空,Result(值))
916    pub(crate) fn remove_rec(this: &mut Self, target: V, idx: usize) -> (bool, RemoveResult<E>) {
917        use RemoveFieldCollexError::*;
918        let items = &mut this.items;
919        (false,
920         if let RawField::Thing(ref mut t) = items[idx] {
921             match &mut t.1 {
922                 Field::Elem(e) => {
923                     if target.ne(e.collexate_ref()) {
924                         Err(NotExist)
925                     } else {
926                         let ans = Self::remove_in(this, idx);
927                         return (ans.0, ans.1.map(|cf| cf.unwrap().into_elem()))
928                     }
929                 }
930                 Field::Collex(collex) => {
931                     // 循环直到到最里面那层。
932                     // 用idx_of是因为不可能出现超出span或空的情况
933                     let sub = Self::remove_rec(collex,target,collex.idx_of(&target));
934                     // 错误时 sub.0 是 false,不用额外判断
935                     return if sub.0 {
936                         (Self::remove_in(this, idx).0, sub.1)
937                     } else {sub}
938                 }
939             }
940         } else {
941             Err(NotExist)
942         }
943        )
944    }
945    
946    /// 删除对应值
947    pub fn remove(&mut self, target: V) -> RemoveResult<E> {
948        let idx = self.get_index(&target)
949            .map_err(Into::<RemoveFieldCollexError>::into)?;
950        let ans = Self::remove_rec(self,target,idx);
951        if ans.0 {
952            self.items.clear()
953        }
954        ans.1
955    }
956    
957    pub fn find_gt(&self, target: V) -> Option<&E> {
958        let last_idx = self.len() - 1;
959        self.find_in(
960            target,
961            |idx| idx+1 ,
962            |f| f.thing_or_next(),
963            |f,v| f.last().collexate_ref().gt(v),
964            move |idx| idx == last_idx,
965        )
966    }
967    
968    
969    pub fn find_ge(&self, target: V) -> Option<&E> {
970        let last_idx = self.len() - 1;
971        self.find_in(
972            target,
973            |idx| idx+1 ,
974            |f| f.thing_or_next(),
975            |f,v| f.last().collexate_ref().ge(v),
976            move |idx| idx == last_idx,
977        )
978    }
979    
980    pub fn find_lt(&self, target: V) -> Option<&E> {
981        self.find_in(
982            target,
983            |idx| idx-1 ,
984            |f| f.thing_or_prev(),
985            |f,v| f.first().collexate_ref().lt(v),
986            |idx| idx == 0,
987        )
988    }
989    
990    
991    pub fn find_le(&self, target: V) -> Option<&E> {
992        self.find_in(
993            target,
994            |idx| idx-1 ,
995            |f| f.thing_or_prev(),
996            |f,v| f.first().collexate_ref().le(v),
997            |idx| idx == 0,
998        )
999    }
1000    
1001    /// 找到最近的大于 target 的值
1002    ///
1003    pub(crate) fn find_in(
1004        &self,
1005        target: V,
1006        next: fn(usize) -> usize,
1007        thing_idx: fn(&CollexField<E, V>) -> Option<Result<usize, usize>>,
1008        cmp: fn(&FieldIn<E, V>, &V) -> bool,
1009        is_edge: impl Fn(usize) -> bool,
1010    ) -> Option<&E> {
1011        let t_idx =
1012            if self.span().start().ge(&target) {
1013                0
1014            } else if self.span().end().map(|v|v.le(&target)).unwrap_or(false) {
1015                self.len()-1
1016            } else {
1017                self.get_index(&target).ok()?
1018            };
1019        // 上面get_index内已经判空。
1020        // 结果落在t位 -> t位的最大值(大于)t -> t位已经足够,进入t位
1021        //           -> t位的最大值不(大于)t -> t+1位必然超过t位,进入下一位
1022        // 结果落在非t位 -> 必然超过t位,进入此位
1023        let f_idx = match thing_idx(&self.items[t_idx])? {
1024            Ok(idx) => {
1025                if cmp(&self.items[idx].as_thing().1, &target) {
1026                    idx
1027                } else {
1028                    if is_edge(idx) {
1029                        return None
1030                    } else {
1031                        next(idx)
1032                    }
1033                }
1034            }
1035            Err(idx) => {
1036                idx
1037            }
1038        };
1039        
1040        // 必然是thing
1041        match self.items[f_idx].as_thing().1 {
1042            Field::Elem(e) => {Some(e)}
1043            Field::Collex(collex) => {
1044                collex.find_in(
1045                    target,
1046                    next,
1047                    thing_idx,
1048                    cmp,
1049                    is_edge
1050                )}
1051        }
1052    }
1053    
1054    /// 找到最近的
1055    ///
1056    /// 两边距离相等时返回更小的
1057    pub fn find_closest(&self, target: V) -> Option<&E> {
1058        use RawField::*;
1059        use Field::*;
1060        
1061        let t_idx =
1062            if self.span().start().ge(&target) {
1063                0
1064            } else if self.span().end().map(|v|v.le(&target)).unwrap_or(false) {
1065                self.len()-1
1066            } else {
1067                self.get_index(&target).ok()?
1068            };
1069        // 上面get_index内已经判空。
1070        // t位是thing -> t位属于t位 -> 是Collex则进入
1071        //                        -> 是Elem返回其
1072        //           -> t大于最大 -> t+1最小值与t最大值比较
1073        //           -> t小于最小 -> t-1最大值与t最小值比较
1074        // t位不是Thing -> 下一个最小值与上一个最大值比较
1075        
1076        match &self.items[t_idx] {
1077            Thing(field) => {
1078                let first = field.1.first();
1079                if target.ge(first.collexate_ref()){
1080                    let last = field.1.last();
1081                    if target.le(last.collexate_ref()) {
1082                        match &field.1 {
1083                            Collex(c) => {
1084                                c.find_closest(target)
1085                            }
1086                            Elem(e) => Some(&e),
1087                        }
1088                    } else { // 大于最大
1089                        Some(
1090                            if t_idx < self.len() {
1091                                self.items.get(t_idx + 1)
1092                                    .map(|v|
1093                                        self.thing_dist_cmp_get(target, last,
1094                                                                v.as_thing().1.first()
1095                                        )
1096                                    )
1097                                    .unwrap_or(last)
1098                            } else{
1099                                last
1100                            }
1101                        )
1102                    }
1103                } else { // 小于最小
1104                    Some(
1105                        if t_idx != 0 {
1106                            self.items.get(t_idx-1)
1107                                .map(|v|
1108                                    self.thing_dist_cmp_get(target,
1109                                                            v.as_thing().1.last(),
1110                                                            first
1111                                    )
1112                                )
1113                                .unwrap_or(first)
1114                        } else {
1115                            first
1116                        }
1117                    )
1118                }
1119            } 
1120            Next(ans) => Some(&self.items[*ans].as_thing().1.first()),
1121            Prev(ans) => Some(&self.items[*ans].as_thing().1.last()),
1122            Among(prev,next) => {
1123                let prev = self.items[*prev].as_thing().1.last();
1124                let next = self.items[*next].as_thing().1.first();
1125                Some(self.thing_dist_cmp_get(target, prev, next))
1126            }
1127            Void => None,
1128        }
1129    }
1130    
1131    pub(crate) fn thing_dist_cmp_get<'a>(&'a self, target:V, prev: &'a E, next: &'a E) -> &'a E{
1132        use std::cmp::Ordering::*;
1133        match dist_cmp(target, prev.collexate(), next.collexate()){
1134            Less => {prev}
1135            // 不可能存储value相同的元素
1136            Equal => {prev}
1137            Greater => {next}
1138        }
1139    }
1140    
1141    /// 判断本容器是否为空
1142    ///
1143    /// 为空不意味着内存占用为0。
1144    pub fn is_empty(&self) -> bool {
1145        self.items.is_empty() || matches!(self.items[0], RawField::Void)
1146    }
1147    
1148    /// 计算指定值对应的块索引,但是带通用前置检查
1149    ///
1150    /// 获取值对应的索引。
1151    pub(crate) fn get_index(
1152        &self,
1153        target: &V,
1154    ) -> GetIndexResult<usize> {
1155        use GetIndexFieldCollexError::*;
1156        if self.is_empty() { return Err(Empty) }
1157        let span = &self.span;
1158        if !span.contains(&target) { return Err(OutOfSpan); }
1159        // is_empty 已检查len>0
1160        Ok(self.idx_of(target).min(self.len() - 1))
1161    }
1162    
1163    pub fn get(&self, value: V) -> Option<&E> {
1164        let idx = self.idx_of(&value);
1165        if self.contains_idx(idx) {
1166            match &self.items[idx] {
1167                RawField::Thing((_, k)) =>
1168                    match k {
1169                        Field::Elem(e) => {
1170                            if value.eq(e.collexate_ref()) {
1171                                Some(e)
1172                            } else {
1173                                None
1174                            }
1175                        }
1176                        Field::Collex(collex) => { collex.get(value) }
1177                    }
1178                _ => None
1179            }
1180        } else { None }
1181    }
1182    
1183    /// # Panics
1184    /// 找不到panic
1185    pub fn unchecked_get(&self, value: V) -> &E {
1186        let idx = self.idx_of(&value);
1187        match &self.items[idx] {
1188            RawField::Thing((_, k)) =>
1189                match k {
1190                    Field::Elem(e) => {
1191                        if value.eq(e.collexate_ref()) {
1192                            e
1193                        } else {
1194                            panic!("Called `FieldCollex::unchecked_get_mut()` on a value is not eq to where it points an field's value")
1195                        }
1196                    }
1197                    Field::Collex(collex) => { collex.unchecked_get(value) }
1198                }
1199            _ => panic!("Called `FieldCollex::unchecked_get()` on a value points an empty field")
1200        }
1201    }
1202    
1203    
1204    pub(crate) fn get_mut(&mut self, value: V) -> Option<&mut E> {
1205        let idx = self.idx_of(&value);
1206        if self.contains_idx(idx) {
1207            match &mut self.items[idx] {
1208                RawField::Thing((_, k)) =>
1209                    match k {
1210                        Field::Elem(e) => {
1211                            if value.eq(e.collexate_ref()) {
1212                                Some(e)
1213                            } else {
1214                                None
1215                            }
1216                        }
1217                        Field::Collex(collex) => { collex.get_mut(value) }
1218                    }
1219                _ => None
1220            }
1221        } else { None }
1222    }
1223    
1224    pub(crate) fn unchecked_get_mut(&mut self, value: V) -> &mut E {
1225        let idx = self.idx_of(&value);
1226        match &mut self.items[idx] {
1227            RawField::Thing((_, k)) =>
1228                match k {
1229                    Field::Elem(e) => {
1230                        if value.eq(e.collexate_ref()) {
1231                            e
1232                        } else {
1233                            panic!("Called `FieldCollex::unchecked_get_mut()` on a value is not eq to where it points an field's value")
1234                        }
1235                    }
1236                    Field::Collex(collex) => { collex.unchecked_get_mut(value) }
1237                }
1238            _ => panic!("Called `FieldCollex::unchecked_get_mut()` on a value points an empty field")
1239        }
1240    }
1241    
1242    /// 闭包结束后,会根据Value是否发生变化来决定是否更新其在Collex中的位置
1243    ///
1244    /// 若更新后的值(仅指collexate值)无法容纳于本Collex,将报错并重置值。
1245    pub fn try_modify<F,R>(&mut self, value: V, op: F) -> ModifyResult<R,R>
1246    where
1247        F: Fn(&mut E) -> R
1248    {
1249        use ModifyFieldCollexError::*;
1250        
1251        let elem = self.get_mut(value).ok_or(CannotFind)?;
1252        let old_v = elem.collexate();
1253        let result = op(elem);
1254        if old_v.eq(elem.collexate_ref()) {
1255            Ok(result)
1256        } else {
1257            // TODO: 优化逻辑
1258            let new_v = elem.collexate();
1259            *elem.collexate_mut() = old_v;
1260            let mut new_e = self.remove(old_v).unwrap();
1261            *new_e.collexate_mut() = new_v;
1262            match self.insert(new_e) {
1263                Ok(()) => Ok(result),
1264                Err(err) => Err(InsertError(err.map(|mut e| {
1265                    *e.collexate_mut() = old_v;
1266                    // 刚删除一模一样的东西,理应可以重新插入
1267                    if let Err(_) = self.insert(e) {
1268                        panic!("Called `FieldCollex::insert` in `FieldCollex::try_modify` but get an **unexpected** error");
1269                    }
1270                    result
1271                }))),
1272            }
1273        }
1274    }
1275    
1276    /// 闭包结束后,会根据Value是否发生变化来决定是否更新其在Collex中的位置
1277    ///
1278    /// 若更新后的值(仅指collexate值)无法容纳于本Collex,将直接通过错误类型的变体返还
1279    pub fn modify<F,R>(&mut self, value: V, op: F) -> ModifyResult<R,(R,E)>
1280    where
1281        F: Fn(&mut E) -> R
1282    {
1283        use ModifyFieldCollexError::*;
1284        
1285        let elem = self.get_mut(value).ok_or(CannotFind)?;
1286        let old_v = elem.collexate();
1287        let result = op(elem);
1288        if old_v.eq(elem.collexate_ref()) {
1289            Ok(result)
1290        } else {
1291            // TODO: 优化逻辑
1292            let new_v = elem.collexate();
1293            *elem.collexate_mut() = old_v;
1294            let mut new_e = self.remove(old_v).unwrap();
1295            *new_e.collexate_mut() = new_v;
1296            match self.insert(new_e) {
1297                Ok(()) => Ok(result),
1298                Err(err) => Err(InsertError(err.map(|e| (result,e)))),
1299            }
1300        }
1301    }
1302    
1303    /// 闭包结束后,会根据Value是否发生变化来决定是否更新其在Collex中的位置
1304    ///
1305    /// # Panics
1306    /// 若无法找到对应的元素,panic
1307    ///
1308    /// 若更新后的值(仅指collexate值)无法容纳于本Collex,将直接Panic
1309    pub fn unchecked_modify<F,R>(&mut self, value: V, op: F) -> R
1310    where
1311        F: Fn(&mut E) -> R
1312    {
1313        let elem = self.unchecked_get_mut(value);
1314        let old_v = elem.collexate();
1315        let result = op(elem);
1316        if old_v.eq(elem.collexate_ref()) {
1317            // do nothing
1318        } else {
1319            // TODO: 优化逻辑
1320            let new_v = elem.collexate();
1321            *elem.collexate_mut() = old_v;
1322            let mut new_e = self.remove(old_v).unwrap();
1323            *new_e.collexate_mut() = new_v;
1324            if let Err(_) = self.insert(new_e) {
1325                panic!("Called `FieldCollex::insert` in `FieldCollex::unchecked_modify` but get an error");
1326            }
1327        }
1328        result
1329    }
1330    
1331}
1332
1333#[cfg(test)]
1334mod tests {
1335    use super::*;
1336    use span_core::Span;
1337    
1338    // ===================== 测试用元素类型(实现Collexetable<u32>) =====================
1339    #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
1340    struct TestElem(u32);
1341    
1342    impl Collexetable<u32> for TestElem {
1343        fn collexate(&self) -> u32 {
1344            self.0
1345        }
1346        
1347        fn collexate_ref(&self) -> &u32 {
1348            &self.0
1349        }
1350        
1351        fn collexate_mut(&mut self) -> &mut u32 {
1352            &mut self.0
1353        }
1354    }
1355    
1356    // ===================== Pub方法测试用例 =====================
1357    #[test]
1358    fn test_basic_construction() {
1359        // 测试:new / with_capacity / span / unit / size / len / capacity / is_empty
1360        let finite_span = Span::new_finite(0u32, 100u32);
1361        let unit = 10u32;
1362        
1363        // 1. new方法(正常场景)
1364        let collex = FieldCollex::<TestElem, u32>::new(finite_span.clone(), unit).unwrap();
1365        assert_eq!(collex.span(), &finite_span);
1366        assert_eq!(*collex.unit(), unit);
1367        assert_eq!(collex.size(), Some(10)); // 100/10=10块
1368        assert_eq!(collex.len(), 0);
1369        assert_eq!(collex.capacity(), 0);
1370        assert!(collex.is_empty());
1371        
1372        // 2. new方法(错误场景:unit=0)
1373        let err_unit_zero = FieldCollex::<TestElem, u32>::new(finite_span.clone(), 0u32).unwrap_err();
1374        assert!(matches!(err_unit_zero, NewFieldCollexError::NonPositiveUnit(_, 0)));
1375        
1376        // 3. new方法(错误场景:空span)
1377        let empty_span = Span::new_finite(5u32, 3u32); // start >= end 为空
1378        let err_empty_span = FieldCollex::<TestElem, u32>::new(empty_span, unit).unwrap_err();
1379        assert!(matches!(err_empty_span, NewFieldCollexError::EmptySpan(_, _)));
1380        
1381        // 4. with_capacity方法(正常场景)
1382        let collex_with_cap = FieldCollex::<TestElem, u32>::with_capacity(finite_span, unit, 5).unwrap();
1383        assert_eq!(collex_with_cap.capacity(), 5);
1384        assert!(collex_with_cap.is_empty());
1385        
1386        // 5. with_capacity方法(错误场景:capacity超限)
1387        let err_cap_out = FieldCollex::<TestElem, u32>::with_capacity(Span::new_finite(0u32, 100u32), 10u32, 11).unwrap_err();
1388        assert!(matches!(err_cap_out, WithCapacityFieldCollexError::OutOfSize(_, _)));
1389    }
1390    
1391    #[test]
1392    fn test_insert_contains() {
1393        // 测试:insert / contains / contains_value / first / last
1394        let span = Span::new_finite(0u32, 100u32);
1395        let unit = 10u32;
1396        let mut collex = FieldCollex::<TestElem, u32>::new(span, unit).unwrap();
1397        
1398        // 插入元素
1399        let elem1 = TestElem(5);
1400        let elem2 = TestElem(15);
1401        assert!(collex.insert(elem1).is_ok());
1402        assert!(collex.insert(elem2).is_ok());
1403        
1404        // 验证包含性
1405        assert!(collex.contains(&elem1));
1406        assert!(collex.contains_value(5u32));
1407        assert!(collex.contains(&elem2));
1408        assert!(!collex.contains(&TestElem(25)));
1409        assert!(!collex.contains_value(25u32));
1410        
1411        // 验证首尾元素
1412        assert_eq!(collex.first(), Some(&elem1));
1413        assert_eq!(collex.last(), Some(&elem2));
1414        
1415        // 验证非空
1416        assert!(!collex.is_empty());
1417    }
1418    
1419    #[test]
1420    fn test_remove() {
1421        // 测试:remove
1422        let span = Span::new_finite(0u32, 100u32);
1423        let unit = 10u32;
1424        let mut collex = FieldCollex::<TestElem, u32>::new(span, unit).unwrap();
1425        
1426        // 插入后删除
1427        let elem = TestElem(5);
1428        collex.insert(elem).unwrap();
1429        let removed = collex.remove(5u32).unwrap();
1430        assert_eq!(removed, elem);
1431        
1432        // 验证删除后不包含
1433        assert!(!collex.contains(&elem));
1434        assert!(!collex.contains_value(5u32));
1435        assert!(collex.is_empty());
1436        
1437        // 错误场景:删除不存在的值
1438        let err_remove = collex.remove(10u32).unwrap_err();
1439        assert!(matches!(err_remove, RemoveFieldCollexError::NotExist));
1440    }
1441    
1442    #[test]
1443    fn test_extend_try_extend() {
1444        // 测试:extend / try_extend
1445        let span = Span::new_finite(0u32, 100u32);
1446        let unit = 10u32;
1447        let mut collex = FieldCollex::<TestElem, u32>::new(span, unit).unwrap();
1448        
1449        // 1. extend:批量插入
1450        let elems = vec![TestElem(5), TestElem(15), TestElem(25)];
1451        collex.extend(elems.clone());
1452        assert!(collex.contains(&TestElem(5)));
1453        assert!(collex.contains(&TestElem(15)));
1454        
1455        // 2. try_extend:批量插入并返回结果
1456        let elems2 = vec![TestElem(25), TestElem(35), TestElem(105)]; // 105超出span范围
1457        let result = collex.try_extend(elems2);
1458        // 验证:105超出span,25已存在,35插入成功
1459        assert!(!result.out_of_span.is_empty() && result.out_of_span[0].0 == 105);
1460        assert!(!result.already_exist.is_empty() && result.already_exist[0].0 == 25);
1461        assert!(collex.contains(&TestElem(35)));
1462    }
1463    
1464    #[test]
1465    fn test_find_methods() {
1466        // 测试:find_gt / find_ge / find_lt / find_le
1467        let span = Span::new_finite(0u32, 100u32);
1468        let unit = 10u32;
1469        let mut collex = FieldCollex::<TestElem, u32>::new(span, unit).unwrap();
1470        
1471        // 插入测试元素
1472        let elems = [TestElem(5), TestElem(15), TestElem(25)];
1473        for &e in &elems {
1474            collex.insert(e).unwrap();
1475        }
1476        
1477        // 测试find_gt(大于)
1478        let gt = collex.find_gt(10u32).unwrap();
1479        assert_eq!(*gt, TestElem(15));
1480        
1481        // 测试find_ge(大于等于)
1482        let ge = collex.find_ge(15u32).unwrap();
1483        assert_eq!(*ge, TestElem(15));
1484        
1485        // 测试find_lt(小于)
1486        let lt = collex.find_lt(20u32).unwrap();
1487        assert_eq!(*lt, TestElem(15));
1488        
1489        // 测试find_le(小于等于)
1490        let le = collex.find_le(25u32).unwrap();
1491        assert_eq!(*le, TestElem(25));
1492        
1493        // 错误场景:找不到匹配值
1494        let err_find = collex.find_gt(30u32);
1495        assert!(matches!(err_find, None));
1496    }
1497    
1498    #[test]
1499    fn test_with_elements() {
1500        // 测试:with_elements(批量构造)
1501        let span = Span::new_finite(0u32, 100u32);
1502        // 实际运用场景建议使用5或10(即使目前没这么多元素)要保持尽量不分层!
1503        let unit = 50u32;
1504        let elems = vec![TestElem(5), TestElem(15), TestElem(25), TestElem(105)]; // 105超出span
1505        
1506        // 构造FieldCollex
1507        let collex = FieldCollex::<TestElem, u32>::with_elements(span, unit, elems).unwrap();
1508        // 验证:105被忽略,5/15/25插入成功
1509        assert!(collex.contains(&TestElem(5)));
1510        assert!(collex.contains(&TestElem(15)));
1511        assert!(!collex.contains(&TestElem(105)));
1512        assert_eq!(collex.first(), Some(&TestElem(5)));
1513        assert_eq!(collex.last(), Some(&TestElem(25)));
1514    }
1515    
1516    
1517    #[test]
1518    fn test_find_closest() {
1519        // 测试:find_closest
1520        let span = Span::new_finite(0u32, 100u32);
1521        // 实际运用场景建议使用5或10(即使目前没这么多元素)要保持尽量不分层!
1522        let unit = 50u32;
1523        let elems = vec![TestElem(5), TestElem(15), TestElem(25), TestElem(105)]; // 105超出span
1524        
1525        // 构造FieldCollex
1526        let collex = FieldCollex::<TestElem, u32>::with_elements(span, unit, elems).unwrap();
1527        // 相等直接取
1528        assert_eq!(collex.find_closest(5), Some(&TestElem(5)));
1529        assert_eq!(collex.find_closest(25), Some(&TestElem(25)));
1530        // 俩距相同取更小
1531        assert_eq!(collex.find_closest(10), Some(&TestElem(5)));
1532        assert_eq!(collex.find_closest(20), Some(&TestElem(15)));
1533        // 越界取边界
1534        assert_eq!(collex.find_closest(114514), Some(&TestElem(25)));
1535        // 边界仅1值
1536        assert_eq!(collex.find_closest(0), Some(&TestElem(5)));
1537        // 未分配时取边界
1538        assert_eq!(collex.find_closest(100), Some(&TestElem(25)));
1539    }
1540    
1541    #[test]
1542    fn test_get() {
1543        // 测试:get系列函数
1544        let span = Span::new_finite(0u32, 100u32);
1545        let unit = 10u32;
1546        let elems = vec![TestElem(5), TestElem(15), TestElem(25)];
1547        
1548        // 构造FieldCollex
1549        let collex = FieldCollex::<TestElem, u32>::with_elements(span, unit, elems).unwrap();
1550        assert_eq!(collex.get(5), Some(&TestElem(5)));
1551        assert_eq!(collex.unchecked_get(15), &TestElem(15));
1552        assert_eq!(collex.get(25), Some(&TestElem(25)));
1553        assert_eq!(collex.get(0), None);
1554        assert_eq!(collex.get(10), None);
1555        assert_eq!(collex.get(114514), None);
1556    }
1557    
1558    #[test]
1559    fn test_modify() {
1560        // 测试:modify系列函数
1561        let span = Span::new_finite(0u32, 100u32);
1562        let unit = 10u32;
1563        let elems = vec![TestElem(5),  TestElem(25),  TestElem(35),  TestElem(45)];
1564        
1565        // 构造FieldCollex
1566        let mut collex = FieldCollex::<TestElem, u32>::with_elements(span, unit, elems).unwrap();
1567        
1568        assert_eq!(collex.first(), Some(&TestElem(5)));
1569        
1570        // Value未修改
1571        // ... edit other field (but there we do nothing)
1572        collex.modify(5,|_| ()).unwrap();
1573        assert_eq!(collex.first(), Some(&TestElem(5)));
1574        
1575        // 修改Value但依旧在此位置
1576        collex.modify(5,|v| v.0=1 ).unwrap();
1577        assert_eq!(collex.first(), Some(&TestElem(1)));
1578        
1579        // 修改Value,改变位置
1580        let _ans = collex.modify(1,|v| v.0=15 );
1581        assert_eq!(collex.first(), Some(&TestElem(15)));
1582        
1583        // 修改Value,移到别的后面
1584        collex.modify(15,|v| v.0=26 ).unwrap();
1585        assert_eq!(collex.first(), Some(&TestElem(25)));
1586        
1587        // 改改别的吧
1588        let _ans = collex.modify(45,|v| v.0=0 );
1589        assert_eq!(collex.first(), Some(&TestElem(0)));
1590        
1591        // modify会在值非法时弹出元素(当然是你修改后的)
1592        let ans = collex.modify(0,|v| v.0=123 );
1593        assert!(matches!(ans, Err(ModifyFieldCollexError::InsertError(InsertFieldCollexError::OutOfSpan(((),TestElem(123)))))));
1594        assert_eq!(collex.first(), Some(&TestElem(25)));
1595        
1596        // try_modify会在值非法时还原值
1597        let ans = collex.try_modify(25,|v| v.0=123 );
1598        assert!(matches!(ans, Err(ModifyFieldCollexError::InsertError(InsertFieldCollexError::OutOfSpan(()) )) ));
1599        assert_eq!(collex.first(), Some(&TestElem(25)));
1600    }
1601}