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
use core::fmt::Debug;

use crate::{BTree, BTreeTrait, FindResult, MoveListener, Query};

#[derive(Debug)]
#[repr(transparent)]
struct OrdTrait<Key, Value> {
    _phantom: core::marker::PhantomData<(Key, Value)>,
}

#[derive(Debug)]
pub struct OrdTreeMap<Key: Clone + Ord + Debug + 'static, Value: Clone + Debug> {
    tree: BTree<OrdTrait<Key, Value>>,
    len: usize,
}

#[derive(Debug)]
pub struct OrdTreeSet<Key: Clone + Ord + Debug + 'static>(OrdTreeMap<Key, ()>);

impl<Key: Clone + Ord + Debug + 'static, Value: Clone + Debug + 'static> OrdTreeMap<Key, Value> {
    #[inline(always)]
    pub fn new() -> Self {
        Self {
            tree: BTree::new(),
            len: 0,
        }
    }

    #[inline(always)]
    pub fn insert(&mut self, key: Key, value: Value) {
        let result = self.tree.query::<OrdTrait<Key, Value>>(&key);
        if !result.found {
            self.len += 1;
            self.tree.insert_by_query_result(result, (key, value));
        } else {
            let leaf = self.tree.nodes.get_mut(result.leaf).unwrap();
            leaf.elements[result.elem_index].1 = value;
        }
    }

    #[inline(always)]
    pub fn delete(&mut self, value: &Key) -> Option<(Key, Value)> {
        match self.tree.delete::<OrdTrait<Key, Value>>(value) {
            Some(v) => {
                self.len -= 1;
                Some(v)
            }
            None => None,
        }
    }

    pub fn set_listener(&mut self, listener: Option<MoveListener<(Key, Value)>>) {
        self.tree.set_listener(listener);
    }

    #[inline(always)]
    pub fn iter(&self) -> impl Iterator<Item = &(Key, Value)> {
        self.tree.iter()
    }

    #[inline(always)]
    pub fn iter_key(&self) -> impl Iterator<Item = &Key> {
        self.tree.iter().map(|x| &x.0)
    }

    #[inline(always)]
    pub fn len(&self) -> usize {
        self.len
    }

    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    #[allow(unused)]
    pub(crate) fn check(&self) {
        self.tree.check()
    }
}

impl<Key: Clone + Ord + Debug + 'static> OrdTreeSet<Key> {
    #[inline(always)]
    pub fn new() -> Self {
        Self(OrdTreeMap::new())
    }

    #[inline(always)]
    pub fn insert(&mut self, key: Key) {
        self.0.insert(key, ());
    }

    #[inline(always)]
    pub fn delete(&mut self, key: &Key) -> bool {
        self.0.delete(key).is_some()
    }

    #[inline(always)]
    pub fn iter(&self) -> impl Iterator<Item = &Key> {
        self.0.iter_key()
    }

    pub fn len(&self) -> usize {
        self.0.len
    }

    pub fn is_empty(&self) -> bool {
        self.0.len == 0
    }

    fn check(&self) {
        self.0.check()
    }
}

impl<Key: Clone + Ord + Debug + 'static> Default for OrdTreeSet<Key> {
    #[inline(always)]
    fn default() -> Self {
        Self::new()
    }
}

impl<Key: Clone + Ord + Debug + 'static, Value: Clone + Debug + 'static> Default
    for OrdTreeMap<Key, Value>
{
    #[inline(always)]
    fn default() -> Self {
        Self::new()
    }
}

impl<Key, Value> Default for OrdTrait<Key, Value> {
    #[inline(always)]
    fn default() -> Self {
        Self {
            _phantom: Default::default(),
        }
    }
}

impl<Key: Clone + Ord + Debug + 'static, Value: Clone + Debug> BTreeTrait for OrdTrait<Key, Value> {
    type Elem = (Key, Value);
    type Cache = Option<(Key, Key)>;

    const MAX_LEN: usize = 32;

    #[inline(always)]
    fn calc_cache_internal(
        cache: &mut Self::Cache,
        caches: &[crate::Child<Self>],
        _: Option<()>,
    ) -> Option<()> {
        *cache = Some((
            caches[0].cache.as_ref().unwrap().0.clone(),
            caches[caches.len() - 1].cache.as_ref().unwrap().1.clone(),
        ));
        None
    }

    #[inline(always)]
    fn calc_cache_leaf(cache: &mut Self::Cache, elements: &[Self::Elem], diff: Option<()>) {
        if elements.is_empty() {
            return;
        }

        *cache = Some((
            elements[0].0.clone(),
            elements[elements.len() - 1].0.clone(),
        ))
    }

    type CacheDiff = ();

    #[inline(always)]
    fn merge_cache_diff(_: &mut Self::CacheDiff, _: &Self::CacheDiff) {}
}

impl<Key: Ord + Clone + Debug + 'static, Value: Clone + Debug + 'static> Query<OrdTrait<Key, Value>>
    for OrdTrait<Key, Value>
{
    type QueryArg = Key;

    fn find_node(
        &mut self,
        target: &Self::QueryArg,
        child_caches: &[crate::Child<OrdTrait<Key, Value>>],
    ) -> crate::FindResult {
        match child_caches.binary_search_by(|x| {
            let (min, max) = x.cache.as_ref().unwrap();
            if target < min {
                core::cmp::Ordering::Greater
            } else if target > max {
                core::cmp::Ordering::Less
            } else {
                core::cmp::Ordering::Equal
            }
        }) {
            Ok(i) => FindResult::new_found(i, 0),
            Err(i) => FindResult::new_missing(i, 0),
        }
    }

    fn find_element(&mut self, target: &Key, elements: &[(Key, Value)]) -> crate::FindResult {
        match elements.binary_search_by_key(&target, |x| &x.0) {
            Ok(i) => FindResult::new_found(i, 0),
            Err(i) => FindResult::new_missing(i, 0),
        }
    }

    #[inline(always)]
    fn init(_target: &Self::QueryArg) -> Self {
        Self::default()
    }
}

#[cfg(test)]
mod test {
    use std::cmp::Ordering;

    use rand::{Rng, SeedableRng};

    use crate::HeapVec;

    use super::*;

    #[test]
    fn test() {
        let mut tree: OrdTreeSet<u64> = OrdTreeSet::new();
        let mut rng = rand::rngs::StdRng::seed_from_u64(123);
        let mut data: HeapVec<u64> = (0..1000).map(|_| rng.gen()).collect();
        for &value in data.iter() {
            tree.insert(value);
        }
        data.sort_unstable();
        assert_eq!(tree.iter().copied().collect::<HeapVec<_>>(), data);
        tree.check();
    }

    #[test]
    fn test_delete() {
        let mut tree: OrdTreeSet<u64> = OrdTreeSet::new();
        tree.insert(12);
        tree.delete(&12);
        assert_eq!(tree.len(), 0);
    }

    #[test]
    fn test_compare_pos() {
        let mut tree: OrdTreeSet<u64> = OrdTreeSet::new();
        for i in 0..100 {
            tree.insert(i);
        }
        for i in 0..99 {
            let a = tree.0.tree.query::<OrdTrait<u64, ()>>(&i);
            assert_eq!(tree.0.tree.compare_pos(a, a), Ordering::Equal);
            for j in i + 1..100 {
                let b = tree.0.tree.query::<OrdTrait<u64, ()>>(&j);
                assert_eq!(tree.0.tree.compare_pos(a, b), Ordering::Less);
                assert_eq!(tree.0.tree.compare_pos(b, a), Ordering::Greater);
            }
        }
    }

    mod move_event_test {
        use std::{
            cell::RefCell,
            collections::HashMap,
            rc::Rc,
            sync::{Arc, Mutex},
        };

        use thunderdome::Index as ArenaIndex;

        use super::*;
        #[test]
        fn test() {
            let mut tree: OrdTreeMap<u64, usize> = OrdTreeMap::new();
            let record: Arc<Mutex<HashMap<u64, ArenaIndex>>> = Default::default();
            let mut rng = rand::rngs::StdRng::seed_from_u64(123);
            let mut data: HeapVec<u64> = (0..1000).map(|_| rng.gen()).collect();
            let record_clone = record.clone();
            tree.set_listener(Some(Box::new(move |event| {
                if let Some(leaf) = event.target_leaf {
                    let mut record = record.lock().unwrap();
                    record.insert(event.elem.0, leaf);
                } else {
                    let mut record = record.lock().unwrap();
                    record.remove(&event.elem.0);
                }
            })));
            for &value in data.iter() {
                tree.insert(value, 0);
            }
            {
                let record = record_clone.lock().unwrap();
                assert_eq!(record.len(), 1000);
                for &value in data.iter() {
                    let index = record.get(&value).unwrap();
                    let node = tree.tree.get_node(*index);
                    assert!(node.elements.iter().any(|x| x.0 == value));
                }
            }
            for value in data.drain(0..100) {
                tree.delete(&value);
            }
            {
                let record = record_clone.lock().unwrap();
                assert_eq!(record.len(), 900);
                assert_eq!(tree.len, 900);
                for &value in data.iter() {
                    let index = record.get(&value).unwrap();
                    let node = tree.tree.get_node(*index);
                    assert!(node.elements.iter().any(|x| x.0 == value));
                }
            }
            for value in data.drain(0..800) {
                tree.delete(&value);
            }
            {
                let record = record_clone.lock().unwrap();
                assert_eq!(record.len(), 100);
                assert_eq!(tree.len, 100);
                for &value in data.iter() {
                    let index = record.get(&value).unwrap();
                    let node = tree.tree.get_node(*index);
                    assert!(node.elements.iter().any(|x| x.0 == value));
                }
            }
            tree.tree.check();
            for i in (0..100).rev() {
                tree.delete(&data.pop().unwrap());
                {
                    let record = record_clone.lock().unwrap();
                    assert_eq!(record.len(), i);
                    assert_eq!(tree.len, i);
                    for &value in data.iter() {
                        let index = record.get(&value).unwrap();
                        let node = tree.tree.get_node(*index);
                        assert!(node.elements.iter().any(|x| x.0 == value));
                    }
                }
            }
        }
    }
}