Struct NodeRef

Source
pub struct NodeRef<B, S>
where S: SplaySpec,
{ /* private fields */ }

Implementations§

Source§

impl<S> NodeRef<Owned, S>
where S: SplaySpec,

Source

pub fn new(node: NonNull<Node<S::T>>) -> Self

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 160)
156    pub unsafe fn from_data<A>(data: S::T, allocator: &mut A) -> Self
157    where
158        A: Allocator<Node<S::T>>,
159    {
160        Self::new(allocator.allocate(Node::new(data)))
161    }
162    pub fn borrow_mut(&mut self) -> NodeRef<marker::Mut<'_>, S> {
163        unsafe { NodeRef::new_unchecked(self.node) }
164    }
165    pub fn borrow_datamut(&mut self) -> NodeRef<marker::DataMut<'_>, S> {
166        unsafe { NodeRef::new_unchecked(self.node) }
167    }
168    pub fn into_dying(self) -> NodeRef<marker::Dying, S> {
169        unsafe { NodeRef::new_unchecked(self.node) }
170    }
171}
172
173impl<'a, S> NodeRef<marker::Immut<'a>, S>
174where
175    S: SplaySpec,
176    S::T: 'a,
177{
178    pub fn data(&self) -> &'a S::T {
179        unsafe { &(*self.as_ptr()).data }
180    }
181    pub fn left(&self) -> Option<Self> {
182        unsafe {
183            (*self.as_ptr())
184                .left
185                .map(|node| NodeRef::new_unchecked(node))
186        }
187    }
188    pub fn right(&self) -> Option<Self> {
189        unsafe {
190            (*self.as_ptr())
191                .right
192                .map(|node| NodeRef::new_unchecked(node))
193        }
194    }
195    pub fn traverse<F>(self, f: &mut F)
196    where
197        S::T: 'a,
198        F: FnMut(Self),
199    {
200        if let Some(left) = self.clone().left() {
201            left.traverse(f);
202        }
203        f(self);
204        if let Some(right) = self.clone().right() {
205            right.traverse(f);
206        }
207    }
208}
209
210impl<'a, S> NodeRef<marker::DataMut<'a>, S>
211where
212    S: SplaySpec,
213    S::T: 'a,
214{
215    pub fn data(&self) -> &'a S::T {
216        unsafe { &(*self.as_ptr()).data }
217    }
218    pub fn data_mut(&self) -> &'a mut S::T {
219        unsafe { &mut (*self.as_ptr()).data }
220    }
221    pub fn left(&self) -> Option<Self> {
222        unsafe {
223            (*self.as_ptr())
224                .left
225                .map(|node| NodeRef::new_unchecked(node))
226        }
227    }
228    pub fn right(&self) -> Option<Self> {
229        unsafe {
230            (*self.as_ptr())
231                .right
232                .map(|node| NodeRef::new_unchecked(node))
233        }
234    }
235    pub fn reverse(&self) {
236        unsafe {
237            let node = &mut (*self.as_ptr());
238            swap(&mut node.left, &mut node.right);
239        }
240    }
241}
242
243impl<'a, S> NodeRef<marker::Mut<'a>, S>
244where
245    S: SplaySpec,
246    S::T: 'a,
247{
248    pub fn data(self) -> &'a S::T {
249        unsafe { &(*self.as_ptr()).data }
250    }
251    pub fn data_mut(self) -> &'a mut S::T {
252        unsafe { &mut (*self.as_ptr()).data }
253    }
254    pub fn take_left(&mut self) -> Option<NodeRef<marker::Owned, S>> {
255        Some(NodeRef::new(unsafe { (*self.as_ptr()).left.take()? }))
256    }
257    pub fn take_right(&mut self) -> Option<NodeRef<marker::Owned, S>> {
258        Some(NodeRef::new(unsafe { (*self.as_ptr()).right.take()? }))
259    }
260    pub fn set_left(&mut self, node: Option<NodeRef<marker::Owned, S>>) {
261        unsafe { (*self.as_ptr()).left = node.map(|node| node.node) }
262    }
263    pub fn set_right(&mut self, node: Option<NodeRef<marker::Owned, S>>) {
264        unsafe { (*self.as_ptr()).right = node.map(|node| node.node) }
265    }
266}
267
268impl<S> NodeRef<marker::Dying, S>
269where
270    S: SplaySpec,
271{
272    pub unsafe fn into_inner(self) -> NonNull<Node<S::T>> {
273        let node = self.node;
274        unsafe {
275            debug_assert!((*node.as_ptr()).left.is_none());
276            debug_assert!((*node.as_ptr()).right.is_none());
277        }
278        node
279    }
280    pub unsafe fn into_data<A>(self, allocator: &mut A) -> S::T
281    where
282        A: Allocator<Node<S::T>>,
283    {
284        let Node { data, left, right } = allocator.deallocate(self.node);
285        debug_assert!(left.is_none());
286        debug_assert!(right.is_none());
287        data
288    }
289}
290
291impl<S> NodeRef<marker::Owned, S>
292where
293    S: SplaySpec,
294{
295    /// `cmp(key)`: [`Ordering`] between splaying and `key`
296    pub fn splay_by<Seeker>(self, mut seeker: Seeker) -> (Ordering, Self)
297    where
298        Seeker: SplaySeeker<S = S>,
299    {
300        let mut x = self;
301        // let dummy = Node { data: None, left: left_subtree, right: right_subtree };
302        let mut left_subtree: Option<NonNull<Node<S::T>>> = None;
303        let mut right_subtree: Option<NonNull<Node<S::T>>> = None;
304        let mut left_entry = &mut left_subtree;
305        let mut right_entry = &mut right_subtree;
306        let mut stack = vec![];
307
308        macro_rules! add {
309            (@left Some($ptr:ident)) => { add!(@inner Some($ptr.node), left_entry $ptr right); };
310            (@right Some($ptr:ident)) => { add!(@inner Some($ptr.node), right_entry $ptr left); };
311            (@inner $node:expr, $entry:ident $ptr:ident $dir:ident) => {
312                *$entry = $node;
313                if S::has_bottom_up() {
314                    stack.push($ptr.node);
315                }
316                $entry = unsafe { &mut (*$entry.as_mut().unwrap().as_ptr()).$dir };
317            };
318        }
319
320        let root_ord = loop {
321            S::top_down(x.borrow_datamut());
322            match seeker.splay_seek(x.reborrow()) {
323                Ordering::Less => {
324                    if let Some(mut y) = x.borrow_mut().take_left() {
325                        S::top_down(y.borrow_datamut());
326                        match seeker.splay_seek(y.reborrow()) {
327                            Ordering::Less => {
328                                if let Some(mut z) = y.borrow_mut().take_left() {
329                                    S::top_down(z.borrow_datamut());
330                                    x.borrow_mut().set_left(y.borrow_mut().take_right());
331                                    S::bottom_up(x.borrow_datamut());
332                                    y.borrow_mut().set_right(Some(x));
333                                    add!(@right Some(y));
334                                    x = z;
335                                } else {
336                                    add!(@right Some(x));
337                                    x = y;
338                                    break Ordering::Less;
339                                }
340                            }
341                            Ordering::Equal => {
342                                add!(@right Some(x));
343                                x = y;
344                                break Ordering::Equal;
345                            }
346                            Ordering::Greater => {
347                                if let Some(mut z) = y.borrow_mut().take_right() {
348                                    S::top_down(z.borrow_datamut());
349                                    add!(@right Some(x));
350                                    add!(@left Some(y));
351                                    x = z;
352                                } else {
353                                    add!(@right Some(x));
354                                    x = y;
355                                    break Ordering::Greater;
356                                }
357                            }
358                        }
359                    } else {
360                        break Ordering::Less;
361                    }
362                }
363                Ordering::Equal => break Ordering::Equal,
364                Ordering::Greater => {
365                    if let Some(mut y) = x.borrow_mut().take_right() {
366                        S::top_down(y.borrow_datamut());
367                        match seeker.splay_seek(y.reborrow()) {
368                            Ordering::Less => {
369                                if let Some(mut z) = y.borrow_mut().take_left() {
370                                    S::top_down(z.borrow_datamut());
371                                    add!(@left Some(x));
372                                    add!(@right Some(y));
373                                    x = z;
374                                } else {
375                                    add!(@left Some(x));
376                                    x = y;
377                                    break Ordering::Less;
378                                }
379                            }
380                            Ordering::Equal => {
381                                add!(@left Some(x));
382                                x = y;
383                                break Ordering::Equal;
384                            }
385                            Ordering::Greater => {
386                                if let Some(mut z) = y.borrow_mut().take_right() {
387                                    S::top_down(z.borrow_datamut());
388                                    x.borrow_mut().set_right(y.borrow_mut().take_left());
389                                    S::bottom_up(x.borrow_datamut());
390                                    y.borrow_mut().set_left(Some(x));
391                                    add!(@left Some(y));
392                                    x = z;
393                                } else {
394                                    add!(@left Some(x));
395                                    x = y;
396                                    break Ordering::Greater;
397                                }
398                            }
399                        }
400                    } else {
401                        break Ordering::Greater;
402                    }
403                }
404            }
405        };
406        *left_entry = x.borrow_mut().take_left().map(|node| node.node);
407        *right_entry = x.borrow_mut().take_right().map(|node| node.node);
408        unsafe {
409            x.borrow_mut()
410                .set_left(left_subtree.map(|node| NodeRef::new_unchecked(node)));
411            x.borrow_mut()
412                .set_right(right_subtree.map(|node| NodeRef::new_unchecked(node)));
413            if S::has_bottom_up() {
414                while let Some(node) = stack.pop() {
415                    S::bottom_up(NodeRef::new_unchecked(node));
416                }
417            }
418        }
419        S::bottom_up(x.borrow_datamut());
420        (root_ord, x)
421    }
422    pub fn insert_left(mut self, mut node: Self) -> Self {
423        if let Some(left) = self.borrow_mut().take_left() {
424            node.borrow_mut().set_left(Some(left));
425            S::bottom_up(self.borrow_datamut());
426        };
427        node.borrow_mut().set_right(Some(self));
428        S::bottom_up(node.borrow_datamut());
429        node
430    }
431    pub fn insert_right(mut self, mut node: Self) -> Self {
432        if let Some(right) = self.borrow_mut().take_right() {
433            node.borrow_mut().set_right(Some(right));
434            S::bottom_up(self.borrow_datamut());
435        }
436        node.borrow_mut().set_left(Some(self));
437        S::bottom_up(node.borrow_datamut());
438        node
439    }
440    pub fn insert_first(self, mut node: Self) -> Self {
441        node.borrow_mut().set_right(Some(self));
442        S::bottom_up(node.borrow_datamut());
443        node
444    }
445    pub fn insert_last(self, mut node: Self) -> Self {
446        node.borrow_mut().set_left(Some(self));
447        S::bottom_up(node.borrow_datamut());
448        node
449    }
450    pub fn merge(mut self, mut other: Self) -> Self {
451        if other.reborrow().left().is_none() {
452            S::top_down(other.borrow_datamut());
453            other.borrow_mut().set_left(Some(self));
454            S::bottom_up(other.borrow_datamut());
455            other
456        } else {
457            self = self.splay_by(SeekRight::new()).1;
458            self.borrow_mut().set_right(Some(other));
459            S::bottom_up(self.borrow_datamut());
460            self
461        }
462    }
463}
464
465impl<S> Root<S>
466where
467    S: SplaySpec,
468{
469    pub fn new(root: Option<NodeRef<marker::Owned, S>>) -> Self {
470        Self { root }
471    }
472    pub unsafe fn from_single_nodes(nodes: Vec<NodeRef<marker::Owned, S>>) -> Self {
473        unsafe { Self::from_single_nodes_inner(&nodes) }
474    }
475    unsafe fn from_single_nodes_inner(nodes: &[NodeRef<marker::Owned, S>]) -> Self {
476        if nodes.is_empty() {
477            Self::new(None)
478        } else {
479            let m = nodes.len() / 2;
480            let left = unsafe { Self::from_single_nodes_inner(&nodes[..m]) };
481            let right = unsafe { Self::from_single_nodes_inner(&nodes[m + 1..]) };
482            let mut node = NodeRef::new(nodes[m].node);
483            node.borrow_mut().set_left(left.root);
484            node.borrow_mut().set_right(right.root);
485            S::bottom_up(node.borrow_datamut());
486            Self::new(Some(node))
487        }
488    }
Source

pub unsafe fn from_data<A>(data: S::T, allocator: &mut A) -> Self
where A: Allocator<Node<S::T>>,

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/sequence.rs (lines 372-381)
367    pub fn insert(&mut self, index: usize, x: T::Key) {
368        assert!(index <= self.length);
369        self.root.splay_by(SeekBySize::new(index));
370        let agg = T::single_agg(&x);
371        unsafe {
372            let node = NodeRef::from_data(
373                LazyAggElement {
374                    key: x,
375                    agg,
376                    lazy: T::act_unit(),
377                    size: 1,
378                    rev: false,
379                },
380                self.alloc.deref_mut(),
381            );
382            if index == self.length {
383                self.root.insert_right(node);
384            } else {
385                self.root.insert_left(node);
386            }
387        }
388        self.length += 1;
389    }
390    pub fn remove(&mut self, index: usize) -> Option<T::Key> {
391        if index >= self.length {
392            return None;
393        }
394        self.root.splay_by(SeekBySize::new(index));
395        self.length -= 1;
396        let node = self.root.take_root().unwrap().into_dying();
397        unsafe { Some(node.into_data(self.alloc.deref_mut()).key) }
398    }
399    pub fn position_acc<R, F>(&mut self, range: R, f: F) -> Option<usize>
400    where
401        R: RangeBounds<usize>,
402        F: FnMut(&T::Agg) -> bool,
403    {
404        let mut range = self.range(range);
405        let ord = range.root_mut().splay_by(SeekByAccCond::new(f));
406        if !matches!(ord, Some(Ordering::Equal)) {
407            return None;
408        }
409        let front_size = range.front().size();
410        let left_size = range.root().left_size();
411        Some(front_size + left_size)
412    }
413    pub fn rposition_acc<R, F>(&mut self, range: R, f: F) -> Option<usize>
414    where
415        R: RangeBounds<usize>,
416        F: FnMut(&T::Agg) -> bool,
417    {
418        let mut range = self.range(range);
419        let ord = range.root_mut().splay_by(SeekByRaccCond::new(f));
420        if !matches!(ord, Some(Ordering::Equal)) {
421            return None;
422        }
423        let front_size = range.front().size();
424        let left_size = range.root().left_size();
425        Some(front_size + left_size)
426    }
427    pub fn rotate_left(&mut self, mid: usize) {
428        assert!(mid <= self.length);
429        if mid != 0 || mid != self.length {
430            self.range(mid..).drop_rotate_left()
431        }
432    }
433    pub fn rotate_right(&mut self, k: usize) {
434        assert!(k <= self.length);
435        self.rotate_left(self.length - k);
436    }
437}
438
439impl<T, A> Extend<T::Key> for SplaySequence<T, A>
440where
441    T: MonoidAction,
442    A: Allocator<Node<LazyAggElement<T>>>,
443{
444    fn extend<I>(&mut self, iter: I)
445    where
446        I: IntoIterator<Item = T::Key>,
447    {
448        let nodes: Vec<_> = unsafe {
449            iter.into_iter()
450                .map(|key| {
451                    let agg = T::single_agg(&key);
452                    NodeRef::from_data(
453                        LazyAggElement {
454                            key,
455                            agg,
456                            lazy: T::act_unit(),
457                            size: 1,
458                            rev: false,
459                        },
460                        self.alloc.deref_mut(),
461                    )
462                })
463                .collect()
464        };
465        self.length += nodes.len();
466        let mut root = unsafe { Root::from_single_nodes(nodes) };
467        self.root.append(&mut root);
468    }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sized_map.rs (lines 203-206)
189    pub fn insert(&mut self, key: K, value: V) -> Option<V>
190    where
191        K: Ord,
192    {
193        let ord = self.splay_by_key(&key);
194        self.length += (ord != Some(Ordering::Equal)) as usize;
195        match ord {
196            Some(Ordering::Equal) => {
197                return Some(replace(
198                    &mut (self.root.root_data_mut().unwrap().data_mut().0).1,
199                    value,
200                ));
201            }
202            Some(Ordering::Less) => unsafe {
203                self.root.insert_left(NodeRef::from_data(
204                    ((key, value), 1),
205                    self.alloc.deref_mut(),
206                ));
207            },
208            _ => unsafe {
209                self.root.insert_right(NodeRef::from_data(
210                    ((key, value), 1),
211                    self.alloc.deref_mut(),
212                ));
213            },
214        }
215        None
216    }
Source

pub fn borrow_mut(&mut self) -> NodeRef<Mut<'_>, S>

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 324)
296    pub fn splay_by<Seeker>(self, mut seeker: Seeker) -> (Ordering, Self)
297    where
298        Seeker: SplaySeeker<S = S>,
299    {
300        let mut x = self;
301        // let dummy = Node { data: None, left: left_subtree, right: right_subtree };
302        let mut left_subtree: Option<NonNull<Node<S::T>>> = None;
303        let mut right_subtree: Option<NonNull<Node<S::T>>> = None;
304        let mut left_entry = &mut left_subtree;
305        let mut right_entry = &mut right_subtree;
306        let mut stack = vec![];
307
308        macro_rules! add {
309            (@left Some($ptr:ident)) => { add!(@inner Some($ptr.node), left_entry $ptr right); };
310            (@right Some($ptr:ident)) => { add!(@inner Some($ptr.node), right_entry $ptr left); };
311            (@inner $node:expr, $entry:ident $ptr:ident $dir:ident) => {
312                *$entry = $node;
313                if S::has_bottom_up() {
314                    stack.push($ptr.node);
315                }
316                $entry = unsafe { &mut (*$entry.as_mut().unwrap().as_ptr()).$dir };
317            };
318        }
319
320        let root_ord = loop {
321            S::top_down(x.borrow_datamut());
322            match seeker.splay_seek(x.reborrow()) {
323                Ordering::Less => {
324                    if let Some(mut y) = x.borrow_mut().take_left() {
325                        S::top_down(y.borrow_datamut());
326                        match seeker.splay_seek(y.reborrow()) {
327                            Ordering::Less => {
328                                if let Some(mut z) = y.borrow_mut().take_left() {
329                                    S::top_down(z.borrow_datamut());
330                                    x.borrow_mut().set_left(y.borrow_mut().take_right());
331                                    S::bottom_up(x.borrow_datamut());
332                                    y.borrow_mut().set_right(Some(x));
333                                    add!(@right Some(y));
334                                    x = z;
335                                } else {
336                                    add!(@right Some(x));
337                                    x = y;
338                                    break Ordering::Less;
339                                }
340                            }
341                            Ordering::Equal => {
342                                add!(@right Some(x));
343                                x = y;
344                                break Ordering::Equal;
345                            }
346                            Ordering::Greater => {
347                                if let Some(mut z) = y.borrow_mut().take_right() {
348                                    S::top_down(z.borrow_datamut());
349                                    add!(@right Some(x));
350                                    add!(@left Some(y));
351                                    x = z;
352                                } else {
353                                    add!(@right Some(x));
354                                    x = y;
355                                    break Ordering::Greater;
356                                }
357                            }
358                        }
359                    } else {
360                        break Ordering::Less;
361                    }
362                }
363                Ordering::Equal => break Ordering::Equal,
364                Ordering::Greater => {
365                    if let Some(mut y) = x.borrow_mut().take_right() {
366                        S::top_down(y.borrow_datamut());
367                        match seeker.splay_seek(y.reborrow()) {
368                            Ordering::Less => {
369                                if let Some(mut z) = y.borrow_mut().take_left() {
370                                    S::top_down(z.borrow_datamut());
371                                    add!(@left Some(x));
372                                    add!(@right Some(y));
373                                    x = z;
374                                } else {
375                                    add!(@left Some(x));
376                                    x = y;
377                                    break Ordering::Less;
378                                }
379                            }
380                            Ordering::Equal => {
381                                add!(@left Some(x));
382                                x = y;
383                                break Ordering::Equal;
384                            }
385                            Ordering::Greater => {
386                                if let Some(mut z) = y.borrow_mut().take_right() {
387                                    S::top_down(z.borrow_datamut());
388                                    x.borrow_mut().set_right(y.borrow_mut().take_left());
389                                    S::bottom_up(x.borrow_datamut());
390                                    y.borrow_mut().set_left(Some(x));
391                                    add!(@left Some(y));
392                                    x = z;
393                                } else {
394                                    add!(@left Some(x));
395                                    x = y;
396                                    break Ordering::Greater;
397                                }
398                            }
399                        }
400                    } else {
401                        break Ordering::Greater;
402                    }
403                }
404            }
405        };
406        *left_entry = x.borrow_mut().take_left().map(|node| node.node);
407        *right_entry = x.borrow_mut().take_right().map(|node| node.node);
408        unsafe {
409            x.borrow_mut()
410                .set_left(left_subtree.map(|node| NodeRef::new_unchecked(node)));
411            x.borrow_mut()
412                .set_right(right_subtree.map(|node| NodeRef::new_unchecked(node)));
413            if S::has_bottom_up() {
414                while let Some(node) = stack.pop() {
415                    S::bottom_up(NodeRef::new_unchecked(node));
416                }
417            }
418        }
419        S::bottom_up(x.borrow_datamut());
420        (root_ord, x)
421    }
422    pub fn insert_left(mut self, mut node: Self) -> Self {
423        if let Some(left) = self.borrow_mut().take_left() {
424            node.borrow_mut().set_left(Some(left));
425            S::bottom_up(self.borrow_datamut());
426        };
427        node.borrow_mut().set_right(Some(self));
428        S::bottom_up(node.borrow_datamut());
429        node
430    }
431    pub fn insert_right(mut self, mut node: Self) -> Self {
432        if let Some(right) = self.borrow_mut().take_right() {
433            node.borrow_mut().set_right(Some(right));
434            S::bottom_up(self.borrow_datamut());
435        }
436        node.borrow_mut().set_left(Some(self));
437        S::bottom_up(node.borrow_datamut());
438        node
439    }
440    pub fn insert_first(self, mut node: Self) -> Self {
441        node.borrow_mut().set_right(Some(self));
442        S::bottom_up(node.borrow_datamut());
443        node
444    }
445    pub fn insert_last(self, mut node: Self) -> Self {
446        node.borrow_mut().set_left(Some(self));
447        S::bottom_up(node.borrow_datamut());
448        node
449    }
450    pub fn merge(mut self, mut other: Self) -> Self {
451        if other.reborrow().left().is_none() {
452            S::top_down(other.borrow_datamut());
453            other.borrow_mut().set_left(Some(self));
454            S::bottom_up(other.borrow_datamut());
455            other
456        } else {
457            self = self.splay_by(SeekRight::new()).1;
458            self.borrow_mut().set_right(Some(other));
459            S::bottom_up(self.borrow_datamut());
460            self
461        }
462    }
463}
464
465impl<S> Root<S>
466where
467    S: SplaySpec,
468{
469    pub fn new(root: Option<NodeRef<marker::Owned, S>>) -> Self {
470        Self { root }
471    }
472    pub unsafe fn from_single_nodes(nodes: Vec<NodeRef<marker::Owned, S>>) -> Self {
473        unsafe { Self::from_single_nodes_inner(&nodes) }
474    }
475    unsafe fn from_single_nodes_inner(nodes: &[NodeRef<marker::Owned, S>]) -> Self {
476        if nodes.is_empty() {
477            Self::new(None)
478        } else {
479            let m = nodes.len() / 2;
480            let left = unsafe { Self::from_single_nodes_inner(&nodes[..m]) };
481            let right = unsafe { Self::from_single_nodes_inner(&nodes[m + 1..]) };
482            let mut node = NodeRef::new(nodes[m].node);
483            node.borrow_mut().set_left(left.root);
484            node.borrow_mut().set_right(right.root);
485            S::bottom_up(node.borrow_datamut());
486            Self::new(Some(node))
487        }
488    }
489    pub fn is_empty(&self) -> bool {
490        self.root.is_none()
491    }
492    pub fn root(&self) -> Option<NodeRef<marker::Immut<'_>, S>> {
493        Some(self.root.as_ref()?.reborrow())
494    }
495    pub fn root_data_mut(&mut self) -> Option<NodeRef<marker::DataMut<'_>, S>> {
496        Some(self.root.as_mut()?.borrow_datamut())
497    }
498    pub fn splay_by<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
499    where
500        Seeker: SplaySeeker<S = S>,
501    {
502        let (ord, root) = self.root.take()?.splay_by(seeker);
503        self.root = Some(root);
504        Some(ord)
505    }
506    pub fn insert_left(&mut self, mut node: NodeRef<marker::Owned, S>) {
507        self.root = Some(match self.root.take() {
508            Some(root) => root.insert_left(node),
509            None => {
510                S::bottom_up(node.borrow_datamut());
511                node
512            }
513        });
514    }
515    pub fn insert_right(&mut self, mut node: NodeRef<marker::Owned, S>) {
516        self.root = Some(match self.root.take() {
517            Some(root) => root.insert_right(node),
518            None => {
519                S::bottom_up(node.borrow_datamut());
520                node
521            }
522        });
523    }
524    pub fn insert_first(&mut self, mut node: NodeRef<marker::Owned, S>) {
525        self.root = Some(match self.root.take() {
526            Some(root) => root.insert_first(node),
527            None => {
528                S::bottom_up(node.borrow_datamut());
529                node
530            }
531        });
532    }
533    pub fn insert_last(&mut self, mut node: NodeRef<marker::Owned, S>) {
534        self.root = Some(match self.root.take() {
535            Some(root) => root.insert_last(node),
536            None => {
537                S::bottom_up(node.borrow_datamut());
538                node
539            }
540        });
541    }
542    pub fn take_root(&mut self) -> Option<NodeRef<marker::Owned, S>> {
543        let mut root = self.root.take()?;
544        let right = root.borrow_mut().take_right();
545        self.root = root.borrow_mut().take_left();
546        self.append(&mut Self::new(right));
547        Some(root)
548    }
549    pub fn take_first(&mut self) -> Option<NodeRef<marker::Owned, S>> {
550        let mut root = self.root.take()?.splay_by(SeekLeft::new()).1;
551        let right = root.borrow_mut().take_right();
552        self.root = right;
553        Some(root)
554    }
555    pub fn take_last(&mut self) -> Option<NodeRef<marker::Owned, S>> {
556        let mut root = self.root.take()?.splay_by(SeekRight::new()).1;
557        let left = root.borrow_mut().take_left();
558        self.root = left;
559        Some(root)
560    }
561    pub fn split_left(&mut self) -> Option<NodeRef<marker::Owned, S>> {
562        let root = self.root.as_mut()?;
563        let left = root.borrow_mut().take_left();
564        S::bottom_up(root.borrow_datamut());
565        left
566    }
567    pub fn split_right(&mut self) -> Option<NodeRef<marker::Owned, S>> {
568        let root = self.root.as_mut()?;
569        let right = root.borrow_mut().take_right();
570        S::bottom_up(root.borrow_datamut());
571        right
572    }
Source

pub fn borrow_datamut(&mut self) -> NodeRef<DataMut<'_>, S>

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 321)
296    pub fn splay_by<Seeker>(self, mut seeker: Seeker) -> (Ordering, Self)
297    where
298        Seeker: SplaySeeker<S = S>,
299    {
300        let mut x = self;
301        // let dummy = Node { data: None, left: left_subtree, right: right_subtree };
302        let mut left_subtree: Option<NonNull<Node<S::T>>> = None;
303        let mut right_subtree: Option<NonNull<Node<S::T>>> = None;
304        let mut left_entry = &mut left_subtree;
305        let mut right_entry = &mut right_subtree;
306        let mut stack = vec![];
307
308        macro_rules! add {
309            (@left Some($ptr:ident)) => { add!(@inner Some($ptr.node), left_entry $ptr right); };
310            (@right Some($ptr:ident)) => { add!(@inner Some($ptr.node), right_entry $ptr left); };
311            (@inner $node:expr, $entry:ident $ptr:ident $dir:ident) => {
312                *$entry = $node;
313                if S::has_bottom_up() {
314                    stack.push($ptr.node);
315                }
316                $entry = unsafe { &mut (*$entry.as_mut().unwrap().as_ptr()).$dir };
317            };
318        }
319
320        let root_ord = loop {
321            S::top_down(x.borrow_datamut());
322            match seeker.splay_seek(x.reborrow()) {
323                Ordering::Less => {
324                    if let Some(mut y) = x.borrow_mut().take_left() {
325                        S::top_down(y.borrow_datamut());
326                        match seeker.splay_seek(y.reborrow()) {
327                            Ordering::Less => {
328                                if let Some(mut z) = y.borrow_mut().take_left() {
329                                    S::top_down(z.borrow_datamut());
330                                    x.borrow_mut().set_left(y.borrow_mut().take_right());
331                                    S::bottom_up(x.borrow_datamut());
332                                    y.borrow_mut().set_right(Some(x));
333                                    add!(@right Some(y));
334                                    x = z;
335                                } else {
336                                    add!(@right Some(x));
337                                    x = y;
338                                    break Ordering::Less;
339                                }
340                            }
341                            Ordering::Equal => {
342                                add!(@right Some(x));
343                                x = y;
344                                break Ordering::Equal;
345                            }
346                            Ordering::Greater => {
347                                if let Some(mut z) = y.borrow_mut().take_right() {
348                                    S::top_down(z.borrow_datamut());
349                                    add!(@right Some(x));
350                                    add!(@left Some(y));
351                                    x = z;
352                                } else {
353                                    add!(@right Some(x));
354                                    x = y;
355                                    break Ordering::Greater;
356                                }
357                            }
358                        }
359                    } else {
360                        break Ordering::Less;
361                    }
362                }
363                Ordering::Equal => break Ordering::Equal,
364                Ordering::Greater => {
365                    if let Some(mut y) = x.borrow_mut().take_right() {
366                        S::top_down(y.borrow_datamut());
367                        match seeker.splay_seek(y.reborrow()) {
368                            Ordering::Less => {
369                                if let Some(mut z) = y.borrow_mut().take_left() {
370                                    S::top_down(z.borrow_datamut());
371                                    add!(@left Some(x));
372                                    add!(@right Some(y));
373                                    x = z;
374                                } else {
375                                    add!(@left Some(x));
376                                    x = y;
377                                    break Ordering::Less;
378                                }
379                            }
380                            Ordering::Equal => {
381                                add!(@left Some(x));
382                                x = y;
383                                break Ordering::Equal;
384                            }
385                            Ordering::Greater => {
386                                if let Some(mut z) = y.borrow_mut().take_right() {
387                                    S::top_down(z.borrow_datamut());
388                                    x.borrow_mut().set_right(y.borrow_mut().take_left());
389                                    S::bottom_up(x.borrow_datamut());
390                                    y.borrow_mut().set_left(Some(x));
391                                    add!(@left Some(y));
392                                    x = z;
393                                } else {
394                                    add!(@left Some(x));
395                                    x = y;
396                                    break Ordering::Greater;
397                                }
398                            }
399                        }
400                    } else {
401                        break Ordering::Greater;
402                    }
403                }
404            }
405        };
406        *left_entry = x.borrow_mut().take_left().map(|node| node.node);
407        *right_entry = x.borrow_mut().take_right().map(|node| node.node);
408        unsafe {
409            x.borrow_mut()
410                .set_left(left_subtree.map(|node| NodeRef::new_unchecked(node)));
411            x.borrow_mut()
412                .set_right(right_subtree.map(|node| NodeRef::new_unchecked(node)));
413            if S::has_bottom_up() {
414                while let Some(node) = stack.pop() {
415                    S::bottom_up(NodeRef::new_unchecked(node));
416                }
417            }
418        }
419        S::bottom_up(x.borrow_datamut());
420        (root_ord, x)
421    }
422    pub fn insert_left(mut self, mut node: Self) -> Self {
423        if let Some(left) = self.borrow_mut().take_left() {
424            node.borrow_mut().set_left(Some(left));
425            S::bottom_up(self.borrow_datamut());
426        };
427        node.borrow_mut().set_right(Some(self));
428        S::bottom_up(node.borrow_datamut());
429        node
430    }
431    pub fn insert_right(mut self, mut node: Self) -> Self {
432        if let Some(right) = self.borrow_mut().take_right() {
433            node.borrow_mut().set_right(Some(right));
434            S::bottom_up(self.borrow_datamut());
435        }
436        node.borrow_mut().set_left(Some(self));
437        S::bottom_up(node.borrow_datamut());
438        node
439    }
440    pub fn insert_first(self, mut node: Self) -> Self {
441        node.borrow_mut().set_right(Some(self));
442        S::bottom_up(node.borrow_datamut());
443        node
444    }
445    pub fn insert_last(self, mut node: Self) -> Self {
446        node.borrow_mut().set_left(Some(self));
447        S::bottom_up(node.borrow_datamut());
448        node
449    }
450    pub fn merge(mut self, mut other: Self) -> Self {
451        if other.reborrow().left().is_none() {
452            S::top_down(other.borrow_datamut());
453            other.borrow_mut().set_left(Some(self));
454            S::bottom_up(other.borrow_datamut());
455            other
456        } else {
457            self = self.splay_by(SeekRight::new()).1;
458            self.borrow_mut().set_right(Some(other));
459            S::bottom_up(self.borrow_datamut());
460            self
461        }
462    }
463}
464
465impl<S> Root<S>
466where
467    S: SplaySpec,
468{
469    pub fn new(root: Option<NodeRef<marker::Owned, S>>) -> Self {
470        Self { root }
471    }
472    pub unsafe fn from_single_nodes(nodes: Vec<NodeRef<marker::Owned, S>>) -> Self {
473        unsafe { Self::from_single_nodes_inner(&nodes) }
474    }
475    unsafe fn from_single_nodes_inner(nodes: &[NodeRef<marker::Owned, S>]) -> Self {
476        if nodes.is_empty() {
477            Self::new(None)
478        } else {
479            let m = nodes.len() / 2;
480            let left = unsafe { Self::from_single_nodes_inner(&nodes[..m]) };
481            let right = unsafe { Self::from_single_nodes_inner(&nodes[m + 1..]) };
482            let mut node = NodeRef::new(nodes[m].node);
483            node.borrow_mut().set_left(left.root);
484            node.borrow_mut().set_right(right.root);
485            S::bottom_up(node.borrow_datamut());
486            Self::new(Some(node))
487        }
488    }
489    pub fn is_empty(&self) -> bool {
490        self.root.is_none()
491    }
492    pub fn root(&self) -> Option<NodeRef<marker::Immut<'_>, S>> {
493        Some(self.root.as_ref()?.reborrow())
494    }
495    pub fn root_data_mut(&mut self) -> Option<NodeRef<marker::DataMut<'_>, S>> {
496        Some(self.root.as_mut()?.borrow_datamut())
497    }
498    pub fn splay_by<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
499    where
500        Seeker: SplaySeeker<S = S>,
501    {
502        let (ord, root) = self.root.take()?.splay_by(seeker);
503        self.root = Some(root);
504        Some(ord)
505    }
506    pub fn insert_left(&mut self, mut node: NodeRef<marker::Owned, S>) {
507        self.root = Some(match self.root.take() {
508            Some(root) => root.insert_left(node),
509            None => {
510                S::bottom_up(node.borrow_datamut());
511                node
512            }
513        });
514    }
515    pub fn insert_right(&mut self, mut node: NodeRef<marker::Owned, S>) {
516        self.root = Some(match self.root.take() {
517            Some(root) => root.insert_right(node),
518            None => {
519                S::bottom_up(node.borrow_datamut());
520                node
521            }
522        });
523    }
524    pub fn insert_first(&mut self, mut node: NodeRef<marker::Owned, S>) {
525        self.root = Some(match self.root.take() {
526            Some(root) => root.insert_first(node),
527            None => {
528                S::bottom_up(node.borrow_datamut());
529                node
530            }
531        });
532    }
533    pub fn insert_last(&mut self, mut node: NodeRef<marker::Owned, S>) {
534        self.root = Some(match self.root.take() {
535            Some(root) => root.insert_last(node),
536            None => {
537                S::bottom_up(node.borrow_datamut());
538                node
539            }
540        });
541    }
542    pub fn take_root(&mut self) -> Option<NodeRef<marker::Owned, S>> {
543        let mut root = self.root.take()?;
544        let right = root.borrow_mut().take_right();
545        self.root = root.borrow_mut().take_left();
546        self.append(&mut Self::new(right));
547        Some(root)
548    }
549    pub fn take_first(&mut self) -> Option<NodeRef<marker::Owned, S>> {
550        let mut root = self.root.take()?.splay_by(SeekLeft::new()).1;
551        let right = root.borrow_mut().take_right();
552        self.root = right;
553        Some(root)
554    }
555    pub fn take_last(&mut self) -> Option<NodeRef<marker::Owned, S>> {
556        let mut root = self.root.take()?.splay_by(SeekRight::new()).1;
557        let left = root.borrow_mut().take_left();
558        self.root = left;
559        Some(root)
560    }
561    pub fn split_left(&mut self) -> Option<NodeRef<marker::Owned, S>> {
562        let root = self.root.as_mut()?;
563        let left = root.borrow_mut().take_left();
564        S::bottom_up(root.borrow_datamut());
565        left
566    }
567    pub fn split_right(&mut self) -> Option<NodeRef<marker::Owned, S>> {
568        let root = self.root.as_mut()?;
569        let right = root.borrow_mut().take_right();
570        S::bottom_up(root.borrow_datamut());
571        right
572    }
Source

pub fn into_dying(self) -> NodeRef<Dying, S>

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 265)
262    fn drop(&mut self) {
263        unsafe {
264            while let Some(node) = self.root.take_first() {
265                self.alloc.deallocate(node.into_dying().into_inner());
266            }
267            ManuallyDrop::drop(&mut self.alloc);
268        }
269    }
270}
271
272impl<T, A> Default for SplaySequence<T, A>
273where
274    T: MonoidAction,
275    A: Allocator<Node<LazyAggElement<T>>> + Default,
276{
277    fn default() -> Self {
278        Self {
279            root: Root::default(),
280            length: 0,
281            alloc: Default::default(),
282        }
283    }
284}
285
286impl<T> SplaySequence<T>
287where
288    T: MonoidAction,
289{
290    pub fn new() -> Self {
291        Default::default()
292    }
293    pub fn with_capacity(capacity: usize) -> Self {
294        Self {
295            root: Root::default(),
296            length: 0,
297            alloc: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
298        }
299    }
300    pub fn len(&self) -> usize {
301        self.length
302    }
303    pub fn is_empty(&self) -> bool {
304        self.length == 0
305    }
306}
307impl<T, A> SplaySequence<T, A>
308where
309    T: MonoidAction,
310    A: Allocator<Node<LazyAggElement<T>>>,
311{
312    fn range<R>(&mut self, range: R) -> NodeRange<'_, LazyAggSplay<T>>
313    where
314        R: RangeBounds<usize>,
315    {
316        let start = match range.start_bound() {
317            Bound::Included(&index) => Bound::Included(SeekBySize::new(index)),
318            Bound::Excluded(&index) => Bound::Excluded(SeekBySize::new(index)),
319            Bound::Unbounded => Bound::Unbounded,
320        };
321        let end = match range.end_bound() {
322            Bound::Included(&index) => Bound::Included(SeekBySize::new(index)),
323            Bound::Excluded(&index) => Bound::Excluded(SeekBySize::new(index)),
324            Bound::Unbounded => Bound::Unbounded,
325        };
326        self.root.range(start, end)
327    }
328    pub fn update<R>(&mut self, range: R, x: T::Act)
329    where
330        R: RangeBounds<usize>,
331    {
332        if let Some(root) = self.range(range).root_mut().root_data_mut() {
333            LazyAggSplay::<T>::update_lazy(root, &x);
334        }
335    }
336    pub fn fold<R>(&mut self, range: R) -> T::Agg
337    where
338        R: RangeBounds<usize>,
339    {
340        if let Some(root) = self.range(range).root().root() {
341            root.data().agg.clone()
342        } else {
343            T::agg_unit()
344        }
345    }
346    pub fn reverse<R>(&mut self, range: R)
347    where
348        R: RangeBounds<usize>,
349    {
350        if let Some(root) = self.range(range).root_mut().root_data_mut() {
351            LazyAggSplay::<T>::reverse(root);
352        }
353    }
354    pub fn get(&mut self, index: usize) -> Option<&T::Key> {
355        self.root.splay_by(SeekBySize::new(index))?;
356        self.root.root().map(|root| &root.data().key)
357    }
358    pub fn modify<F>(&mut self, index: usize, f: F)
359    where
360        F: FnOnce(&T::Key) -> T::Key,
361    {
362        self.root.splay_by(SeekBySize::new(index)).unwrap();
363        let data = self.root.root_data_mut().unwrap().data_mut();
364        data.key = f(&data.key);
365        LazyAggSplay::<T>::bottom_up(self.root.root_data_mut().unwrap());
366    }
367    pub fn insert(&mut self, index: usize, x: T::Key) {
368        assert!(index <= self.length);
369        self.root.splay_by(SeekBySize::new(index));
370        let agg = T::single_agg(&x);
371        unsafe {
372            let node = NodeRef::from_data(
373                LazyAggElement {
374                    key: x,
375                    agg,
376                    lazy: T::act_unit(),
377                    size: 1,
378                    rev: false,
379                },
380                self.alloc.deref_mut(),
381            );
382            if index == self.length {
383                self.root.insert_right(node);
384            } else {
385                self.root.insert_left(node);
386            }
387        }
388        self.length += 1;
389    }
390    pub fn remove(&mut self, index: usize) -> Option<T::Key> {
391        if index >= self.length {
392            return None;
393        }
394        self.root.splay_by(SeekBySize::new(index));
395        self.length -= 1;
396        let node = self.root.take_root().unwrap().into_dying();
397        unsafe { Some(node.into_data(self.alloc.deref_mut()).key) }
398    }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sized_map.rs (line 113)
110    fn drop(&mut self) {
111        unsafe {
112            while let Some(node) = self.root.take_first() {
113                self.alloc.deallocate(node.into_dying().into_inner());
114            }
115            ManuallyDrop::drop(&mut self.alloc);
116        }
117    }
118}
119
120impl<K, V, A> Default for SplayMap<K, V, A>
121where
122    A: Allocator<Node<((K, V), usize)>> + Default,
123{
124    fn default() -> Self {
125        Self {
126            root: Root::default(),
127            length: 0,
128            alloc: Default::default(),
129        }
130    }
131}
132
133impl<K, V> SplayMap<K, V> {
134    pub fn new() -> Self {
135        Default::default()
136    }
137    pub fn with_capacity(capacity: usize) -> Self {
138        Self {
139            root: Root::default(),
140            length: 0,
141            alloc: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
142        }
143    }
144}
145impl<K, V, A> SplayMap<K, V, A>
146where
147    A: Allocator<Node<((K, V), usize)>>,
148{
149    pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
150    where
151        K: Borrow<Q>,
152        Q: Ord + ?Sized,
153    {
154        self.get_key_value(key).map(|(_, v)| v)
155    }
156    fn splay_by_key<Q>(&mut self, key: &Q) -> Option<Ordering>
157    where
158        K: Borrow<Q>,
159        Q: Ord + ?Sized,
160    {
161        self.root.splay_by(SeekByKey::new(key))
162    }
163    pub fn get_key_value<Q>(&mut self, key: &Q) -> Option<(&K, &V)>
164    where
165        K: Borrow<Q>,
166        Q: Ord + ?Sized,
167    {
168        if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
169            return None;
170        }
171        self.root.root().map(|node| {
172            let ((k, v), _) = node.data();
173            (k, v)
174        })
175    }
176    fn splay_at(&mut self, index: usize) -> Option<Ordering> {
177        self.root.splay_by(SeekBySize::new(index))
178    }
179    pub fn get_key_value_at(&mut self, index: usize) -> Option<(&K, &V)> {
180        if index >= self.length {
181            return None;
182        }
183        self.splay_at(index);
184        self.root.root().map(|node| {
185            let ((k, v), _) = node.data();
186            (k, v)
187        })
188    }
189    pub fn insert(&mut self, key: K, value: V) -> Option<V>
190    where
191        K: Ord,
192    {
193        let ord = self.splay_by_key(&key);
194        self.length += (ord != Some(Ordering::Equal)) as usize;
195        match ord {
196            Some(Ordering::Equal) => {
197                return Some(replace(
198                    &mut (self.root.root_data_mut().unwrap().data_mut().0).1,
199                    value,
200                ));
201            }
202            Some(Ordering::Less) => unsafe {
203                self.root.insert_left(NodeRef::from_data(
204                    ((key, value), 1),
205                    self.alloc.deref_mut(),
206                ));
207            },
208            _ => unsafe {
209                self.root.insert_right(NodeRef::from_data(
210                    ((key, value), 1),
211                    self.alloc.deref_mut(),
212                ));
213            },
214        }
215        None
216    }
217    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
218    where
219        K: Borrow<Q>,
220        Q: Ord + ?Sized,
221    {
222        if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
223            return None;
224        }
225        self.length -= 1;
226        let node = self.root.take_root().unwrap().into_dying();
227        unsafe { Some((node.into_data(self.alloc.deref_mut()).0).1) }
228    }
229    pub fn remove_at(&mut self, index: usize) -> Option<(K, V)> {
230        if index >= self.length {
231            return None;
232        }
233        self.splay_at(index);
234        self.length -= 1;
235        let node = self.root.take_root().unwrap().into_dying();
236        unsafe { Some(node.into_data(self.alloc.deref_mut()).0) }
237    }
Source§

impl<'a, S> NodeRef<Immut<'a>, S>
where S: SplaySpec, S::T: 'a,

Source

pub fn data(&self) -> &'a S::T

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/sized_map.rs (line 55)
54    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
55        self.key.cmp((node.data().0).0.borrow())
56    }
57}
58
59struct SeekBySize<K, V> {
60    index: usize,
61    _marker: PhantomData<fn() -> (K, V)>,
62}
63impl<K, V> SeekBySize<K, V> {
64    fn new(index: usize) -> Self {
65        Self {
66            index,
67            _marker: PhantomData,
68        }
69    }
70}
71impl<K, V> SplaySeeker for SeekBySize<K, V> {
72    type S = SizedSplay<(K, V)>;
73    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
74        let lsize = node.left().map(|l| l.data().1).unwrap_or_default();
75        let ord = self.index.cmp(&lsize);
76        if matches!(ord, Ordering::Greater) {
77            self.index -= lsize + 1;
78        }
79        ord
80    }
81}
82
83pub struct SplayMap<K, V, A = MemoryPool<Node<((K, V), usize)>>>
84where
85    A: Allocator<Node<((K, V), usize)>>,
86{
87    root: Root<SizedSplay<(K, V)>>,
88    length: usize,
89    alloc: ManuallyDrop<A>,
90}
91
92impl<K, V, A> Debug for SplayMap<K, V, A>
93where
94    K: Debug,
95    V: Debug,
96    A: Allocator<Node<((K, V), usize)>>,
97{
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.debug_struct("SplayMap")
100            .field("root", &self.root)
101            .field("length", &self.length)
102            .finish()
103    }
104}
105
106impl<K, V, A> Drop for SplayMap<K, V, A>
107where
108    A: Allocator<Node<((K, V), usize)>>,
109{
110    fn drop(&mut self) {
111        unsafe {
112            while let Some(node) = self.root.take_first() {
113                self.alloc.deallocate(node.into_dying().into_inner());
114            }
115            ManuallyDrop::drop(&mut self.alloc);
116        }
117    }
118}
119
120impl<K, V, A> Default for SplayMap<K, V, A>
121where
122    A: Allocator<Node<((K, V), usize)>> + Default,
123{
124    fn default() -> Self {
125        Self {
126            root: Root::default(),
127            length: 0,
128            alloc: Default::default(),
129        }
130    }
131}
132
133impl<K, V> SplayMap<K, V> {
134    pub fn new() -> Self {
135        Default::default()
136    }
137    pub fn with_capacity(capacity: usize) -> Self {
138        Self {
139            root: Root::default(),
140            length: 0,
141            alloc: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
142        }
143    }
144}
145impl<K, V, A> SplayMap<K, V, A>
146where
147    A: Allocator<Node<((K, V), usize)>>,
148{
149    pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
150    where
151        K: Borrow<Q>,
152        Q: Ord + ?Sized,
153    {
154        self.get_key_value(key).map(|(_, v)| v)
155    }
156    fn splay_by_key<Q>(&mut self, key: &Q) -> Option<Ordering>
157    where
158        K: Borrow<Q>,
159        Q: Ord + ?Sized,
160    {
161        self.root.splay_by(SeekByKey::new(key))
162    }
163    pub fn get_key_value<Q>(&mut self, key: &Q) -> Option<(&K, &V)>
164    where
165        K: Borrow<Q>,
166        Q: Ord + ?Sized,
167    {
168        if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
169            return None;
170        }
171        self.root.root().map(|node| {
172            let ((k, v), _) = node.data();
173            (k, v)
174        })
175    }
176    fn splay_at(&mut self, index: usize) -> Option<Ordering> {
177        self.root.splay_by(SeekBySize::new(index))
178    }
179    pub fn get_key_value_at(&mut self, index: usize) -> Option<(&K, &V)> {
180        if index >= self.length {
181            return None;
182        }
183        self.splay_at(index);
184        self.root.root().map(|node| {
185            let ((k, v), _) = node.data();
186            (k, v)
187        })
188    }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 136)
135    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
136        let lsize = node.left().map(|l| l.data().size).unwrap_or_default();
137        let ord = self.index.cmp(&lsize);
138        if matches!(ord, Ordering::Greater) {
139            self.index -= lsize + 1;
140        }
141        ord
142    }
143}
144
145struct SeekByAccCond<F, T>
146where
147    T: MonoidAction,
148{
149    acc: T::Agg,
150    f: F,
151    _marker: PhantomData<fn() -> T>,
152}
153impl<F, T> SeekByAccCond<F, T>
154where
155    T: MonoidAction,
156{
157    fn new(f: F) -> Self {
158        Self {
159            acc: T::agg_unit(),
160            f,
161            _marker: PhantomData,
162        }
163    }
164}
165impl<F, T> SplaySeeker for SeekByAccCond<F, T>
166where
167    F: FnMut(&T::Agg) -> bool,
168    T: MonoidAction,
169{
170    type S = LazyAggSplay<T>;
171    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
172        if let Some(lagg) = node.left().map(|l| &l.data().agg) {
173            let nacc = T::agg_operate(&self.acc, lagg);
174            if (self.f)(&nacc) {
175                return Ordering::Less;
176            }
177            self.acc = nacc;
178        };
179        self.acc = T::agg_operate(&self.acc, &T::single_agg(&node.data().key));
180        if (self.f)(&self.acc) {
181            Ordering::Equal
182        } else {
183            Ordering::Greater
184        }
185    }
186}
187
188struct SeekByRaccCond<F, T>
189where
190    T: MonoidAction,
191{
192    acc: T::Agg,
193    f: F,
194    _marker: PhantomData<fn() -> T>,
195}
196impl<F, T> SeekByRaccCond<F, T>
197where
198    T: MonoidAction,
199{
200    fn new(f: F) -> Self {
201        Self {
202            acc: T::agg_unit(),
203            f,
204            _marker: PhantomData,
205        }
206    }
207}
208impl<F, T> SplaySeeker for SeekByRaccCond<F, T>
209where
210    F: FnMut(&T::Agg) -> bool,
211    T: MonoidAction,
212{
213    type S = LazyAggSplay<T>;
214    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
215        if let Some(lagg) = node.right().map(|r| &r.data().agg) {
216            let nacc = T::agg_operate(lagg, &self.acc);
217            if (self.f)(&nacc) {
218                return Ordering::Greater;
219            }
220            self.acc = nacc;
221        };
222        self.acc = T::agg_operate(&T::single_agg(&node.data().key), &self.acc);
223        if (self.f)(&self.acc) {
224            Ordering::Equal
225        } else {
226            Ordering::Less
227        }
228    }
229}
230
231pub struct SplaySequence<T, A = MemoryPool<Node<LazyAggElement<T>>>>
232where
233    T: MonoidAction,
234    A: Allocator<Node<LazyAggElement<T>>>,
235{
236    root: Root<LazyAggSplay<T>>,
237    length: usize,
238    alloc: ManuallyDrop<A>,
239}
240
241impl<T, A> Debug for SplaySequence<T, A>
242where
243    T: MonoidAction,
244    T::Key: Debug,
245    T::Agg: Debug,
246    T::Act: Debug,
247    A: Allocator<Node<LazyAggElement<T>>>,
248{
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_struct("SplayMap")
251            .field("root", &self.root)
252            .field("length", &self.length)
253            .finish()
254    }
255}
256
257impl<T, A> Drop for SplaySequence<T, A>
258where
259    T: MonoidAction,
260    A: Allocator<Node<LazyAggElement<T>>>,
261{
262    fn drop(&mut self) {
263        unsafe {
264            while let Some(node) = self.root.take_first() {
265                self.alloc.deallocate(node.into_dying().into_inner());
266            }
267            ManuallyDrop::drop(&mut self.alloc);
268        }
269    }
270}
271
272impl<T, A> Default for SplaySequence<T, A>
273where
274    T: MonoidAction,
275    A: Allocator<Node<LazyAggElement<T>>> + Default,
276{
277    fn default() -> Self {
278        Self {
279            root: Root::default(),
280            length: 0,
281            alloc: Default::default(),
282        }
283    }
284}
285
286impl<T> SplaySequence<T>
287where
288    T: MonoidAction,
289{
290    pub fn new() -> Self {
291        Default::default()
292    }
293    pub fn with_capacity(capacity: usize) -> Self {
294        Self {
295            root: Root::default(),
296            length: 0,
297            alloc: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
298        }
299    }
300    pub fn len(&self) -> usize {
301        self.length
302    }
303    pub fn is_empty(&self) -> bool {
304        self.length == 0
305    }
306}
307impl<T, A> SplaySequence<T, A>
308where
309    T: MonoidAction,
310    A: Allocator<Node<LazyAggElement<T>>>,
311{
312    fn range<R>(&mut self, range: R) -> NodeRange<'_, LazyAggSplay<T>>
313    where
314        R: RangeBounds<usize>,
315    {
316        let start = match range.start_bound() {
317            Bound::Included(&index) => Bound::Included(SeekBySize::new(index)),
318            Bound::Excluded(&index) => Bound::Excluded(SeekBySize::new(index)),
319            Bound::Unbounded => Bound::Unbounded,
320        };
321        let end = match range.end_bound() {
322            Bound::Included(&index) => Bound::Included(SeekBySize::new(index)),
323            Bound::Excluded(&index) => Bound::Excluded(SeekBySize::new(index)),
324            Bound::Unbounded => Bound::Unbounded,
325        };
326        self.root.range(start, end)
327    }
328    pub fn update<R>(&mut self, range: R, x: T::Act)
329    where
330        R: RangeBounds<usize>,
331    {
332        if let Some(root) = self.range(range).root_mut().root_data_mut() {
333            LazyAggSplay::<T>::update_lazy(root, &x);
334        }
335    }
336    pub fn fold<R>(&mut self, range: R) -> T::Agg
337    where
338        R: RangeBounds<usize>,
339    {
340        if let Some(root) = self.range(range).root().root() {
341            root.data().agg.clone()
342        } else {
343            T::agg_unit()
344        }
345    }
346    pub fn reverse<R>(&mut self, range: R)
347    where
348        R: RangeBounds<usize>,
349    {
350        if let Some(root) = self.range(range).root_mut().root_data_mut() {
351            LazyAggSplay::<T>::reverse(root);
352        }
353    }
354    pub fn get(&mut self, index: usize) -> Option<&T::Key> {
355        self.root.splay_by(SeekBySize::new(index))?;
356        self.root.root().map(|root| &root.data().key)
357    }
358    pub fn modify<F>(&mut self, index: usize, f: F)
359    where
360        F: FnOnce(&T::Key) -> T::Key,
361    {
362        self.root.splay_by(SeekBySize::new(index)).unwrap();
363        let data = self.root.root_data_mut().unwrap().data_mut();
364        data.key = f(&data.key);
365        LazyAggSplay::<T>::bottom_up(self.root.root_data_mut().unwrap());
366    }
367    pub fn insert(&mut self, index: usize, x: T::Key) {
368        assert!(index <= self.length);
369        self.root.splay_by(SeekBySize::new(index));
370        let agg = T::single_agg(&x);
371        unsafe {
372            let node = NodeRef::from_data(
373                LazyAggElement {
374                    key: x,
375                    agg,
376                    lazy: T::act_unit(),
377                    size: 1,
378                    rev: false,
379                },
380                self.alloc.deref_mut(),
381            );
382            if index == self.length {
383                self.root.insert_right(node);
384            } else {
385                self.root.insert_left(node);
386            }
387        }
388        self.length += 1;
389    }
390    pub fn remove(&mut self, index: usize) -> Option<T::Key> {
391        if index >= self.length {
392            return None;
393        }
394        self.root.splay_by(SeekBySize::new(index));
395        self.length -= 1;
396        let node = self.root.take_root().unwrap().into_dying();
397        unsafe { Some(node.into_data(self.alloc.deref_mut()).key) }
398    }
399    pub fn position_acc<R, F>(&mut self, range: R, f: F) -> Option<usize>
400    where
401        R: RangeBounds<usize>,
402        F: FnMut(&T::Agg) -> bool,
403    {
404        let mut range = self.range(range);
405        let ord = range.root_mut().splay_by(SeekByAccCond::new(f));
406        if !matches!(ord, Some(Ordering::Equal)) {
407            return None;
408        }
409        let front_size = range.front().size();
410        let left_size = range.root().left_size();
411        Some(front_size + left_size)
412    }
413    pub fn rposition_acc<R, F>(&mut self, range: R, f: F) -> Option<usize>
414    where
415        R: RangeBounds<usize>,
416        F: FnMut(&T::Agg) -> bool,
417    {
418        let mut range = self.range(range);
419        let ord = range.root_mut().splay_by(SeekByRaccCond::new(f));
420        if !matches!(ord, Some(Ordering::Equal)) {
421            return None;
422        }
423        let front_size = range.front().size();
424        let left_size = range.root().left_size();
425        Some(front_size + left_size)
426    }
427    pub fn rotate_left(&mut self, mid: usize) {
428        assert!(mid <= self.length);
429        if mid != 0 || mid != self.length {
430            self.range(mid..).drop_rotate_left()
431        }
432    }
433    pub fn rotate_right(&mut self, k: usize) {
434        assert!(k <= self.length);
435        self.rotate_left(self.length - k);
436    }
437}
438
439impl<T, A> Extend<T::Key> for SplaySequence<T, A>
440where
441    T: MonoidAction,
442    A: Allocator<Node<LazyAggElement<T>>>,
443{
444    fn extend<I>(&mut self, iter: I)
445    where
446        I: IntoIterator<Item = T::Key>,
447    {
448        let nodes: Vec<_> = unsafe {
449            iter.into_iter()
450                .map(|key| {
451                    let agg = T::single_agg(&key);
452                    NodeRef::from_data(
453                        LazyAggElement {
454                            key,
455                            agg,
456                            lazy: T::act_unit(),
457                            size: 1,
458                            rev: false,
459                        },
460                        self.alloc.deref_mut(),
461                    )
462                })
463                .collect()
464        };
465        self.length += nodes.len();
466        let mut root = unsafe { Root::from_single_nodes(nodes) };
467        self.root.append(&mut root);
468    }
469}
470
471impl<T> Root<LazyAggSplay<T>>
472where
473    T: MonoidAction,
474{
475    fn size(&self) -> usize {
476        self.root().map(|root| root.data().size).unwrap_or_default()
477    }
478    fn left_size(&self) -> usize {
479        self.root()
480            .and_then(|root| root.left().map(|left| left.data().size))
481            .unwrap_or_default()
482    }
crates/competitive/src/data_structure/splay_tree/node.rs (line 642)
630        fn fmt_recurse<'a, S>(
631            node: NodeRef<marker::Immut<'a>, S>,
632            f: &mut fmt::Formatter<'_>,
633        ) -> fmt::Result
634        where
635            S: SplaySpec,
636            S::T: 'a + Debug,
637        {
638            write!(f, "[")?;
639            if let Some(left) = node.left() {
640                fmt_recurse(left, f)?;
641            }
642            node.data().fmt(f)?;
643            if let Some(right) = node.right() {
644                fmt_recurse(right, f)?;
645            }
646            write!(f, "]")?;
647            Ok(())
648        }
Source

pub fn left(&self) -> Option<Self>

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 200)
195    pub fn traverse<F>(self, f: &mut F)
196    where
197        S::T: 'a,
198        F: FnMut(Self),
199    {
200        if let Some(left) = self.clone().left() {
201            left.traverse(f);
202        }
203        f(self);
204        if let Some(right) = self.clone().right() {
205            right.traverse(f);
206        }
207    }
208}
209
210impl<'a, S> NodeRef<marker::DataMut<'a>, S>
211where
212    S: SplaySpec,
213    S::T: 'a,
214{
215    pub fn data(&self) -> &'a S::T {
216        unsafe { &(*self.as_ptr()).data }
217    }
218    pub fn data_mut(&self) -> &'a mut S::T {
219        unsafe { &mut (*self.as_ptr()).data }
220    }
221    pub fn left(&self) -> Option<Self> {
222        unsafe {
223            (*self.as_ptr())
224                .left
225                .map(|node| NodeRef::new_unchecked(node))
226        }
227    }
228    pub fn right(&self) -> Option<Self> {
229        unsafe {
230            (*self.as_ptr())
231                .right
232                .map(|node| NodeRef::new_unchecked(node))
233        }
234    }
235    pub fn reverse(&self) {
236        unsafe {
237            let node = &mut (*self.as_ptr());
238            swap(&mut node.left, &mut node.right);
239        }
240    }
241}
242
243impl<'a, S> NodeRef<marker::Mut<'a>, S>
244where
245    S: SplaySpec,
246    S::T: 'a,
247{
248    pub fn data(self) -> &'a S::T {
249        unsafe { &(*self.as_ptr()).data }
250    }
251    pub fn data_mut(self) -> &'a mut S::T {
252        unsafe { &mut (*self.as_ptr()).data }
253    }
254    pub fn take_left(&mut self) -> Option<NodeRef<marker::Owned, S>> {
255        Some(NodeRef::new(unsafe { (*self.as_ptr()).left.take()? }))
256    }
257    pub fn take_right(&mut self) -> Option<NodeRef<marker::Owned, S>> {
258        Some(NodeRef::new(unsafe { (*self.as_ptr()).right.take()? }))
259    }
260    pub fn set_left(&mut self, node: Option<NodeRef<marker::Owned, S>>) {
261        unsafe { (*self.as_ptr()).left = node.map(|node| node.node) }
262    }
263    pub fn set_right(&mut self, node: Option<NodeRef<marker::Owned, S>>) {
264        unsafe { (*self.as_ptr()).right = node.map(|node| node.node) }
265    }
266}
267
268impl<S> NodeRef<marker::Dying, S>
269where
270    S: SplaySpec,
271{
272    pub unsafe fn into_inner(self) -> NonNull<Node<S::T>> {
273        let node = self.node;
274        unsafe {
275            debug_assert!((*node.as_ptr()).left.is_none());
276            debug_assert!((*node.as_ptr()).right.is_none());
277        }
278        node
279    }
280    pub unsafe fn into_data<A>(self, allocator: &mut A) -> S::T
281    where
282        A: Allocator<Node<S::T>>,
283    {
284        let Node { data, left, right } = allocator.deallocate(self.node);
285        debug_assert!(left.is_none());
286        debug_assert!(right.is_none());
287        data
288    }
289}
290
291impl<S> NodeRef<marker::Owned, S>
292where
293    S: SplaySpec,
294{
295    /// `cmp(key)`: [`Ordering`] between splaying and `key`
296    pub fn splay_by<Seeker>(self, mut seeker: Seeker) -> (Ordering, Self)
297    where
298        Seeker: SplaySeeker<S = S>,
299    {
300        let mut x = self;
301        // let dummy = Node { data: None, left: left_subtree, right: right_subtree };
302        let mut left_subtree: Option<NonNull<Node<S::T>>> = None;
303        let mut right_subtree: Option<NonNull<Node<S::T>>> = None;
304        let mut left_entry = &mut left_subtree;
305        let mut right_entry = &mut right_subtree;
306        let mut stack = vec![];
307
308        macro_rules! add {
309            (@left Some($ptr:ident)) => { add!(@inner Some($ptr.node), left_entry $ptr right); };
310            (@right Some($ptr:ident)) => { add!(@inner Some($ptr.node), right_entry $ptr left); };
311            (@inner $node:expr, $entry:ident $ptr:ident $dir:ident) => {
312                *$entry = $node;
313                if S::has_bottom_up() {
314                    stack.push($ptr.node);
315                }
316                $entry = unsafe { &mut (*$entry.as_mut().unwrap().as_ptr()).$dir };
317            };
318        }
319
320        let root_ord = loop {
321            S::top_down(x.borrow_datamut());
322            match seeker.splay_seek(x.reborrow()) {
323                Ordering::Less => {
324                    if let Some(mut y) = x.borrow_mut().take_left() {
325                        S::top_down(y.borrow_datamut());
326                        match seeker.splay_seek(y.reborrow()) {
327                            Ordering::Less => {
328                                if let Some(mut z) = y.borrow_mut().take_left() {
329                                    S::top_down(z.borrow_datamut());
330                                    x.borrow_mut().set_left(y.borrow_mut().take_right());
331                                    S::bottom_up(x.borrow_datamut());
332                                    y.borrow_mut().set_right(Some(x));
333                                    add!(@right Some(y));
334                                    x = z;
335                                } else {
336                                    add!(@right Some(x));
337                                    x = y;
338                                    break Ordering::Less;
339                                }
340                            }
341                            Ordering::Equal => {
342                                add!(@right Some(x));
343                                x = y;
344                                break Ordering::Equal;
345                            }
346                            Ordering::Greater => {
347                                if let Some(mut z) = y.borrow_mut().take_right() {
348                                    S::top_down(z.borrow_datamut());
349                                    add!(@right Some(x));
350                                    add!(@left Some(y));
351                                    x = z;
352                                } else {
353                                    add!(@right Some(x));
354                                    x = y;
355                                    break Ordering::Greater;
356                                }
357                            }
358                        }
359                    } else {
360                        break Ordering::Less;
361                    }
362                }
363                Ordering::Equal => break Ordering::Equal,
364                Ordering::Greater => {
365                    if let Some(mut y) = x.borrow_mut().take_right() {
366                        S::top_down(y.borrow_datamut());
367                        match seeker.splay_seek(y.reborrow()) {
368                            Ordering::Less => {
369                                if let Some(mut z) = y.borrow_mut().take_left() {
370                                    S::top_down(z.borrow_datamut());
371                                    add!(@left Some(x));
372                                    add!(@right Some(y));
373                                    x = z;
374                                } else {
375                                    add!(@left Some(x));
376                                    x = y;
377                                    break Ordering::Less;
378                                }
379                            }
380                            Ordering::Equal => {
381                                add!(@left Some(x));
382                                x = y;
383                                break Ordering::Equal;
384                            }
385                            Ordering::Greater => {
386                                if let Some(mut z) = y.borrow_mut().take_right() {
387                                    S::top_down(z.borrow_datamut());
388                                    x.borrow_mut().set_right(y.borrow_mut().take_left());
389                                    S::bottom_up(x.borrow_datamut());
390                                    y.borrow_mut().set_left(Some(x));
391                                    add!(@left Some(y));
392                                    x = z;
393                                } else {
394                                    add!(@left Some(x));
395                                    x = y;
396                                    break Ordering::Greater;
397                                }
398                            }
399                        }
400                    } else {
401                        break Ordering::Greater;
402                    }
403                }
404            }
405        };
406        *left_entry = x.borrow_mut().take_left().map(|node| node.node);
407        *right_entry = x.borrow_mut().take_right().map(|node| node.node);
408        unsafe {
409            x.borrow_mut()
410                .set_left(left_subtree.map(|node| NodeRef::new_unchecked(node)));
411            x.borrow_mut()
412                .set_right(right_subtree.map(|node| NodeRef::new_unchecked(node)));
413            if S::has_bottom_up() {
414                while let Some(node) = stack.pop() {
415                    S::bottom_up(NodeRef::new_unchecked(node));
416                }
417            }
418        }
419        S::bottom_up(x.borrow_datamut());
420        (root_ord, x)
421    }
422    pub fn insert_left(mut self, mut node: Self) -> Self {
423        if let Some(left) = self.borrow_mut().take_left() {
424            node.borrow_mut().set_left(Some(left));
425            S::bottom_up(self.borrow_datamut());
426        };
427        node.borrow_mut().set_right(Some(self));
428        S::bottom_up(node.borrow_datamut());
429        node
430    }
431    pub fn insert_right(mut self, mut node: Self) -> Self {
432        if let Some(right) = self.borrow_mut().take_right() {
433            node.borrow_mut().set_right(Some(right));
434            S::bottom_up(self.borrow_datamut());
435        }
436        node.borrow_mut().set_left(Some(self));
437        S::bottom_up(node.borrow_datamut());
438        node
439    }
440    pub fn insert_first(self, mut node: Self) -> Self {
441        node.borrow_mut().set_right(Some(self));
442        S::bottom_up(node.borrow_datamut());
443        node
444    }
445    pub fn insert_last(self, mut node: Self) -> Self {
446        node.borrow_mut().set_left(Some(self));
447        S::bottom_up(node.borrow_datamut());
448        node
449    }
450    pub fn merge(mut self, mut other: Self) -> Self {
451        if other.reborrow().left().is_none() {
452            S::top_down(other.borrow_datamut());
453            other.borrow_mut().set_left(Some(self));
454            S::bottom_up(other.borrow_datamut());
455            other
456        } else {
457            self = self.splay_by(SeekRight::new()).1;
458            self.borrow_mut().set_right(Some(other));
459            S::bottom_up(self.borrow_datamut());
460            self
461        }
462    }
463}
464
465impl<S> Root<S>
466where
467    S: SplaySpec,
468{
469    pub fn new(root: Option<NodeRef<marker::Owned, S>>) -> Self {
470        Self { root }
471    }
472    pub unsafe fn from_single_nodes(nodes: Vec<NodeRef<marker::Owned, S>>) -> Self {
473        unsafe { Self::from_single_nodes_inner(&nodes) }
474    }
475    unsafe fn from_single_nodes_inner(nodes: &[NodeRef<marker::Owned, S>]) -> Self {
476        if nodes.is_empty() {
477            Self::new(None)
478        } else {
479            let m = nodes.len() / 2;
480            let left = unsafe { Self::from_single_nodes_inner(&nodes[..m]) };
481            let right = unsafe { Self::from_single_nodes_inner(&nodes[m + 1..]) };
482            let mut node = NodeRef::new(nodes[m].node);
483            node.borrow_mut().set_left(left.root);
484            node.borrow_mut().set_right(right.root);
485            S::bottom_up(node.borrow_datamut());
486            Self::new(Some(node))
487        }
488    }
489    pub fn is_empty(&self) -> bool {
490        self.root.is_none()
491    }
492    pub fn root(&self) -> Option<NodeRef<marker::Immut<'_>, S>> {
493        Some(self.root.as_ref()?.reborrow())
494    }
495    pub fn root_data_mut(&mut self) -> Option<NodeRef<marker::DataMut<'_>, S>> {
496        Some(self.root.as_mut()?.borrow_datamut())
497    }
498    pub fn splay_by<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
499    where
500        Seeker: SplaySeeker<S = S>,
501    {
502        let (ord, root) = self.root.take()?.splay_by(seeker);
503        self.root = Some(root);
504        Some(ord)
505    }
506    pub fn insert_left(&mut self, mut node: NodeRef<marker::Owned, S>) {
507        self.root = Some(match self.root.take() {
508            Some(root) => root.insert_left(node),
509            None => {
510                S::bottom_up(node.borrow_datamut());
511                node
512            }
513        });
514    }
515    pub fn insert_right(&mut self, mut node: NodeRef<marker::Owned, S>) {
516        self.root = Some(match self.root.take() {
517            Some(root) => root.insert_right(node),
518            None => {
519                S::bottom_up(node.borrow_datamut());
520                node
521            }
522        });
523    }
524    pub fn insert_first(&mut self, mut node: NodeRef<marker::Owned, S>) {
525        self.root = Some(match self.root.take() {
526            Some(root) => root.insert_first(node),
527            None => {
528                S::bottom_up(node.borrow_datamut());
529                node
530            }
531        });
532    }
533    pub fn insert_last(&mut self, mut node: NodeRef<marker::Owned, S>) {
534        self.root = Some(match self.root.take() {
535            Some(root) => root.insert_last(node),
536            None => {
537                S::bottom_up(node.borrow_datamut());
538                node
539            }
540        });
541    }
542    pub fn take_root(&mut self) -> Option<NodeRef<marker::Owned, S>> {
543        let mut root = self.root.take()?;
544        let right = root.borrow_mut().take_right();
545        self.root = root.borrow_mut().take_left();
546        self.append(&mut Self::new(right));
547        Some(root)
548    }
549    pub fn take_first(&mut self) -> Option<NodeRef<marker::Owned, S>> {
550        let mut root = self.root.take()?.splay_by(SeekLeft::new()).1;
551        let right = root.borrow_mut().take_right();
552        self.root = right;
553        Some(root)
554    }
555    pub fn take_last(&mut self) -> Option<NodeRef<marker::Owned, S>> {
556        let mut root = self.root.take()?.splay_by(SeekRight::new()).1;
557        let left = root.borrow_mut().take_left();
558        self.root = left;
559        Some(root)
560    }
561    pub fn split_left(&mut self) -> Option<NodeRef<marker::Owned, S>> {
562        let root = self.root.as_mut()?;
563        let left = root.borrow_mut().take_left();
564        S::bottom_up(root.borrow_datamut());
565        left
566    }
567    pub fn split_right(&mut self) -> Option<NodeRef<marker::Owned, S>> {
568        let root = self.root.as_mut()?;
569        let right = root.borrow_mut().take_right();
570        S::bottom_up(root.borrow_datamut());
571        right
572    }
573    pub fn split_left_eq(&mut self) -> Option<NodeRef<marker::Owned, S>> {
574        let right = self.split_right();
575        replace(&mut self.root, right)
576    }
577    pub fn split_right_eq(&mut self) -> Option<NodeRef<marker::Owned, S>> {
578        let left = self.split_left();
579        replace(&mut self.root, left)
580    }
581    pub fn append(&mut self, other: &mut Self) {
582        self.root = match (self.root.take(), other.root.take()) {
583            (Some(node), None) | (None, Some(node)) => Some(node),
584            (Some(left), Some(right)) => Some(left.merge(right)),
585            (None, None) => None,
586        }
587    }
588    pub fn range<Seeker>(&mut self, start: Bound<Seeker>, end: Bound<Seeker>) -> NodeRange<'_, S>
589    where
590        Seeker: SplaySeeker<S = S>,
591    {
592        if self.is_empty() {
593            return NodeRange::new(self);
594        }
595        let right = match end {
596            Bound::Included(seeker) => match self.splay_by(seeker).unwrap() {
597                Ordering::Greater | Ordering::Equal => self.split_right(),
598                Ordering::Less => self.split_right_eq(),
599            },
600            Bound::Excluded(seeker) => match self.splay_by(seeker).unwrap() {
601                Ordering::Greater => self.split_right(),
602                Ordering::Less | Ordering::Equal => self.split_right_eq(),
603            },
604            Bound::Unbounded => None,
605        };
606        if self.is_empty() {
607            return NodeRange::three_way(None, self, right);
608        }
609        let left = match start {
610            Bound::Included(seeker) => match self.splay_by(seeker).unwrap() {
611                Ordering::Less | Ordering::Equal => self.split_left(),
612                Ordering::Greater => self.split_left_eq(),
613            },
614            Bound::Excluded(seeker) => match self.splay_by(seeker).unwrap() {
615                Ordering::Less => self.split_left(),
616                Ordering::Greater | Ordering::Equal => self.split_left_eq(),
617            },
618            Bound::Unbounded => None,
619        };
620        NodeRange::three_way(left, self, right)
621    }
622}
623
624impl<S> Debug for Root<S>
625where
626    S: SplaySpec,
627    S::T: Debug,
628{
629    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630        fn fmt_recurse<'a, S>(
631            node: NodeRef<marker::Immut<'a>, S>,
632            f: &mut fmt::Formatter<'_>,
633        ) -> fmt::Result
634        where
635            S: SplaySpec,
636            S::T: 'a + Debug,
637        {
638            write!(f, "[")?;
639            if let Some(left) = node.left() {
640                fmt_recurse(left, f)?;
641            }
642            node.data().fmt(f)?;
643            if let Some(right) = node.right() {
644                fmt_recurse(right, f)?;
645            }
646            write!(f, "]")?;
647            Ok(())
648        }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sized_map.rs (line 74)
73    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
74        let lsize = node.left().map(|l| l.data().1).unwrap_or_default();
75        let ord = self.index.cmp(&lsize);
76        if matches!(ord, Ordering::Greater) {
77            self.index -= lsize + 1;
78        }
79        ord
80    }
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 136)
135    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
136        let lsize = node.left().map(|l| l.data().size).unwrap_or_default();
137        let ord = self.index.cmp(&lsize);
138        if matches!(ord, Ordering::Greater) {
139            self.index -= lsize + 1;
140        }
141        ord
142    }
143}
144
145struct SeekByAccCond<F, T>
146where
147    T: MonoidAction,
148{
149    acc: T::Agg,
150    f: F,
151    _marker: PhantomData<fn() -> T>,
152}
153impl<F, T> SeekByAccCond<F, T>
154where
155    T: MonoidAction,
156{
157    fn new(f: F) -> Self {
158        Self {
159            acc: T::agg_unit(),
160            f,
161            _marker: PhantomData,
162        }
163    }
164}
165impl<F, T> SplaySeeker for SeekByAccCond<F, T>
166where
167    F: FnMut(&T::Agg) -> bool,
168    T: MonoidAction,
169{
170    type S = LazyAggSplay<T>;
171    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
172        if let Some(lagg) = node.left().map(|l| &l.data().agg) {
173            let nacc = T::agg_operate(&self.acc, lagg);
174            if (self.f)(&nacc) {
175                return Ordering::Less;
176            }
177            self.acc = nacc;
178        };
179        self.acc = T::agg_operate(&self.acc, &T::single_agg(&node.data().key));
180        if (self.f)(&self.acc) {
181            Ordering::Equal
182        } else {
183            Ordering::Greater
184        }
185    }
186}
187
188struct SeekByRaccCond<F, T>
189where
190    T: MonoidAction,
191{
192    acc: T::Agg,
193    f: F,
194    _marker: PhantomData<fn() -> T>,
195}
196impl<F, T> SeekByRaccCond<F, T>
197where
198    T: MonoidAction,
199{
200    fn new(f: F) -> Self {
201        Self {
202            acc: T::agg_unit(),
203            f,
204            _marker: PhantomData,
205        }
206    }
207}
208impl<F, T> SplaySeeker for SeekByRaccCond<F, T>
209where
210    F: FnMut(&T::Agg) -> bool,
211    T: MonoidAction,
212{
213    type S = LazyAggSplay<T>;
214    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
215        if let Some(lagg) = node.right().map(|r| &r.data().agg) {
216            let nacc = T::agg_operate(lagg, &self.acc);
217            if (self.f)(&nacc) {
218                return Ordering::Greater;
219            }
220            self.acc = nacc;
221        };
222        self.acc = T::agg_operate(&T::single_agg(&node.data().key), &self.acc);
223        if (self.f)(&self.acc) {
224            Ordering::Equal
225        } else {
226            Ordering::Less
227        }
228    }
229}
230
231pub struct SplaySequence<T, A = MemoryPool<Node<LazyAggElement<T>>>>
232where
233    T: MonoidAction,
234    A: Allocator<Node<LazyAggElement<T>>>,
235{
236    root: Root<LazyAggSplay<T>>,
237    length: usize,
238    alloc: ManuallyDrop<A>,
239}
240
241impl<T, A> Debug for SplaySequence<T, A>
242where
243    T: MonoidAction,
244    T::Key: Debug,
245    T::Agg: Debug,
246    T::Act: Debug,
247    A: Allocator<Node<LazyAggElement<T>>>,
248{
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_struct("SplayMap")
251            .field("root", &self.root)
252            .field("length", &self.length)
253            .finish()
254    }
255}
256
257impl<T, A> Drop for SplaySequence<T, A>
258where
259    T: MonoidAction,
260    A: Allocator<Node<LazyAggElement<T>>>,
261{
262    fn drop(&mut self) {
263        unsafe {
264            while let Some(node) = self.root.take_first() {
265                self.alloc.deallocate(node.into_dying().into_inner());
266            }
267            ManuallyDrop::drop(&mut self.alloc);
268        }
269    }
270}
271
272impl<T, A> Default for SplaySequence<T, A>
273where
274    T: MonoidAction,
275    A: Allocator<Node<LazyAggElement<T>>> + Default,
276{
277    fn default() -> Self {
278        Self {
279            root: Root::default(),
280            length: 0,
281            alloc: Default::default(),
282        }
283    }
284}
285
286impl<T> SplaySequence<T>
287where
288    T: MonoidAction,
289{
290    pub fn new() -> Self {
291        Default::default()
292    }
293    pub fn with_capacity(capacity: usize) -> Self {
294        Self {
295            root: Root::default(),
296            length: 0,
297            alloc: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
298        }
299    }
300    pub fn len(&self) -> usize {
301        self.length
302    }
303    pub fn is_empty(&self) -> bool {
304        self.length == 0
305    }
306}
307impl<T, A> SplaySequence<T, A>
308where
309    T: MonoidAction,
310    A: Allocator<Node<LazyAggElement<T>>>,
311{
312    fn range<R>(&mut self, range: R) -> NodeRange<'_, LazyAggSplay<T>>
313    where
314        R: RangeBounds<usize>,
315    {
316        let start = match range.start_bound() {
317            Bound::Included(&index) => Bound::Included(SeekBySize::new(index)),
318            Bound::Excluded(&index) => Bound::Excluded(SeekBySize::new(index)),
319            Bound::Unbounded => Bound::Unbounded,
320        };
321        let end = match range.end_bound() {
322            Bound::Included(&index) => Bound::Included(SeekBySize::new(index)),
323            Bound::Excluded(&index) => Bound::Excluded(SeekBySize::new(index)),
324            Bound::Unbounded => Bound::Unbounded,
325        };
326        self.root.range(start, end)
327    }
328    pub fn update<R>(&mut self, range: R, x: T::Act)
329    where
330        R: RangeBounds<usize>,
331    {
332        if let Some(root) = self.range(range).root_mut().root_data_mut() {
333            LazyAggSplay::<T>::update_lazy(root, &x);
334        }
335    }
336    pub fn fold<R>(&mut self, range: R) -> T::Agg
337    where
338        R: RangeBounds<usize>,
339    {
340        if let Some(root) = self.range(range).root().root() {
341            root.data().agg.clone()
342        } else {
343            T::agg_unit()
344        }
345    }
346    pub fn reverse<R>(&mut self, range: R)
347    where
348        R: RangeBounds<usize>,
349    {
350        if let Some(root) = self.range(range).root_mut().root_data_mut() {
351            LazyAggSplay::<T>::reverse(root);
352        }
353    }
354    pub fn get(&mut self, index: usize) -> Option<&T::Key> {
355        self.root.splay_by(SeekBySize::new(index))?;
356        self.root.root().map(|root| &root.data().key)
357    }
358    pub fn modify<F>(&mut self, index: usize, f: F)
359    where
360        F: FnOnce(&T::Key) -> T::Key,
361    {
362        self.root.splay_by(SeekBySize::new(index)).unwrap();
363        let data = self.root.root_data_mut().unwrap().data_mut();
364        data.key = f(&data.key);
365        LazyAggSplay::<T>::bottom_up(self.root.root_data_mut().unwrap());
366    }
367    pub fn insert(&mut self, index: usize, x: T::Key) {
368        assert!(index <= self.length);
369        self.root.splay_by(SeekBySize::new(index));
370        let agg = T::single_agg(&x);
371        unsafe {
372            let node = NodeRef::from_data(
373                LazyAggElement {
374                    key: x,
375                    agg,
376                    lazy: T::act_unit(),
377                    size: 1,
378                    rev: false,
379                },
380                self.alloc.deref_mut(),
381            );
382            if index == self.length {
383                self.root.insert_right(node);
384            } else {
385                self.root.insert_left(node);
386            }
387        }
388        self.length += 1;
389    }
390    pub fn remove(&mut self, index: usize) -> Option<T::Key> {
391        if index >= self.length {
392            return None;
393        }
394        self.root.splay_by(SeekBySize::new(index));
395        self.length -= 1;
396        let node = self.root.take_root().unwrap().into_dying();
397        unsafe { Some(node.into_data(self.alloc.deref_mut()).key) }
398    }
399    pub fn position_acc<R, F>(&mut self, range: R, f: F) -> Option<usize>
400    where
401        R: RangeBounds<usize>,
402        F: FnMut(&T::Agg) -> bool,
403    {
404        let mut range = self.range(range);
405        let ord = range.root_mut().splay_by(SeekByAccCond::new(f));
406        if !matches!(ord, Some(Ordering::Equal)) {
407            return None;
408        }
409        let front_size = range.front().size();
410        let left_size = range.root().left_size();
411        Some(front_size + left_size)
412    }
413    pub fn rposition_acc<R, F>(&mut self, range: R, f: F) -> Option<usize>
414    where
415        R: RangeBounds<usize>,
416        F: FnMut(&T::Agg) -> bool,
417    {
418        let mut range = self.range(range);
419        let ord = range.root_mut().splay_by(SeekByRaccCond::new(f));
420        if !matches!(ord, Some(Ordering::Equal)) {
421            return None;
422        }
423        let front_size = range.front().size();
424        let left_size = range.root().left_size();
425        Some(front_size + left_size)
426    }
427    pub fn rotate_left(&mut self, mid: usize) {
428        assert!(mid <= self.length);
429        if mid != 0 || mid != self.length {
430            self.range(mid..).drop_rotate_left()
431        }
432    }
433    pub fn rotate_right(&mut self, k: usize) {
434        assert!(k <= self.length);
435        self.rotate_left(self.length - k);
436    }
437}
438
439impl<T, A> Extend<T::Key> for SplaySequence<T, A>
440where
441    T: MonoidAction,
442    A: Allocator<Node<LazyAggElement<T>>>,
443{
444    fn extend<I>(&mut self, iter: I)
445    where
446        I: IntoIterator<Item = T::Key>,
447    {
448        let nodes: Vec<_> = unsafe {
449            iter.into_iter()
450                .map(|key| {
451                    let agg = T::single_agg(&key);
452                    NodeRef::from_data(
453                        LazyAggElement {
454                            key,
455                            agg,
456                            lazy: T::act_unit(),
457                            size: 1,
458                            rev: false,
459                        },
460                        self.alloc.deref_mut(),
461                    )
462                })
463                .collect()
464        };
465        self.length += nodes.len();
466        let mut root = unsafe { Root::from_single_nodes(nodes) };
467        self.root.append(&mut root);
468    }
469}
470
471impl<T> Root<LazyAggSplay<T>>
472where
473    T: MonoidAction,
474{
475    fn size(&self) -> usize {
476        self.root().map(|root| root.data().size).unwrap_or_default()
477    }
478    fn left_size(&self) -> usize {
479        self.root()
480            .and_then(|root| root.left().map(|left| left.data().size))
481            .unwrap_or_default()
482    }
Source

pub fn right(&self) -> Option<Self>

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 204)
195    pub fn traverse<F>(self, f: &mut F)
196    where
197        S::T: 'a,
198        F: FnMut(Self),
199    {
200        if let Some(left) = self.clone().left() {
201            left.traverse(f);
202        }
203        f(self);
204        if let Some(right) = self.clone().right() {
205            right.traverse(f);
206        }
207    }
208}
209
210impl<'a, S> NodeRef<marker::DataMut<'a>, S>
211where
212    S: SplaySpec,
213    S::T: 'a,
214{
215    pub fn data(&self) -> &'a S::T {
216        unsafe { &(*self.as_ptr()).data }
217    }
218    pub fn data_mut(&self) -> &'a mut S::T {
219        unsafe { &mut (*self.as_ptr()).data }
220    }
221    pub fn left(&self) -> Option<Self> {
222        unsafe {
223            (*self.as_ptr())
224                .left
225                .map(|node| NodeRef::new_unchecked(node))
226        }
227    }
228    pub fn right(&self) -> Option<Self> {
229        unsafe {
230            (*self.as_ptr())
231                .right
232                .map(|node| NodeRef::new_unchecked(node))
233        }
234    }
235    pub fn reverse(&self) {
236        unsafe {
237            let node = &mut (*self.as_ptr());
238            swap(&mut node.left, &mut node.right);
239        }
240    }
241}
242
243impl<'a, S> NodeRef<marker::Mut<'a>, S>
244where
245    S: SplaySpec,
246    S::T: 'a,
247{
248    pub fn data(self) -> &'a S::T {
249        unsafe { &(*self.as_ptr()).data }
250    }
251    pub fn data_mut(self) -> &'a mut S::T {
252        unsafe { &mut (*self.as_ptr()).data }
253    }
254    pub fn take_left(&mut self) -> Option<NodeRef<marker::Owned, S>> {
255        Some(NodeRef::new(unsafe { (*self.as_ptr()).left.take()? }))
256    }
257    pub fn take_right(&mut self) -> Option<NodeRef<marker::Owned, S>> {
258        Some(NodeRef::new(unsafe { (*self.as_ptr()).right.take()? }))
259    }
260    pub fn set_left(&mut self, node: Option<NodeRef<marker::Owned, S>>) {
261        unsafe { (*self.as_ptr()).left = node.map(|node| node.node) }
262    }
263    pub fn set_right(&mut self, node: Option<NodeRef<marker::Owned, S>>) {
264        unsafe { (*self.as_ptr()).right = node.map(|node| node.node) }
265    }
266}
267
268impl<S> NodeRef<marker::Dying, S>
269where
270    S: SplaySpec,
271{
272    pub unsafe fn into_inner(self) -> NonNull<Node<S::T>> {
273        let node = self.node;
274        unsafe {
275            debug_assert!((*node.as_ptr()).left.is_none());
276            debug_assert!((*node.as_ptr()).right.is_none());
277        }
278        node
279    }
280    pub unsafe fn into_data<A>(self, allocator: &mut A) -> S::T
281    where
282        A: Allocator<Node<S::T>>,
283    {
284        let Node { data, left, right } = allocator.deallocate(self.node);
285        debug_assert!(left.is_none());
286        debug_assert!(right.is_none());
287        data
288    }
289}
290
291impl<S> NodeRef<marker::Owned, S>
292where
293    S: SplaySpec,
294{
295    /// `cmp(key)`: [`Ordering`] between splaying and `key`
296    pub fn splay_by<Seeker>(self, mut seeker: Seeker) -> (Ordering, Self)
297    where
298        Seeker: SplaySeeker<S = S>,
299    {
300        let mut x = self;
301        // let dummy = Node { data: None, left: left_subtree, right: right_subtree };
302        let mut left_subtree: Option<NonNull<Node<S::T>>> = None;
303        let mut right_subtree: Option<NonNull<Node<S::T>>> = None;
304        let mut left_entry = &mut left_subtree;
305        let mut right_entry = &mut right_subtree;
306        let mut stack = vec![];
307
308        macro_rules! add {
309            (@left Some($ptr:ident)) => { add!(@inner Some($ptr.node), left_entry $ptr right); };
310            (@right Some($ptr:ident)) => { add!(@inner Some($ptr.node), right_entry $ptr left); };
311            (@inner $node:expr, $entry:ident $ptr:ident $dir:ident) => {
312                *$entry = $node;
313                if S::has_bottom_up() {
314                    stack.push($ptr.node);
315                }
316                $entry = unsafe { &mut (*$entry.as_mut().unwrap().as_ptr()).$dir };
317            };
318        }
319
320        let root_ord = loop {
321            S::top_down(x.borrow_datamut());
322            match seeker.splay_seek(x.reborrow()) {
323                Ordering::Less => {
324                    if let Some(mut y) = x.borrow_mut().take_left() {
325                        S::top_down(y.borrow_datamut());
326                        match seeker.splay_seek(y.reborrow()) {
327                            Ordering::Less => {
328                                if let Some(mut z) = y.borrow_mut().take_left() {
329                                    S::top_down(z.borrow_datamut());
330                                    x.borrow_mut().set_left(y.borrow_mut().take_right());
331                                    S::bottom_up(x.borrow_datamut());
332                                    y.borrow_mut().set_right(Some(x));
333                                    add!(@right Some(y));
334                                    x = z;
335                                } else {
336                                    add!(@right Some(x));
337                                    x = y;
338                                    break Ordering::Less;
339                                }
340                            }
341                            Ordering::Equal => {
342                                add!(@right Some(x));
343                                x = y;
344                                break Ordering::Equal;
345                            }
346                            Ordering::Greater => {
347                                if let Some(mut z) = y.borrow_mut().take_right() {
348                                    S::top_down(z.borrow_datamut());
349                                    add!(@right Some(x));
350                                    add!(@left Some(y));
351                                    x = z;
352                                } else {
353                                    add!(@right Some(x));
354                                    x = y;
355                                    break Ordering::Greater;
356                                }
357                            }
358                        }
359                    } else {
360                        break Ordering::Less;
361                    }
362                }
363                Ordering::Equal => break Ordering::Equal,
364                Ordering::Greater => {
365                    if let Some(mut y) = x.borrow_mut().take_right() {
366                        S::top_down(y.borrow_datamut());
367                        match seeker.splay_seek(y.reborrow()) {
368                            Ordering::Less => {
369                                if let Some(mut z) = y.borrow_mut().take_left() {
370                                    S::top_down(z.borrow_datamut());
371                                    add!(@left Some(x));
372                                    add!(@right Some(y));
373                                    x = z;
374                                } else {
375                                    add!(@left Some(x));
376                                    x = y;
377                                    break Ordering::Less;
378                                }
379                            }
380                            Ordering::Equal => {
381                                add!(@left Some(x));
382                                x = y;
383                                break Ordering::Equal;
384                            }
385                            Ordering::Greater => {
386                                if let Some(mut z) = y.borrow_mut().take_right() {
387                                    S::top_down(z.borrow_datamut());
388                                    x.borrow_mut().set_right(y.borrow_mut().take_left());
389                                    S::bottom_up(x.borrow_datamut());
390                                    y.borrow_mut().set_left(Some(x));
391                                    add!(@left Some(y));
392                                    x = z;
393                                } else {
394                                    add!(@left Some(x));
395                                    x = y;
396                                    break Ordering::Greater;
397                                }
398                            }
399                        }
400                    } else {
401                        break Ordering::Greater;
402                    }
403                }
404            }
405        };
406        *left_entry = x.borrow_mut().take_left().map(|node| node.node);
407        *right_entry = x.borrow_mut().take_right().map(|node| node.node);
408        unsafe {
409            x.borrow_mut()
410                .set_left(left_subtree.map(|node| NodeRef::new_unchecked(node)));
411            x.borrow_mut()
412                .set_right(right_subtree.map(|node| NodeRef::new_unchecked(node)));
413            if S::has_bottom_up() {
414                while let Some(node) = stack.pop() {
415                    S::bottom_up(NodeRef::new_unchecked(node));
416                }
417            }
418        }
419        S::bottom_up(x.borrow_datamut());
420        (root_ord, x)
421    }
422    pub fn insert_left(mut self, mut node: Self) -> Self {
423        if let Some(left) = self.borrow_mut().take_left() {
424            node.borrow_mut().set_left(Some(left));
425            S::bottom_up(self.borrow_datamut());
426        };
427        node.borrow_mut().set_right(Some(self));
428        S::bottom_up(node.borrow_datamut());
429        node
430    }
431    pub fn insert_right(mut self, mut node: Self) -> Self {
432        if let Some(right) = self.borrow_mut().take_right() {
433            node.borrow_mut().set_right(Some(right));
434            S::bottom_up(self.borrow_datamut());
435        }
436        node.borrow_mut().set_left(Some(self));
437        S::bottom_up(node.borrow_datamut());
438        node
439    }
440    pub fn insert_first(self, mut node: Self) -> Self {
441        node.borrow_mut().set_right(Some(self));
442        S::bottom_up(node.borrow_datamut());
443        node
444    }
445    pub fn insert_last(self, mut node: Self) -> Self {
446        node.borrow_mut().set_left(Some(self));
447        S::bottom_up(node.borrow_datamut());
448        node
449    }
450    pub fn merge(mut self, mut other: Self) -> Self {
451        if other.reborrow().left().is_none() {
452            S::top_down(other.borrow_datamut());
453            other.borrow_mut().set_left(Some(self));
454            S::bottom_up(other.borrow_datamut());
455            other
456        } else {
457            self = self.splay_by(SeekRight::new()).1;
458            self.borrow_mut().set_right(Some(other));
459            S::bottom_up(self.borrow_datamut());
460            self
461        }
462    }
463}
464
465impl<S> Root<S>
466where
467    S: SplaySpec,
468{
469    pub fn new(root: Option<NodeRef<marker::Owned, S>>) -> Self {
470        Self { root }
471    }
472    pub unsafe fn from_single_nodes(nodes: Vec<NodeRef<marker::Owned, S>>) -> Self {
473        unsafe { Self::from_single_nodes_inner(&nodes) }
474    }
475    unsafe fn from_single_nodes_inner(nodes: &[NodeRef<marker::Owned, S>]) -> Self {
476        if nodes.is_empty() {
477            Self::new(None)
478        } else {
479            let m = nodes.len() / 2;
480            let left = unsafe { Self::from_single_nodes_inner(&nodes[..m]) };
481            let right = unsafe { Self::from_single_nodes_inner(&nodes[m + 1..]) };
482            let mut node = NodeRef::new(nodes[m].node);
483            node.borrow_mut().set_left(left.root);
484            node.borrow_mut().set_right(right.root);
485            S::bottom_up(node.borrow_datamut());
486            Self::new(Some(node))
487        }
488    }
489    pub fn is_empty(&self) -> bool {
490        self.root.is_none()
491    }
492    pub fn root(&self) -> Option<NodeRef<marker::Immut<'_>, S>> {
493        Some(self.root.as_ref()?.reborrow())
494    }
495    pub fn root_data_mut(&mut self) -> Option<NodeRef<marker::DataMut<'_>, S>> {
496        Some(self.root.as_mut()?.borrow_datamut())
497    }
498    pub fn splay_by<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
499    where
500        Seeker: SplaySeeker<S = S>,
501    {
502        let (ord, root) = self.root.take()?.splay_by(seeker);
503        self.root = Some(root);
504        Some(ord)
505    }
506    pub fn insert_left(&mut self, mut node: NodeRef<marker::Owned, S>) {
507        self.root = Some(match self.root.take() {
508            Some(root) => root.insert_left(node),
509            None => {
510                S::bottom_up(node.borrow_datamut());
511                node
512            }
513        });
514    }
515    pub fn insert_right(&mut self, mut node: NodeRef<marker::Owned, S>) {
516        self.root = Some(match self.root.take() {
517            Some(root) => root.insert_right(node),
518            None => {
519                S::bottom_up(node.borrow_datamut());
520                node
521            }
522        });
523    }
524    pub fn insert_first(&mut self, mut node: NodeRef<marker::Owned, S>) {
525        self.root = Some(match self.root.take() {
526            Some(root) => root.insert_first(node),
527            None => {
528                S::bottom_up(node.borrow_datamut());
529                node
530            }
531        });
532    }
533    pub fn insert_last(&mut self, mut node: NodeRef<marker::Owned, S>) {
534        self.root = Some(match self.root.take() {
535            Some(root) => root.insert_last(node),
536            None => {
537                S::bottom_up(node.borrow_datamut());
538                node
539            }
540        });
541    }
542    pub fn take_root(&mut self) -> Option<NodeRef<marker::Owned, S>> {
543        let mut root = self.root.take()?;
544        let right = root.borrow_mut().take_right();
545        self.root = root.borrow_mut().take_left();
546        self.append(&mut Self::new(right));
547        Some(root)
548    }
549    pub fn take_first(&mut self) -> Option<NodeRef<marker::Owned, S>> {
550        let mut root = self.root.take()?.splay_by(SeekLeft::new()).1;
551        let right = root.borrow_mut().take_right();
552        self.root = right;
553        Some(root)
554    }
555    pub fn take_last(&mut self) -> Option<NodeRef<marker::Owned, S>> {
556        let mut root = self.root.take()?.splay_by(SeekRight::new()).1;
557        let left = root.borrow_mut().take_left();
558        self.root = left;
559        Some(root)
560    }
561    pub fn split_left(&mut self) -> Option<NodeRef<marker::Owned, S>> {
562        let root = self.root.as_mut()?;
563        let left = root.borrow_mut().take_left();
564        S::bottom_up(root.borrow_datamut());
565        left
566    }
567    pub fn split_right(&mut self) -> Option<NodeRef<marker::Owned, S>> {
568        let root = self.root.as_mut()?;
569        let right = root.borrow_mut().take_right();
570        S::bottom_up(root.borrow_datamut());
571        right
572    }
573    pub fn split_left_eq(&mut self) -> Option<NodeRef<marker::Owned, S>> {
574        let right = self.split_right();
575        replace(&mut self.root, right)
576    }
577    pub fn split_right_eq(&mut self) -> Option<NodeRef<marker::Owned, S>> {
578        let left = self.split_left();
579        replace(&mut self.root, left)
580    }
581    pub fn append(&mut self, other: &mut Self) {
582        self.root = match (self.root.take(), other.root.take()) {
583            (Some(node), None) | (None, Some(node)) => Some(node),
584            (Some(left), Some(right)) => Some(left.merge(right)),
585            (None, None) => None,
586        }
587    }
588    pub fn range<Seeker>(&mut self, start: Bound<Seeker>, end: Bound<Seeker>) -> NodeRange<'_, S>
589    where
590        Seeker: SplaySeeker<S = S>,
591    {
592        if self.is_empty() {
593            return NodeRange::new(self);
594        }
595        let right = match end {
596            Bound::Included(seeker) => match self.splay_by(seeker).unwrap() {
597                Ordering::Greater | Ordering::Equal => self.split_right(),
598                Ordering::Less => self.split_right_eq(),
599            },
600            Bound::Excluded(seeker) => match self.splay_by(seeker).unwrap() {
601                Ordering::Greater => self.split_right(),
602                Ordering::Less | Ordering::Equal => self.split_right_eq(),
603            },
604            Bound::Unbounded => None,
605        };
606        if self.is_empty() {
607            return NodeRange::three_way(None, self, right);
608        }
609        let left = match start {
610            Bound::Included(seeker) => match self.splay_by(seeker).unwrap() {
611                Ordering::Less | Ordering::Equal => self.split_left(),
612                Ordering::Greater => self.split_left_eq(),
613            },
614            Bound::Excluded(seeker) => match self.splay_by(seeker).unwrap() {
615                Ordering::Less => self.split_left(),
616                Ordering::Greater | Ordering::Equal => self.split_left_eq(),
617            },
618            Bound::Unbounded => None,
619        };
620        NodeRange::three_way(left, self, right)
621    }
622}
623
624impl<S> Debug for Root<S>
625where
626    S: SplaySpec,
627    S::T: Debug,
628{
629    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630        fn fmt_recurse<'a, S>(
631            node: NodeRef<marker::Immut<'a>, S>,
632            f: &mut fmt::Formatter<'_>,
633        ) -> fmt::Result
634        where
635            S: SplaySpec,
636            S::T: 'a + Debug,
637        {
638            write!(f, "[")?;
639            if let Some(left) = node.left() {
640                fmt_recurse(left, f)?;
641            }
642            node.data().fmt(f)?;
643            if let Some(right) = node.right() {
644                fmt_recurse(right, f)?;
645            }
646            write!(f, "]")?;
647            Ok(())
648        }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 215)
214    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
215        if let Some(lagg) = node.right().map(|r| &r.data().agg) {
216            let nacc = T::agg_operate(lagg, &self.acc);
217            if (self.f)(&nacc) {
218                return Ordering::Greater;
219            }
220            self.acc = nacc;
221        };
222        self.acc = T::agg_operate(&T::single_agg(&node.data().key), &self.acc);
223        if (self.f)(&self.acc) {
224            Ordering::Equal
225        } else {
226            Ordering::Less
227        }
228    }
Source

pub fn traverse<F>(self, f: &mut F)
where S::T: 'a, F: FnMut(Self),

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 201)
195    pub fn traverse<F>(self, f: &mut F)
196    where
197        S::T: 'a,
198        F: FnMut(Self),
199    {
200        if let Some(left) = self.clone().left() {
201            left.traverse(f);
202        }
203        f(self);
204        if let Some(right) = self.clone().right() {
205            right.traverse(f);
206        }
207    }
Source§

impl<'a, S> NodeRef<DataMut<'a>, S>
where S: SplaySpec, S::T: 'a,

Source

pub fn data(&self) -> &'a S::T

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/sized_map.rs (line 24)
23    fn bottom_up(node: NodeRef<marker::DataMut<'_>, Self>) {
24        let l = node.left().map(|p| p.data().1).unwrap_or_default();
25        let r = node.right().map(|p| p.data().1).unwrap_or_default();
26        node.data_mut().1 = l + r + 1;
27    }
28}
29
30struct SeekByKey<'a, K, V, Q>
31where
32    Q: ?Sized,
33{
34    key: &'a Q,
35    _marker: PhantomData<fn() -> (K, V)>,
36}
37impl<'a, K, V, Q> SeekByKey<'a, K, V, Q>
38where
39    Q: ?Sized,
40{
41    fn new(key: &'a Q) -> Self {
42        Self {
43            key,
44            _marker: PhantomData,
45        }
46    }
47}
48impl<K, V, Q> SplaySeeker for SeekByKey<'_, K, V, Q>
49where
50    K: Borrow<Q>,
51    Q: Ord + ?Sized,
52{
53    type S = SizedSplay<(K, V)>;
54    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
55        self.key.cmp((node.data().0).0.borrow())
56    }
57}
58
59struct SeekBySize<K, V> {
60    index: usize,
61    _marker: PhantomData<fn() -> (K, V)>,
62}
63impl<K, V> SeekBySize<K, V> {
64    fn new(index: usize) -> Self {
65        Self {
66            index,
67            _marker: PhantomData,
68        }
69    }
70}
71impl<K, V> SplaySeeker for SeekBySize<K, V> {
72    type S = SizedSplay<(K, V)>;
73    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
74        let lsize = node.left().map(|l| l.data().1).unwrap_or_default();
75        let ord = self.index.cmp(&lsize);
76        if matches!(ord, Ordering::Greater) {
77            self.index -= lsize + 1;
78        }
79        ord
80    }
81}
82
83pub struct SplayMap<K, V, A = MemoryPool<Node<((K, V), usize)>>>
84where
85    A: Allocator<Node<((K, V), usize)>>,
86{
87    root: Root<SizedSplay<(K, V)>>,
88    length: usize,
89    alloc: ManuallyDrop<A>,
90}
91
92impl<K, V, A> Debug for SplayMap<K, V, A>
93where
94    K: Debug,
95    V: Debug,
96    A: Allocator<Node<((K, V), usize)>>,
97{
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.debug_struct("SplayMap")
100            .field("root", &self.root)
101            .field("length", &self.length)
102            .finish()
103    }
104}
105
106impl<K, V, A> Drop for SplayMap<K, V, A>
107where
108    A: Allocator<Node<((K, V), usize)>>,
109{
110    fn drop(&mut self) {
111        unsafe {
112            while let Some(node) = self.root.take_first() {
113                self.alloc.deallocate(node.into_dying().into_inner());
114            }
115            ManuallyDrop::drop(&mut self.alloc);
116        }
117    }
118}
119
120impl<K, V, A> Default for SplayMap<K, V, A>
121where
122    A: Allocator<Node<((K, V), usize)>> + Default,
123{
124    fn default() -> Self {
125        Self {
126            root: Root::default(),
127            length: 0,
128            alloc: Default::default(),
129        }
130    }
131}
132
133impl<K, V> SplayMap<K, V> {
134    pub fn new() -> Self {
135        Default::default()
136    }
137    pub fn with_capacity(capacity: usize) -> Self {
138        Self {
139            root: Root::default(),
140            length: 0,
141            alloc: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
142        }
143    }
144}
145impl<K, V, A> SplayMap<K, V, A>
146where
147    A: Allocator<Node<((K, V), usize)>>,
148{
149    pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
150    where
151        K: Borrow<Q>,
152        Q: Ord + ?Sized,
153    {
154        self.get_key_value(key).map(|(_, v)| v)
155    }
156    fn splay_by_key<Q>(&mut self, key: &Q) -> Option<Ordering>
157    where
158        K: Borrow<Q>,
159        Q: Ord + ?Sized,
160    {
161        self.root.splay_by(SeekByKey::new(key))
162    }
163    pub fn get_key_value<Q>(&mut self, key: &Q) -> Option<(&K, &V)>
164    where
165        K: Borrow<Q>,
166        Q: Ord + ?Sized,
167    {
168        if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
169            return None;
170        }
171        self.root.root().map(|node| {
172            let ((k, v), _) = node.data();
173            (k, v)
174        })
175    }
176    fn splay_at(&mut self, index: usize) -> Option<Ordering> {
177        self.root.splay_by(SeekBySize::new(index))
178    }
179    pub fn get_key_value_at(&mut self, index: usize) -> Option<(&K, &V)> {
180        if index >= self.length {
181            return None;
182        }
183        self.splay_at(index);
184        self.root.root().map(|node| {
185            let ((k, v), _) = node.data();
186            (k, v)
187        })
188    }
189    pub fn insert(&mut self, key: K, value: V) -> Option<V>
190    where
191        K: Ord,
192    {
193        let ord = self.splay_by_key(&key);
194        self.length += (ord != Some(Ordering::Equal)) as usize;
195        match ord {
196            Some(Ordering::Equal) => {
197                return Some(replace(
198                    &mut (self.root.root_data_mut().unwrap().data_mut().0).1,
199                    value,
200                ));
201            }
202            Some(Ordering::Less) => unsafe {
203                self.root.insert_left(NodeRef::from_data(
204                    ((key, value), 1),
205                    self.alloc.deref_mut(),
206                ));
207            },
208            _ => unsafe {
209                self.root.insert_right(NodeRef::from_data(
210                    ((key, value), 1),
211                    self.alloc.deref_mut(),
212                ));
213            },
214        }
215        None
216    }
217    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
218    where
219        K: Borrow<Q>,
220        Q: Ord + ?Sized,
221    {
222        if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
223            return None;
224        }
225        self.length -= 1;
226        let node = self.root.take_root().unwrap().into_dying();
227        unsafe { Some((node.into_data(self.alloc.deref_mut()).0).1) }
228    }
229    pub fn remove_at(&mut self, index: usize) -> Option<(K, V)> {
230        if index >= self.length {
231            return None;
232        }
233        self.splay_at(index);
234        self.length -= 1;
235        let node = self.root.take_root().unwrap().into_dying();
236        unsafe { Some(node.into_data(self.alloc.deref_mut()).0) }
237    }
238    pub fn len(&self) -> usize {
239        self.length
240    }
241    pub fn is_empty(&self) -> bool {
242        self.len() == 0
243    }
244    pub fn iter(&mut self) -> Iter<'_, K, V> {
245        Iter {
246            iter: NodeRange::new(&mut self.root),
247        }
248    }
249    pub fn range<Q, R>(&mut self, range: R) -> Iter<'_, K, V>
250    where
251        K: Borrow<Q>,
252        Q: Ord + ?Sized,
253        R: RangeBounds<Q>,
254    {
255        let start = match range.start_bound() {
256            Bound::Included(key) => Bound::Included(SeekByKey::new(key)),
257            Bound::Excluded(key) => Bound::Excluded(SeekByKey::new(key)),
258            Bound::Unbounded => Bound::Unbounded,
259        };
260        let end = match range.end_bound() {
261            Bound::Included(key) => Bound::Included(SeekByKey::new(key)),
262            Bound::Excluded(key) => Bound::Excluded(SeekByKey::new(key)),
263            Bound::Unbounded => Bound::Unbounded,
264        };
265        Iter {
266            iter: self.root.range(start, end),
267        }
268    }
269    pub fn range_at<R>(&mut self, range: R) -> Iter<'_, K, V>
270    where
271        R: RangeBounds<usize>,
272    {
273        let start = match range.start_bound() {
274            Bound::Included(&index) => Bound::Included(SeekBySize::new(index)),
275            Bound::Excluded(&index) => Bound::Excluded(SeekBySize::new(index)),
276            Bound::Unbounded => Bound::Unbounded,
277        };
278        let end = match range.end_bound() {
279            Bound::Included(&index) => Bound::Included(SeekBySize::new(index)),
280            Bound::Excluded(&index) => Bound::Excluded(SeekBySize::new(index)),
281            Bound::Unbounded => Bound::Unbounded,
282        };
283        Iter {
284            iter: self.root.range(start, end),
285        }
286    }
287}
288
289#[derive(Debug)]
290pub struct Iter<'a, K, V> {
291    iter: NodeRange<'a, SizedSplay<(K, V)>>,
292}
293impl<K, V> Iterator for Iter<'_, K, V>
294where
295    K: Clone,
296    V: Clone,
297{
298    type Item = (K, V);
299    fn next(&mut self) -> Option<Self::Item> {
300        self.iter.next_checked().map(|node| node.data().0.clone())
301    }
302    fn last(mut self) -> Option<Self::Item> {
303        self.next_back()
304    }
305    fn min(mut self) -> Option<Self::Item> {
306        self.next()
307    }
308    fn max(mut self) -> Option<Self::Item> {
309        self.next_back()
310    }
311}
312impl<K, V> FusedIterator for Iter<'_, K, V>
313where
314    K: Clone,
315    V: Clone,
316{
317}
318impl<K, V> DoubleEndedIterator for Iter<'_, K, V>
319where
320    K: Clone,
321    V: Clone,
322{
323    fn next_back(&mut self) -> Option<Self::Item> {
324        self.iter
325            .next_back_checked()
326            .map(|node| node.data().0.clone())
327    }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 51)
49    pub fn update_lazy(mut node: NodeRef<marker::DataMut<'_>, Self>, lazy: &T::Act) {
50        T::act_operate_assign(&mut node.data_mut().lazy, lazy);
51        node.data_mut().key = T::act_key(&node.data().key, lazy);
52        if let Some(nxlazy) = T::act_agg(&node.data().agg, lazy) {
53            node.data_mut().agg = nxlazy;
54        } else {
55            node = Self::propagate(node);
56            Self::recalc(node);
57        }
58    }
59    pub fn reverse(node: NodeRef<marker::DataMut<'_>, Self>) {
60        node.reverse();
61        T::toggle(&mut node.data_mut().agg);
62        node.data_mut().rev ^= true;
63    }
64    fn propagate(node: NodeRef<marker::DataMut<'_>, Self>) -> NodeRef<marker::DataMut<'_>, Self> {
65        let lazy = replace(&mut node.data_mut().lazy, T::act_unit());
66        if let Some(left) = node.left() {
67            Self::update_lazy(left, &lazy);
68        }
69        if let Some(right) = node.right() {
70            Self::update_lazy(right, &lazy);
71        }
72        if replace(&mut node.data_mut().rev, false) {
73            if let Some(left) = node.left() {
74                Self::reverse(left);
75            }
76            if let Some(right) = node.right() {
77                Self::reverse(right);
78            }
79        }
80        node
81    }
82    fn recalc(node: NodeRef<marker::DataMut<'_>, Self>) -> NodeRef<marker::DataMut<'_>, Self> {
83        let mut agg = T::single_agg(&node.data().key);
84        let mut size = 1;
85        if let Some(left) = node.left() {
86            let data = left.data();
87            agg = T::agg_operate(&data.agg, &agg);
88            // agg = <T::AggMonoid as Magma>::operate(&data.agg, &agg);
89            size += data.size;
90        }
91        if let Some(right) = node.right() {
92            let data = right.data();
93            agg = T::agg_operate(&agg, &data.agg);
94            size += data.size;
95        }
96        let data = node.data_mut();
97        data.agg = agg;
98        data.size = size;
99        node
100    }
Source

pub fn data_mut(&self) -> &'a mut S::T

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/sized_map.rs (line 26)
23    fn bottom_up(node: NodeRef<marker::DataMut<'_>, Self>) {
24        let l = node.left().map(|p| p.data().1).unwrap_or_default();
25        let r = node.right().map(|p| p.data().1).unwrap_or_default();
26        node.data_mut().1 = l + r + 1;
27    }
28}
29
30struct SeekByKey<'a, K, V, Q>
31where
32    Q: ?Sized,
33{
34    key: &'a Q,
35    _marker: PhantomData<fn() -> (K, V)>,
36}
37impl<'a, K, V, Q> SeekByKey<'a, K, V, Q>
38where
39    Q: ?Sized,
40{
41    fn new(key: &'a Q) -> Self {
42        Self {
43            key,
44            _marker: PhantomData,
45        }
46    }
47}
48impl<K, V, Q> SplaySeeker for SeekByKey<'_, K, V, Q>
49where
50    K: Borrow<Q>,
51    Q: Ord + ?Sized,
52{
53    type S = SizedSplay<(K, V)>;
54    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
55        self.key.cmp((node.data().0).0.borrow())
56    }
57}
58
59struct SeekBySize<K, V> {
60    index: usize,
61    _marker: PhantomData<fn() -> (K, V)>,
62}
63impl<K, V> SeekBySize<K, V> {
64    fn new(index: usize) -> Self {
65        Self {
66            index,
67            _marker: PhantomData,
68        }
69    }
70}
71impl<K, V> SplaySeeker for SeekBySize<K, V> {
72    type S = SizedSplay<(K, V)>;
73    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
74        let lsize = node.left().map(|l| l.data().1).unwrap_or_default();
75        let ord = self.index.cmp(&lsize);
76        if matches!(ord, Ordering::Greater) {
77            self.index -= lsize + 1;
78        }
79        ord
80    }
81}
82
83pub struct SplayMap<K, V, A = MemoryPool<Node<((K, V), usize)>>>
84where
85    A: Allocator<Node<((K, V), usize)>>,
86{
87    root: Root<SizedSplay<(K, V)>>,
88    length: usize,
89    alloc: ManuallyDrop<A>,
90}
91
92impl<K, V, A> Debug for SplayMap<K, V, A>
93where
94    K: Debug,
95    V: Debug,
96    A: Allocator<Node<((K, V), usize)>>,
97{
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.debug_struct("SplayMap")
100            .field("root", &self.root)
101            .field("length", &self.length)
102            .finish()
103    }
104}
105
106impl<K, V, A> Drop for SplayMap<K, V, A>
107where
108    A: Allocator<Node<((K, V), usize)>>,
109{
110    fn drop(&mut self) {
111        unsafe {
112            while let Some(node) = self.root.take_first() {
113                self.alloc.deallocate(node.into_dying().into_inner());
114            }
115            ManuallyDrop::drop(&mut self.alloc);
116        }
117    }
118}
119
120impl<K, V, A> Default for SplayMap<K, V, A>
121where
122    A: Allocator<Node<((K, V), usize)>> + Default,
123{
124    fn default() -> Self {
125        Self {
126            root: Root::default(),
127            length: 0,
128            alloc: Default::default(),
129        }
130    }
131}
132
133impl<K, V> SplayMap<K, V> {
134    pub fn new() -> Self {
135        Default::default()
136    }
137    pub fn with_capacity(capacity: usize) -> Self {
138        Self {
139            root: Root::default(),
140            length: 0,
141            alloc: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
142        }
143    }
144}
145impl<K, V, A> SplayMap<K, V, A>
146where
147    A: Allocator<Node<((K, V), usize)>>,
148{
149    pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
150    where
151        K: Borrow<Q>,
152        Q: Ord + ?Sized,
153    {
154        self.get_key_value(key).map(|(_, v)| v)
155    }
156    fn splay_by_key<Q>(&mut self, key: &Q) -> Option<Ordering>
157    where
158        K: Borrow<Q>,
159        Q: Ord + ?Sized,
160    {
161        self.root.splay_by(SeekByKey::new(key))
162    }
163    pub fn get_key_value<Q>(&mut self, key: &Q) -> Option<(&K, &V)>
164    where
165        K: Borrow<Q>,
166        Q: Ord + ?Sized,
167    {
168        if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
169            return None;
170        }
171        self.root.root().map(|node| {
172            let ((k, v), _) = node.data();
173            (k, v)
174        })
175    }
176    fn splay_at(&mut self, index: usize) -> Option<Ordering> {
177        self.root.splay_by(SeekBySize::new(index))
178    }
179    pub fn get_key_value_at(&mut self, index: usize) -> Option<(&K, &V)> {
180        if index >= self.length {
181            return None;
182        }
183        self.splay_at(index);
184        self.root.root().map(|node| {
185            let ((k, v), _) = node.data();
186            (k, v)
187        })
188    }
189    pub fn insert(&mut self, key: K, value: V) -> Option<V>
190    where
191        K: Ord,
192    {
193        let ord = self.splay_by_key(&key);
194        self.length += (ord != Some(Ordering::Equal)) as usize;
195        match ord {
196            Some(Ordering::Equal) => {
197                return Some(replace(
198                    &mut (self.root.root_data_mut().unwrap().data_mut().0).1,
199                    value,
200                ));
201            }
202            Some(Ordering::Less) => unsafe {
203                self.root.insert_left(NodeRef::from_data(
204                    ((key, value), 1),
205                    self.alloc.deref_mut(),
206                ));
207            },
208            _ => unsafe {
209                self.root.insert_right(NodeRef::from_data(
210                    ((key, value), 1),
211                    self.alloc.deref_mut(),
212                ));
213            },
214        }
215        None
216    }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 50)
49    pub fn update_lazy(mut node: NodeRef<marker::DataMut<'_>, Self>, lazy: &T::Act) {
50        T::act_operate_assign(&mut node.data_mut().lazy, lazy);
51        node.data_mut().key = T::act_key(&node.data().key, lazy);
52        if let Some(nxlazy) = T::act_agg(&node.data().agg, lazy) {
53            node.data_mut().agg = nxlazy;
54        } else {
55            node = Self::propagate(node);
56            Self::recalc(node);
57        }
58    }
59    pub fn reverse(node: NodeRef<marker::DataMut<'_>, Self>) {
60        node.reverse();
61        T::toggle(&mut node.data_mut().agg);
62        node.data_mut().rev ^= true;
63    }
64    fn propagate(node: NodeRef<marker::DataMut<'_>, Self>) -> NodeRef<marker::DataMut<'_>, Self> {
65        let lazy = replace(&mut node.data_mut().lazy, T::act_unit());
66        if let Some(left) = node.left() {
67            Self::update_lazy(left, &lazy);
68        }
69        if let Some(right) = node.right() {
70            Self::update_lazy(right, &lazy);
71        }
72        if replace(&mut node.data_mut().rev, false) {
73            if let Some(left) = node.left() {
74                Self::reverse(left);
75            }
76            if let Some(right) = node.right() {
77                Self::reverse(right);
78            }
79        }
80        node
81    }
82    fn recalc(node: NodeRef<marker::DataMut<'_>, Self>) -> NodeRef<marker::DataMut<'_>, Self> {
83        let mut agg = T::single_agg(&node.data().key);
84        let mut size = 1;
85        if let Some(left) = node.left() {
86            let data = left.data();
87            agg = T::agg_operate(&data.agg, &agg);
88            // agg = <T::AggMonoid as Magma>::operate(&data.agg, &agg);
89            size += data.size;
90        }
91        if let Some(right) = node.right() {
92            let data = right.data();
93            agg = T::agg_operate(&agg, &data.agg);
94            size += data.size;
95        }
96        let data = node.data_mut();
97        data.agg = agg;
98        data.size = size;
99        node
100    }
101}
102impl<T> SplaySpec for LazyAggSplay<T>
103where
104    T: MonoidAction,
105{
106    type T = LazyAggElement<T>;
107    fn has_bottom_up() -> bool {
108        true
109    }
110    fn top_down(node: NodeRef<marker::DataMut<'_>, Self>) {
111        Self::propagate(node);
112    }
113    fn bottom_up(node: NodeRef<marker::DataMut<'_>, Self>) {
114        Self::recalc(node);
115    }
116}
117
118struct SeekBySize<T> {
119    index: usize,
120    _marker: PhantomData<fn() -> T>,
121}
122impl<T> SeekBySize<T> {
123    fn new(index: usize) -> Self {
124        Self {
125            index,
126            _marker: PhantomData,
127        }
128    }
129}
130impl<T> SplaySeeker for SeekBySize<T>
131where
132    T: MonoidAction,
133{
134    type S = LazyAggSplay<T>;
135    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
136        let lsize = node.left().map(|l| l.data().size).unwrap_or_default();
137        let ord = self.index.cmp(&lsize);
138        if matches!(ord, Ordering::Greater) {
139            self.index -= lsize + 1;
140        }
141        ord
142    }
143}
144
145struct SeekByAccCond<F, T>
146where
147    T: MonoidAction,
148{
149    acc: T::Agg,
150    f: F,
151    _marker: PhantomData<fn() -> T>,
152}
153impl<F, T> SeekByAccCond<F, T>
154where
155    T: MonoidAction,
156{
157    fn new(f: F) -> Self {
158        Self {
159            acc: T::agg_unit(),
160            f,
161            _marker: PhantomData,
162        }
163    }
164}
165impl<F, T> SplaySeeker for SeekByAccCond<F, T>
166where
167    F: FnMut(&T::Agg) -> bool,
168    T: MonoidAction,
169{
170    type S = LazyAggSplay<T>;
171    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
172        if let Some(lagg) = node.left().map(|l| &l.data().agg) {
173            let nacc = T::agg_operate(&self.acc, lagg);
174            if (self.f)(&nacc) {
175                return Ordering::Less;
176            }
177            self.acc = nacc;
178        };
179        self.acc = T::agg_operate(&self.acc, &T::single_agg(&node.data().key));
180        if (self.f)(&self.acc) {
181            Ordering::Equal
182        } else {
183            Ordering::Greater
184        }
185    }
186}
187
188struct SeekByRaccCond<F, T>
189where
190    T: MonoidAction,
191{
192    acc: T::Agg,
193    f: F,
194    _marker: PhantomData<fn() -> T>,
195}
196impl<F, T> SeekByRaccCond<F, T>
197where
198    T: MonoidAction,
199{
200    fn new(f: F) -> Self {
201        Self {
202            acc: T::agg_unit(),
203            f,
204            _marker: PhantomData,
205        }
206    }
207}
208impl<F, T> SplaySeeker for SeekByRaccCond<F, T>
209where
210    F: FnMut(&T::Agg) -> bool,
211    T: MonoidAction,
212{
213    type S = LazyAggSplay<T>;
214    fn splay_seek(&mut self, node: NodeRef<marker::Immut<'_>, Self::S>) -> Ordering {
215        if let Some(lagg) = node.right().map(|r| &r.data().agg) {
216            let nacc = T::agg_operate(lagg, &self.acc);
217            if (self.f)(&nacc) {
218                return Ordering::Greater;
219            }
220            self.acc = nacc;
221        };
222        self.acc = T::agg_operate(&T::single_agg(&node.data().key), &self.acc);
223        if (self.f)(&self.acc) {
224            Ordering::Equal
225        } else {
226            Ordering::Less
227        }
228    }
229}
230
231pub struct SplaySequence<T, A = MemoryPool<Node<LazyAggElement<T>>>>
232where
233    T: MonoidAction,
234    A: Allocator<Node<LazyAggElement<T>>>,
235{
236    root: Root<LazyAggSplay<T>>,
237    length: usize,
238    alloc: ManuallyDrop<A>,
239}
240
241impl<T, A> Debug for SplaySequence<T, A>
242where
243    T: MonoidAction,
244    T::Key: Debug,
245    T::Agg: Debug,
246    T::Act: Debug,
247    A: Allocator<Node<LazyAggElement<T>>>,
248{
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_struct("SplayMap")
251            .field("root", &self.root)
252            .field("length", &self.length)
253            .finish()
254    }
255}
256
257impl<T, A> Drop for SplaySequence<T, A>
258where
259    T: MonoidAction,
260    A: Allocator<Node<LazyAggElement<T>>>,
261{
262    fn drop(&mut self) {
263        unsafe {
264            while let Some(node) = self.root.take_first() {
265                self.alloc.deallocate(node.into_dying().into_inner());
266            }
267            ManuallyDrop::drop(&mut self.alloc);
268        }
269    }
270}
271
272impl<T, A> Default for SplaySequence<T, A>
273where
274    T: MonoidAction,
275    A: Allocator<Node<LazyAggElement<T>>> + Default,
276{
277    fn default() -> Self {
278        Self {
279            root: Root::default(),
280            length: 0,
281            alloc: Default::default(),
282        }
283    }
284}
285
286impl<T> SplaySequence<T>
287where
288    T: MonoidAction,
289{
290    pub fn new() -> Self {
291        Default::default()
292    }
293    pub fn with_capacity(capacity: usize) -> Self {
294        Self {
295            root: Root::default(),
296            length: 0,
297            alloc: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
298        }
299    }
300    pub fn len(&self) -> usize {
301        self.length
302    }
303    pub fn is_empty(&self) -> bool {
304        self.length == 0
305    }
306}
307impl<T, A> SplaySequence<T, A>
308where
309    T: MonoidAction,
310    A: Allocator<Node<LazyAggElement<T>>>,
311{
312    fn range<R>(&mut self, range: R) -> NodeRange<'_, LazyAggSplay<T>>
313    where
314        R: RangeBounds<usize>,
315    {
316        let start = match range.start_bound() {
317            Bound::Included(&index) => Bound::Included(SeekBySize::new(index)),
318            Bound::Excluded(&index) => Bound::Excluded(SeekBySize::new(index)),
319            Bound::Unbounded => Bound::Unbounded,
320        };
321        let end = match range.end_bound() {
322            Bound::Included(&index) => Bound::Included(SeekBySize::new(index)),
323            Bound::Excluded(&index) => Bound::Excluded(SeekBySize::new(index)),
324            Bound::Unbounded => Bound::Unbounded,
325        };
326        self.root.range(start, end)
327    }
328    pub fn update<R>(&mut self, range: R, x: T::Act)
329    where
330        R: RangeBounds<usize>,
331    {
332        if let Some(root) = self.range(range).root_mut().root_data_mut() {
333            LazyAggSplay::<T>::update_lazy(root, &x);
334        }
335    }
336    pub fn fold<R>(&mut self, range: R) -> T::Agg
337    where
338        R: RangeBounds<usize>,
339    {
340        if let Some(root) = self.range(range).root().root() {
341            root.data().agg.clone()
342        } else {
343            T::agg_unit()
344        }
345    }
346    pub fn reverse<R>(&mut self, range: R)
347    where
348        R: RangeBounds<usize>,
349    {
350        if let Some(root) = self.range(range).root_mut().root_data_mut() {
351            LazyAggSplay::<T>::reverse(root);
352        }
353    }
354    pub fn get(&mut self, index: usize) -> Option<&T::Key> {
355        self.root.splay_by(SeekBySize::new(index))?;
356        self.root.root().map(|root| &root.data().key)
357    }
358    pub fn modify<F>(&mut self, index: usize, f: F)
359    where
360        F: FnOnce(&T::Key) -> T::Key,
361    {
362        self.root.splay_by(SeekBySize::new(index)).unwrap();
363        let data = self.root.root_data_mut().unwrap().data_mut();
364        data.key = f(&data.key);
365        LazyAggSplay::<T>::bottom_up(self.root.root_data_mut().unwrap());
366    }
Source

pub fn left(&self) -> Option<Self>

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/sized_map.rs (line 24)
23    fn bottom_up(node: NodeRef<marker::DataMut<'_>, Self>) {
24        let l = node.left().map(|p| p.data().1).unwrap_or_default();
25        let r = node.right().map(|p| p.data().1).unwrap_or_default();
26        node.data_mut().1 = l + r + 1;
27    }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 66)
64    fn propagate(node: NodeRef<marker::DataMut<'_>, Self>) -> NodeRef<marker::DataMut<'_>, Self> {
65        let lazy = replace(&mut node.data_mut().lazy, T::act_unit());
66        if let Some(left) = node.left() {
67            Self::update_lazy(left, &lazy);
68        }
69        if let Some(right) = node.right() {
70            Self::update_lazy(right, &lazy);
71        }
72        if replace(&mut node.data_mut().rev, false) {
73            if let Some(left) = node.left() {
74                Self::reverse(left);
75            }
76            if let Some(right) = node.right() {
77                Self::reverse(right);
78            }
79        }
80        node
81    }
82    fn recalc(node: NodeRef<marker::DataMut<'_>, Self>) -> NodeRef<marker::DataMut<'_>, Self> {
83        let mut agg = T::single_agg(&node.data().key);
84        let mut size = 1;
85        if let Some(left) = node.left() {
86            let data = left.data();
87            agg = T::agg_operate(&data.agg, &agg);
88            // agg = <T::AggMonoid as Magma>::operate(&data.agg, &agg);
89            size += data.size;
90        }
91        if let Some(right) = node.right() {
92            let data = right.data();
93            agg = T::agg_operate(&agg, &data.agg);
94            size += data.size;
95        }
96        let data = node.data_mut();
97        data.agg = agg;
98        data.size = size;
99        node
100    }
Source

pub fn right(&self) -> Option<Self>

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/sized_map.rs (line 25)
23    fn bottom_up(node: NodeRef<marker::DataMut<'_>, Self>) {
24        let l = node.left().map(|p| p.data().1).unwrap_or_default();
25        let r = node.right().map(|p| p.data().1).unwrap_or_default();
26        node.data_mut().1 = l + r + 1;
27    }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 69)
64    fn propagate(node: NodeRef<marker::DataMut<'_>, Self>) -> NodeRef<marker::DataMut<'_>, Self> {
65        let lazy = replace(&mut node.data_mut().lazy, T::act_unit());
66        if let Some(left) = node.left() {
67            Self::update_lazy(left, &lazy);
68        }
69        if let Some(right) = node.right() {
70            Self::update_lazy(right, &lazy);
71        }
72        if replace(&mut node.data_mut().rev, false) {
73            if let Some(left) = node.left() {
74                Self::reverse(left);
75            }
76            if let Some(right) = node.right() {
77                Self::reverse(right);
78            }
79        }
80        node
81    }
82    fn recalc(node: NodeRef<marker::DataMut<'_>, Self>) -> NodeRef<marker::DataMut<'_>, Self> {
83        let mut agg = T::single_agg(&node.data().key);
84        let mut size = 1;
85        if let Some(left) = node.left() {
86            let data = left.data();
87            agg = T::agg_operate(&data.agg, &agg);
88            // agg = <T::AggMonoid as Magma>::operate(&data.agg, &agg);
89            size += data.size;
90        }
91        if let Some(right) = node.right() {
92            let data = right.data();
93            agg = T::agg_operate(&agg, &data.agg);
94            size += data.size;
95        }
96        let data = node.data_mut();
97        data.agg = agg;
98        data.size = size;
99        node
100    }
Source

pub fn reverse(&self)

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 60)
59    pub fn reverse(node: NodeRef<marker::DataMut<'_>, Self>) {
60        node.reverse();
61        T::toggle(&mut node.data_mut().agg);
62        node.data_mut().rev ^= true;
63    }
Source§

impl<'a, S> NodeRef<Mut<'a>, S>
where S: SplaySpec, S::T: 'a,

Source

pub fn data(self) -> &'a S::T

Source

pub fn data_mut(self) -> &'a mut S::T

Source

pub fn take_left(&mut self) -> Option<NodeRef<Owned, S>>

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 324)
296    pub fn splay_by<Seeker>(self, mut seeker: Seeker) -> (Ordering, Self)
297    where
298        Seeker: SplaySeeker<S = S>,
299    {
300        let mut x = self;
301        // let dummy = Node { data: None, left: left_subtree, right: right_subtree };
302        let mut left_subtree: Option<NonNull<Node<S::T>>> = None;
303        let mut right_subtree: Option<NonNull<Node<S::T>>> = None;
304        let mut left_entry = &mut left_subtree;
305        let mut right_entry = &mut right_subtree;
306        let mut stack = vec![];
307
308        macro_rules! add {
309            (@left Some($ptr:ident)) => { add!(@inner Some($ptr.node), left_entry $ptr right); };
310            (@right Some($ptr:ident)) => { add!(@inner Some($ptr.node), right_entry $ptr left); };
311            (@inner $node:expr, $entry:ident $ptr:ident $dir:ident) => {
312                *$entry = $node;
313                if S::has_bottom_up() {
314                    stack.push($ptr.node);
315                }
316                $entry = unsafe { &mut (*$entry.as_mut().unwrap().as_ptr()).$dir };
317            };
318        }
319
320        let root_ord = loop {
321            S::top_down(x.borrow_datamut());
322            match seeker.splay_seek(x.reborrow()) {
323                Ordering::Less => {
324                    if let Some(mut y) = x.borrow_mut().take_left() {
325                        S::top_down(y.borrow_datamut());
326                        match seeker.splay_seek(y.reborrow()) {
327                            Ordering::Less => {
328                                if let Some(mut z) = y.borrow_mut().take_left() {
329                                    S::top_down(z.borrow_datamut());
330                                    x.borrow_mut().set_left(y.borrow_mut().take_right());
331                                    S::bottom_up(x.borrow_datamut());
332                                    y.borrow_mut().set_right(Some(x));
333                                    add!(@right Some(y));
334                                    x = z;
335                                } else {
336                                    add!(@right Some(x));
337                                    x = y;
338                                    break Ordering::Less;
339                                }
340                            }
341                            Ordering::Equal => {
342                                add!(@right Some(x));
343                                x = y;
344                                break Ordering::Equal;
345                            }
346                            Ordering::Greater => {
347                                if let Some(mut z) = y.borrow_mut().take_right() {
348                                    S::top_down(z.borrow_datamut());
349                                    add!(@right Some(x));
350                                    add!(@left Some(y));
351                                    x = z;
352                                } else {
353                                    add!(@right Some(x));
354                                    x = y;
355                                    break Ordering::Greater;
356                                }
357                            }
358                        }
359                    } else {
360                        break Ordering::Less;
361                    }
362                }
363                Ordering::Equal => break Ordering::Equal,
364                Ordering::Greater => {
365                    if let Some(mut y) = x.borrow_mut().take_right() {
366                        S::top_down(y.borrow_datamut());
367                        match seeker.splay_seek(y.reborrow()) {
368                            Ordering::Less => {
369                                if let Some(mut z) = y.borrow_mut().take_left() {
370                                    S::top_down(z.borrow_datamut());
371                                    add!(@left Some(x));
372                                    add!(@right Some(y));
373                                    x = z;
374                                } else {
375                                    add!(@left Some(x));
376                                    x = y;
377                                    break Ordering::Less;
378                                }
379                            }
380                            Ordering::Equal => {
381                                add!(@left Some(x));
382                                x = y;
383                                break Ordering::Equal;
384                            }
385                            Ordering::Greater => {
386                                if let Some(mut z) = y.borrow_mut().take_right() {
387                                    S::top_down(z.borrow_datamut());
388                                    x.borrow_mut().set_right(y.borrow_mut().take_left());
389                                    S::bottom_up(x.borrow_datamut());
390                                    y.borrow_mut().set_left(Some(x));
391                                    add!(@left Some(y));
392                                    x = z;
393                                } else {
394                                    add!(@left Some(x));
395                                    x = y;
396                                    break Ordering::Greater;
397                                }
398                            }
399                        }
400                    } else {
401                        break Ordering::Greater;
402                    }
403                }
404            }
405        };
406        *left_entry = x.borrow_mut().take_left().map(|node| node.node);
407        *right_entry = x.borrow_mut().take_right().map(|node| node.node);
408        unsafe {
409            x.borrow_mut()
410                .set_left(left_subtree.map(|node| NodeRef::new_unchecked(node)));
411            x.borrow_mut()
412                .set_right(right_subtree.map(|node| NodeRef::new_unchecked(node)));
413            if S::has_bottom_up() {
414                while let Some(node) = stack.pop() {
415                    S::bottom_up(NodeRef::new_unchecked(node));
416                }
417            }
418        }
419        S::bottom_up(x.borrow_datamut());
420        (root_ord, x)
421    }
422    pub fn insert_left(mut self, mut node: Self) -> Self {
423        if let Some(left) = self.borrow_mut().take_left() {
424            node.borrow_mut().set_left(Some(left));
425            S::bottom_up(self.borrow_datamut());
426        };
427        node.borrow_mut().set_right(Some(self));
428        S::bottom_up(node.borrow_datamut());
429        node
430    }
431    pub fn insert_right(mut self, mut node: Self) -> Self {
432        if let Some(right) = self.borrow_mut().take_right() {
433            node.borrow_mut().set_right(Some(right));
434            S::bottom_up(self.borrow_datamut());
435        }
436        node.borrow_mut().set_left(Some(self));
437        S::bottom_up(node.borrow_datamut());
438        node
439    }
440    pub fn insert_first(self, mut node: Self) -> Self {
441        node.borrow_mut().set_right(Some(self));
442        S::bottom_up(node.borrow_datamut());
443        node
444    }
445    pub fn insert_last(self, mut node: Self) -> Self {
446        node.borrow_mut().set_left(Some(self));
447        S::bottom_up(node.borrow_datamut());
448        node
449    }
450    pub fn merge(mut self, mut other: Self) -> Self {
451        if other.reborrow().left().is_none() {
452            S::top_down(other.borrow_datamut());
453            other.borrow_mut().set_left(Some(self));
454            S::bottom_up(other.borrow_datamut());
455            other
456        } else {
457            self = self.splay_by(SeekRight::new()).1;
458            self.borrow_mut().set_right(Some(other));
459            S::bottom_up(self.borrow_datamut());
460            self
461        }
462    }
463}
464
465impl<S> Root<S>
466where
467    S: SplaySpec,
468{
469    pub fn new(root: Option<NodeRef<marker::Owned, S>>) -> Self {
470        Self { root }
471    }
472    pub unsafe fn from_single_nodes(nodes: Vec<NodeRef<marker::Owned, S>>) -> Self {
473        unsafe { Self::from_single_nodes_inner(&nodes) }
474    }
475    unsafe fn from_single_nodes_inner(nodes: &[NodeRef<marker::Owned, S>]) -> Self {
476        if nodes.is_empty() {
477            Self::new(None)
478        } else {
479            let m = nodes.len() / 2;
480            let left = unsafe { Self::from_single_nodes_inner(&nodes[..m]) };
481            let right = unsafe { Self::from_single_nodes_inner(&nodes[m + 1..]) };
482            let mut node = NodeRef::new(nodes[m].node);
483            node.borrow_mut().set_left(left.root);
484            node.borrow_mut().set_right(right.root);
485            S::bottom_up(node.borrow_datamut());
486            Self::new(Some(node))
487        }
488    }
489    pub fn is_empty(&self) -> bool {
490        self.root.is_none()
491    }
492    pub fn root(&self) -> Option<NodeRef<marker::Immut<'_>, S>> {
493        Some(self.root.as_ref()?.reborrow())
494    }
495    pub fn root_data_mut(&mut self) -> Option<NodeRef<marker::DataMut<'_>, S>> {
496        Some(self.root.as_mut()?.borrow_datamut())
497    }
498    pub fn splay_by<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
499    where
500        Seeker: SplaySeeker<S = S>,
501    {
502        let (ord, root) = self.root.take()?.splay_by(seeker);
503        self.root = Some(root);
504        Some(ord)
505    }
506    pub fn insert_left(&mut self, mut node: NodeRef<marker::Owned, S>) {
507        self.root = Some(match self.root.take() {
508            Some(root) => root.insert_left(node),
509            None => {
510                S::bottom_up(node.borrow_datamut());
511                node
512            }
513        });
514    }
515    pub fn insert_right(&mut self, mut node: NodeRef<marker::Owned, S>) {
516        self.root = Some(match self.root.take() {
517            Some(root) => root.insert_right(node),
518            None => {
519                S::bottom_up(node.borrow_datamut());
520                node
521            }
522        });
523    }
524    pub fn insert_first(&mut self, mut node: NodeRef<marker::Owned, S>) {
525        self.root = Some(match self.root.take() {
526            Some(root) => root.insert_first(node),
527            None => {
528                S::bottom_up(node.borrow_datamut());
529                node
530            }
531        });
532    }
533    pub fn insert_last(&mut self, mut node: NodeRef<marker::Owned, S>) {
534        self.root = Some(match self.root.take() {
535            Some(root) => root.insert_last(node),
536            None => {
537                S::bottom_up(node.borrow_datamut());
538                node
539            }
540        });
541    }
542    pub fn take_root(&mut self) -> Option<NodeRef<marker::Owned, S>> {
543        let mut root = self.root.take()?;
544        let right = root.borrow_mut().take_right();
545        self.root = root.borrow_mut().take_left();
546        self.append(&mut Self::new(right));
547        Some(root)
548    }
549    pub fn take_first(&mut self) -> Option<NodeRef<marker::Owned, S>> {
550        let mut root = self.root.take()?.splay_by(SeekLeft::new()).1;
551        let right = root.borrow_mut().take_right();
552        self.root = right;
553        Some(root)
554    }
555    pub fn take_last(&mut self) -> Option<NodeRef<marker::Owned, S>> {
556        let mut root = self.root.take()?.splay_by(SeekRight::new()).1;
557        let left = root.borrow_mut().take_left();
558        self.root = left;
559        Some(root)
560    }
561    pub fn split_left(&mut self) -> Option<NodeRef<marker::Owned, S>> {
562        let root = self.root.as_mut()?;
563        let left = root.borrow_mut().take_left();
564        S::bottom_up(root.borrow_datamut());
565        left
566    }
Source

pub fn take_right(&mut self) -> Option<NodeRef<Owned, S>>

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 330)
296    pub fn splay_by<Seeker>(self, mut seeker: Seeker) -> (Ordering, Self)
297    where
298        Seeker: SplaySeeker<S = S>,
299    {
300        let mut x = self;
301        // let dummy = Node { data: None, left: left_subtree, right: right_subtree };
302        let mut left_subtree: Option<NonNull<Node<S::T>>> = None;
303        let mut right_subtree: Option<NonNull<Node<S::T>>> = None;
304        let mut left_entry = &mut left_subtree;
305        let mut right_entry = &mut right_subtree;
306        let mut stack = vec![];
307
308        macro_rules! add {
309            (@left Some($ptr:ident)) => { add!(@inner Some($ptr.node), left_entry $ptr right); };
310            (@right Some($ptr:ident)) => { add!(@inner Some($ptr.node), right_entry $ptr left); };
311            (@inner $node:expr, $entry:ident $ptr:ident $dir:ident) => {
312                *$entry = $node;
313                if S::has_bottom_up() {
314                    stack.push($ptr.node);
315                }
316                $entry = unsafe { &mut (*$entry.as_mut().unwrap().as_ptr()).$dir };
317            };
318        }
319
320        let root_ord = loop {
321            S::top_down(x.borrow_datamut());
322            match seeker.splay_seek(x.reborrow()) {
323                Ordering::Less => {
324                    if let Some(mut y) = x.borrow_mut().take_left() {
325                        S::top_down(y.borrow_datamut());
326                        match seeker.splay_seek(y.reborrow()) {
327                            Ordering::Less => {
328                                if let Some(mut z) = y.borrow_mut().take_left() {
329                                    S::top_down(z.borrow_datamut());
330                                    x.borrow_mut().set_left(y.borrow_mut().take_right());
331                                    S::bottom_up(x.borrow_datamut());
332                                    y.borrow_mut().set_right(Some(x));
333                                    add!(@right Some(y));
334                                    x = z;
335                                } else {
336                                    add!(@right Some(x));
337                                    x = y;
338                                    break Ordering::Less;
339                                }
340                            }
341                            Ordering::Equal => {
342                                add!(@right Some(x));
343                                x = y;
344                                break Ordering::Equal;
345                            }
346                            Ordering::Greater => {
347                                if let Some(mut z) = y.borrow_mut().take_right() {
348                                    S::top_down(z.borrow_datamut());
349                                    add!(@right Some(x));
350                                    add!(@left Some(y));
351                                    x = z;
352                                } else {
353                                    add!(@right Some(x));
354                                    x = y;
355                                    break Ordering::Greater;
356                                }
357                            }
358                        }
359                    } else {
360                        break Ordering::Less;
361                    }
362                }
363                Ordering::Equal => break Ordering::Equal,
364                Ordering::Greater => {
365                    if let Some(mut y) = x.borrow_mut().take_right() {
366                        S::top_down(y.borrow_datamut());
367                        match seeker.splay_seek(y.reborrow()) {
368                            Ordering::Less => {
369                                if let Some(mut z) = y.borrow_mut().take_left() {
370                                    S::top_down(z.borrow_datamut());
371                                    add!(@left Some(x));
372                                    add!(@right Some(y));
373                                    x = z;
374                                } else {
375                                    add!(@left Some(x));
376                                    x = y;
377                                    break Ordering::Less;
378                                }
379                            }
380                            Ordering::Equal => {
381                                add!(@left Some(x));
382                                x = y;
383                                break Ordering::Equal;
384                            }
385                            Ordering::Greater => {
386                                if let Some(mut z) = y.borrow_mut().take_right() {
387                                    S::top_down(z.borrow_datamut());
388                                    x.borrow_mut().set_right(y.borrow_mut().take_left());
389                                    S::bottom_up(x.borrow_datamut());
390                                    y.borrow_mut().set_left(Some(x));
391                                    add!(@left Some(y));
392                                    x = z;
393                                } else {
394                                    add!(@left Some(x));
395                                    x = y;
396                                    break Ordering::Greater;
397                                }
398                            }
399                        }
400                    } else {
401                        break Ordering::Greater;
402                    }
403                }
404            }
405        };
406        *left_entry = x.borrow_mut().take_left().map(|node| node.node);
407        *right_entry = x.borrow_mut().take_right().map(|node| node.node);
408        unsafe {
409            x.borrow_mut()
410                .set_left(left_subtree.map(|node| NodeRef::new_unchecked(node)));
411            x.borrow_mut()
412                .set_right(right_subtree.map(|node| NodeRef::new_unchecked(node)));
413            if S::has_bottom_up() {
414                while let Some(node) = stack.pop() {
415                    S::bottom_up(NodeRef::new_unchecked(node));
416                }
417            }
418        }
419        S::bottom_up(x.borrow_datamut());
420        (root_ord, x)
421    }
422    pub fn insert_left(mut self, mut node: Self) -> Self {
423        if let Some(left) = self.borrow_mut().take_left() {
424            node.borrow_mut().set_left(Some(left));
425            S::bottom_up(self.borrow_datamut());
426        };
427        node.borrow_mut().set_right(Some(self));
428        S::bottom_up(node.borrow_datamut());
429        node
430    }
431    pub fn insert_right(mut self, mut node: Self) -> Self {
432        if let Some(right) = self.borrow_mut().take_right() {
433            node.borrow_mut().set_right(Some(right));
434            S::bottom_up(self.borrow_datamut());
435        }
436        node.borrow_mut().set_left(Some(self));
437        S::bottom_up(node.borrow_datamut());
438        node
439    }
440    pub fn insert_first(self, mut node: Self) -> Self {
441        node.borrow_mut().set_right(Some(self));
442        S::bottom_up(node.borrow_datamut());
443        node
444    }
445    pub fn insert_last(self, mut node: Self) -> Self {
446        node.borrow_mut().set_left(Some(self));
447        S::bottom_up(node.borrow_datamut());
448        node
449    }
450    pub fn merge(mut self, mut other: Self) -> Self {
451        if other.reborrow().left().is_none() {
452            S::top_down(other.borrow_datamut());
453            other.borrow_mut().set_left(Some(self));
454            S::bottom_up(other.borrow_datamut());
455            other
456        } else {
457            self = self.splay_by(SeekRight::new()).1;
458            self.borrow_mut().set_right(Some(other));
459            S::bottom_up(self.borrow_datamut());
460            self
461        }
462    }
463}
464
465impl<S> Root<S>
466where
467    S: SplaySpec,
468{
469    pub fn new(root: Option<NodeRef<marker::Owned, S>>) -> Self {
470        Self { root }
471    }
472    pub unsafe fn from_single_nodes(nodes: Vec<NodeRef<marker::Owned, S>>) -> Self {
473        unsafe { Self::from_single_nodes_inner(&nodes) }
474    }
475    unsafe fn from_single_nodes_inner(nodes: &[NodeRef<marker::Owned, S>]) -> Self {
476        if nodes.is_empty() {
477            Self::new(None)
478        } else {
479            let m = nodes.len() / 2;
480            let left = unsafe { Self::from_single_nodes_inner(&nodes[..m]) };
481            let right = unsafe { Self::from_single_nodes_inner(&nodes[m + 1..]) };
482            let mut node = NodeRef::new(nodes[m].node);
483            node.borrow_mut().set_left(left.root);
484            node.borrow_mut().set_right(right.root);
485            S::bottom_up(node.borrow_datamut());
486            Self::new(Some(node))
487        }
488    }
489    pub fn is_empty(&self) -> bool {
490        self.root.is_none()
491    }
492    pub fn root(&self) -> Option<NodeRef<marker::Immut<'_>, S>> {
493        Some(self.root.as_ref()?.reborrow())
494    }
495    pub fn root_data_mut(&mut self) -> Option<NodeRef<marker::DataMut<'_>, S>> {
496        Some(self.root.as_mut()?.borrow_datamut())
497    }
498    pub fn splay_by<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
499    where
500        Seeker: SplaySeeker<S = S>,
501    {
502        let (ord, root) = self.root.take()?.splay_by(seeker);
503        self.root = Some(root);
504        Some(ord)
505    }
506    pub fn insert_left(&mut self, mut node: NodeRef<marker::Owned, S>) {
507        self.root = Some(match self.root.take() {
508            Some(root) => root.insert_left(node),
509            None => {
510                S::bottom_up(node.borrow_datamut());
511                node
512            }
513        });
514    }
515    pub fn insert_right(&mut self, mut node: NodeRef<marker::Owned, S>) {
516        self.root = Some(match self.root.take() {
517            Some(root) => root.insert_right(node),
518            None => {
519                S::bottom_up(node.borrow_datamut());
520                node
521            }
522        });
523    }
524    pub fn insert_first(&mut self, mut node: NodeRef<marker::Owned, S>) {
525        self.root = Some(match self.root.take() {
526            Some(root) => root.insert_first(node),
527            None => {
528                S::bottom_up(node.borrow_datamut());
529                node
530            }
531        });
532    }
533    pub fn insert_last(&mut self, mut node: NodeRef<marker::Owned, S>) {
534        self.root = Some(match self.root.take() {
535            Some(root) => root.insert_last(node),
536            None => {
537                S::bottom_up(node.borrow_datamut());
538                node
539            }
540        });
541    }
542    pub fn take_root(&mut self) -> Option<NodeRef<marker::Owned, S>> {
543        let mut root = self.root.take()?;
544        let right = root.borrow_mut().take_right();
545        self.root = root.borrow_mut().take_left();
546        self.append(&mut Self::new(right));
547        Some(root)
548    }
549    pub fn take_first(&mut self) -> Option<NodeRef<marker::Owned, S>> {
550        let mut root = self.root.take()?.splay_by(SeekLeft::new()).1;
551        let right = root.borrow_mut().take_right();
552        self.root = right;
553        Some(root)
554    }
555    pub fn take_last(&mut self) -> Option<NodeRef<marker::Owned, S>> {
556        let mut root = self.root.take()?.splay_by(SeekRight::new()).1;
557        let left = root.borrow_mut().take_left();
558        self.root = left;
559        Some(root)
560    }
561    pub fn split_left(&mut self) -> Option<NodeRef<marker::Owned, S>> {
562        let root = self.root.as_mut()?;
563        let left = root.borrow_mut().take_left();
564        S::bottom_up(root.borrow_datamut());
565        left
566    }
567    pub fn split_right(&mut self) -> Option<NodeRef<marker::Owned, S>> {
568        let root = self.root.as_mut()?;
569        let right = root.borrow_mut().take_right();
570        S::bottom_up(root.borrow_datamut());
571        right
572    }
Source

pub fn set_left(&mut self, node: Option<NodeRef<Owned, S>>)

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 330)
296    pub fn splay_by<Seeker>(self, mut seeker: Seeker) -> (Ordering, Self)
297    where
298        Seeker: SplaySeeker<S = S>,
299    {
300        let mut x = self;
301        // let dummy = Node { data: None, left: left_subtree, right: right_subtree };
302        let mut left_subtree: Option<NonNull<Node<S::T>>> = None;
303        let mut right_subtree: Option<NonNull<Node<S::T>>> = None;
304        let mut left_entry = &mut left_subtree;
305        let mut right_entry = &mut right_subtree;
306        let mut stack = vec![];
307
308        macro_rules! add {
309            (@left Some($ptr:ident)) => { add!(@inner Some($ptr.node), left_entry $ptr right); };
310            (@right Some($ptr:ident)) => { add!(@inner Some($ptr.node), right_entry $ptr left); };
311            (@inner $node:expr, $entry:ident $ptr:ident $dir:ident) => {
312                *$entry = $node;
313                if S::has_bottom_up() {
314                    stack.push($ptr.node);
315                }
316                $entry = unsafe { &mut (*$entry.as_mut().unwrap().as_ptr()).$dir };
317            };
318        }
319
320        let root_ord = loop {
321            S::top_down(x.borrow_datamut());
322            match seeker.splay_seek(x.reborrow()) {
323                Ordering::Less => {
324                    if let Some(mut y) = x.borrow_mut().take_left() {
325                        S::top_down(y.borrow_datamut());
326                        match seeker.splay_seek(y.reborrow()) {
327                            Ordering::Less => {
328                                if let Some(mut z) = y.borrow_mut().take_left() {
329                                    S::top_down(z.borrow_datamut());
330                                    x.borrow_mut().set_left(y.borrow_mut().take_right());
331                                    S::bottom_up(x.borrow_datamut());
332                                    y.borrow_mut().set_right(Some(x));
333                                    add!(@right Some(y));
334                                    x = z;
335                                } else {
336                                    add!(@right Some(x));
337                                    x = y;
338                                    break Ordering::Less;
339                                }
340                            }
341                            Ordering::Equal => {
342                                add!(@right Some(x));
343                                x = y;
344                                break Ordering::Equal;
345                            }
346                            Ordering::Greater => {
347                                if let Some(mut z) = y.borrow_mut().take_right() {
348                                    S::top_down(z.borrow_datamut());
349                                    add!(@right Some(x));
350                                    add!(@left Some(y));
351                                    x = z;
352                                } else {
353                                    add!(@right Some(x));
354                                    x = y;
355                                    break Ordering::Greater;
356                                }
357                            }
358                        }
359                    } else {
360                        break Ordering::Less;
361                    }
362                }
363                Ordering::Equal => break Ordering::Equal,
364                Ordering::Greater => {
365                    if let Some(mut y) = x.borrow_mut().take_right() {
366                        S::top_down(y.borrow_datamut());
367                        match seeker.splay_seek(y.reborrow()) {
368                            Ordering::Less => {
369                                if let Some(mut z) = y.borrow_mut().take_left() {
370                                    S::top_down(z.borrow_datamut());
371                                    add!(@left Some(x));
372                                    add!(@right Some(y));
373                                    x = z;
374                                } else {
375                                    add!(@left Some(x));
376                                    x = y;
377                                    break Ordering::Less;
378                                }
379                            }
380                            Ordering::Equal => {
381                                add!(@left Some(x));
382                                x = y;
383                                break Ordering::Equal;
384                            }
385                            Ordering::Greater => {
386                                if let Some(mut z) = y.borrow_mut().take_right() {
387                                    S::top_down(z.borrow_datamut());
388                                    x.borrow_mut().set_right(y.borrow_mut().take_left());
389                                    S::bottom_up(x.borrow_datamut());
390                                    y.borrow_mut().set_left(Some(x));
391                                    add!(@left Some(y));
392                                    x = z;
393                                } else {
394                                    add!(@left Some(x));
395                                    x = y;
396                                    break Ordering::Greater;
397                                }
398                            }
399                        }
400                    } else {
401                        break Ordering::Greater;
402                    }
403                }
404            }
405        };
406        *left_entry = x.borrow_mut().take_left().map(|node| node.node);
407        *right_entry = x.borrow_mut().take_right().map(|node| node.node);
408        unsafe {
409            x.borrow_mut()
410                .set_left(left_subtree.map(|node| NodeRef::new_unchecked(node)));
411            x.borrow_mut()
412                .set_right(right_subtree.map(|node| NodeRef::new_unchecked(node)));
413            if S::has_bottom_up() {
414                while let Some(node) = stack.pop() {
415                    S::bottom_up(NodeRef::new_unchecked(node));
416                }
417            }
418        }
419        S::bottom_up(x.borrow_datamut());
420        (root_ord, x)
421    }
422    pub fn insert_left(mut self, mut node: Self) -> Self {
423        if let Some(left) = self.borrow_mut().take_left() {
424            node.borrow_mut().set_left(Some(left));
425            S::bottom_up(self.borrow_datamut());
426        };
427        node.borrow_mut().set_right(Some(self));
428        S::bottom_up(node.borrow_datamut());
429        node
430    }
431    pub fn insert_right(mut self, mut node: Self) -> Self {
432        if let Some(right) = self.borrow_mut().take_right() {
433            node.borrow_mut().set_right(Some(right));
434            S::bottom_up(self.borrow_datamut());
435        }
436        node.borrow_mut().set_left(Some(self));
437        S::bottom_up(node.borrow_datamut());
438        node
439    }
440    pub fn insert_first(self, mut node: Self) -> Self {
441        node.borrow_mut().set_right(Some(self));
442        S::bottom_up(node.borrow_datamut());
443        node
444    }
445    pub fn insert_last(self, mut node: Self) -> Self {
446        node.borrow_mut().set_left(Some(self));
447        S::bottom_up(node.borrow_datamut());
448        node
449    }
450    pub fn merge(mut self, mut other: Self) -> Self {
451        if other.reborrow().left().is_none() {
452            S::top_down(other.borrow_datamut());
453            other.borrow_mut().set_left(Some(self));
454            S::bottom_up(other.borrow_datamut());
455            other
456        } else {
457            self = self.splay_by(SeekRight::new()).1;
458            self.borrow_mut().set_right(Some(other));
459            S::bottom_up(self.borrow_datamut());
460            self
461        }
462    }
463}
464
465impl<S> Root<S>
466where
467    S: SplaySpec,
468{
469    pub fn new(root: Option<NodeRef<marker::Owned, S>>) -> Self {
470        Self { root }
471    }
472    pub unsafe fn from_single_nodes(nodes: Vec<NodeRef<marker::Owned, S>>) -> Self {
473        unsafe { Self::from_single_nodes_inner(&nodes) }
474    }
475    unsafe fn from_single_nodes_inner(nodes: &[NodeRef<marker::Owned, S>]) -> Self {
476        if nodes.is_empty() {
477            Self::new(None)
478        } else {
479            let m = nodes.len() / 2;
480            let left = unsafe { Self::from_single_nodes_inner(&nodes[..m]) };
481            let right = unsafe { Self::from_single_nodes_inner(&nodes[m + 1..]) };
482            let mut node = NodeRef::new(nodes[m].node);
483            node.borrow_mut().set_left(left.root);
484            node.borrow_mut().set_right(right.root);
485            S::bottom_up(node.borrow_datamut());
486            Self::new(Some(node))
487        }
488    }
Source

pub fn set_right(&mut self, node: Option<NodeRef<Owned, S>>)

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 332)
296    pub fn splay_by<Seeker>(self, mut seeker: Seeker) -> (Ordering, Self)
297    where
298        Seeker: SplaySeeker<S = S>,
299    {
300        let mut x = self;
301        // let dummy = Node { data: None, left: left_subtree, right: right_subtree };
302        let mut left_subtree: Option<NonNull<Node<S::T>>> = None;
303        let mut right_subtree: Option<NonNull<Node<S::T>>> = None;
304        let mut left_entry = &mut left_subtree;
305        let mut right_entry = &mut right_subtree;
306        let mut stack = vec![];
307
308        macro_rules! add {
309            (@left Some($ptr:ident)) => { add!(@inner Some($ptr.node), left_entry $ptr right); };
310            (@right Some($ptr:ident)) => { add!(@inner Some($ptr.node), right_entry $ptr left); };
311            (@inner $node:expr, $entry:ident $ptr:ident $dir:ident) => {
312                *$entry = $node;
313                if S::has_bottom_up() {
314                    stack.push($ptr.node);
315                }
316                $entry = unsafe { &mut (*$entry.as_mut().unwrap().as_ptr()).$dir };
317            };
318        }
319
320        let root_ord = loop {
321            S::top_down(x.borrow_datamut());
322            match seeker.splay_seek(x.reborrow()) {
323                Ordering::Less => {
324                    if let Some(mut y) = x.borrow_mut().take_left() {
325                        S::top_down(y.borrow_datamut());
326                        match seeker.splay_seek(y.reborrow()) {
327                            Ordering::Less => {
328                                if let Some(mut z) = y.borrow_mut().take_left() {
329                                    S::top_down(z.borrow_datamut());
330                                    x.borrow_mut().set_left(y.borrow_mut().take_right());
331                                    S::bottom_up(x.borrow_datamut());
332                                    y.borrow_mut().set_right(Some(x));
333                                    add!(@right Some(y));
334                                    x = z;
335                                } else {
336                                    add!(@right Some(x));
337                                    x = y;
338                                    break Ordering::Less;
339                                }
340                            }
341                            Ordering::Equal => {
342                                add!(@right Some(x));
343                                x = y;
344                                break Ordering::Equal;
345                            }
346                            Ordering::Greater => {
347                                if let Some(mut z) = y.borrow_mut().take_right() {
348                                    S::top_down(z.borrow_datamut());
349                                    add!(@right Some(x));
350                                    add!(@left Some(y));
351                                    x = z;
352                                } else {
353                                    add!(@right Some(x));
354                                    x = y;
355                                    break Ordering::Greater;
356                                }
357                            }
358                        }
359                    } else {
360                        break Ordering::Less;
361                    }
362                }
363                Ordering::Equal => break Ordering::Equal,
364                Ordering::Greater => {
365                    if let Some(mut y) = x.borrow_mut().take_right() {
366                        S::top_down(y.borrow_datamut());
367                        match seeker.splay_seek(y.reborrow()) {
368                            Ordering::Less => {
369                                if let Some(mut z) = y.borrow_mut().take_left() {
370                                    S::top_down(z.borrow_datamut());
371                                    add!(@left Some(x));
372                                    add!(@right Some(y));
373                                    x = z;
374                                } else {
375                                    add!(@left Some(x));
376                                    x = y;
377                                    break Ordering::Less;
378                                }
379                            }
380                            Ordering::Equal => {
381                                add!(@left Some(x));
382                                x = y;
383                                break Ordering::Equal;
384                            }
385                            Ordering::Greater => {
386                                if let Some(mut z) = y.borrow_mut().take_right() {
387                                    S::top_down(z.borrow_datamut());
388                                    x.borrow_mut().set_right(y.borrow_mut().take_left());
389                                    S::bottom_up(x.borrow_datamut());
390                                    y.borrow_mut().set_left(Some(x));
391                                    add!(@left Some(y));
392                                    x = z;
393                                } else {
394                                    add!(@left Some(x));
395                                    x = y;
396                                    break Ordering::Greater;
397                                }
398                            }
399                        }
400                    } else {
401                        break Ordering::Greater;
402                    }
403                }
404            }
405        };
406        *left_entry = x.borrow_mut().take_left().map(|node| node.node);
407        *right_entry = x.borrow_mut().take_right().map(|node| node.node);
408        unsafe {
409            x.borrow_mut()
410                .set_left(left_subtree.map(|node| NodeRef::new_unchecked(node)));
411            x.borrow_mut()
412                .set_right(right_subtree.map(|node| NodeRef::new_unchecked(node)));
413            if S::has_bottom_up() {
414                while let Some(node) = stack.pop() {
415                    S::bottom_up(NodeRef::new_unchecked(node));
416                }
417            }
418        }
419        S::bottom_up(x.borrow_datamut());
420        (root_ord, x)
421    }
422    pub fn insert_left(mut self, mut node: Self) -> Self {
423        if let Some(left) = self.borrow_mut().take_left() {
424            node.borrow_mut().set_left(Some(left));
425            S::bottom_up(self.borrow_datamut());
426        };
427        node.borrow_mut().set_right(Some(self));
428        S::bottom_up(node.borrow_datamut());
429        node
430    }
431    pub fn insert_right(mut self, mut node: Self) -> Self {
432        if let Some(right) = self.borrow_mut().take_right() {
433            node.borrow_mut().set_right(Some(right));
434            S::bottom_up(self.borrow_datamut());
435        }
436        node.borrow_mut().set_left(Some(self));
437        S::bottom_up(node.borrow_datamut());
438        node
439    }
440    pub fn insert_first(self, mut node: Self) -> Self {
441        node.borrow_mut().set_right(Some(self));
442        S::bottom_up(node.borrow_datamut());
443        node
444    }
445    pub fn insert_last(self, mut node: Self) -> Self {
446        node.borrow_mut().set_left(Some(self));
447        S::bottom_up(node.borrow_datamut());
448        node
449    }
450    pub fn merge(mut self, mut other: Self) -> Self {
451        if other.reborrow().left().is_none() {
452            S::top_down(other.borrow_datamut());
453            other.borrow_mut().set_left(Some(self));
454            S::bottom_up(other.borrow_datamut());
455            other
456        } else {
457            self = self.splay_by(SeekRight::new()).1;
458            self.borrow_mut().set_right(Some(other));
459            S::bottom_up(self.borrow_datamut());
460            self
461        }
462    }
463}
464
465impl<S> Root<S>
466where
467    S: SplaySpec,
468{
469    pub fn new(root: Option<NodeRef<marker::Owned, S>>) -> Self {
470        Self { root }
471    }
472    pub unsafe fn from_single_nodes(nodes: Vec<NodeRef<marker::Owned, S>>) -> Self {
473        unsafe { Self::from_single_nodes_inner(&nodes) }
474    }
475    unsafe fn from_single_nodes_inner(nodes: &[NodeRef<marker::Owned, S>]) -> Self {
476        if nodes.is_empty() {
477            Self::new(None)
478        } else {
479            let m = nodes.len() / 2;
480            let left = unsafe { Self::from_single_nodes_inner(&nodes[..m]) };
481            let right = unsafe { Self::from_single_nodes_inner(&nodes[m + 1..]) };
482            let mut node = NodeRef::new(nodes[m].node);
483            node.borrow_mut().set_left(left.root);
484            node.borrow_mut().set_right(right.root);
485            S::bottom_up(node.borrow_datamut());
486            Self::new(Some(node))
487        }
488    }
Source§

impl<S> NodeRef<Dying, S>
where S: SplaySpec,

Source

pub unsafe fn into_inner(self) -> NonNull<Node<S::T>>

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 265)
262    fn drop(&mut self) {
263        unsafe {
264            while let Some(node) = self.root.take_first() {
265                self.alloc.deallocate(node.into_dying().into_inner());
266            }
267            ManuallyDrop::drop(&mut self.alloc);
268        }
269    }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sized_map.rs (line 113)
110    fn drop(&mut self) {
111        unsafe {
112            while let Some(node) = self.root.take_first() {
113                self.alloc.deallocate(node.into_dying().into_inner());
114            }
115            ManuallyDrop::drop(&mut self.alloc);
116        }
117    }
Source

pub unsafe fn into_data<A>(self, allocator: &mut A) -> S::T
where A: Allocator<Node<S::T>>,

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/sequence.rs (line 397)
390    pub fn remove(&mut self, index: usize) -> Option<T::Key> {
391        if index >= self.length {
392            return None;
393        }
394        self.root.splay_by(SeekBySize::new(index));
395        self.length -= 1;
396        let node = self.root.take_root().unwrap().into_dying();
397        unsafe { Some(node.into_data(self.alloc.deref_mut()).key) }
398    }
More examples
Hide additional examples
crates/competitive/src/data_structure/splay_tree/sized_map.rs (line 227)
217    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
218    where
219        K: Borrow<Q>,
220        Q: Ord + ?Sized,
221    {
222        if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
223            return None;
224        }
225        self.length -= 1;
226        let node = self.root.take_root().unwrap().into_dying();
227        unsafe { Some((node.into_data(self.alloc.deref_mut()).0).1) }
228    }
229    pub fn remove_at(&mut self, index: usize) -> Option<(K, V)> {
230        if index >= self.length {
231            return None;
232        }
233        self.splay_at(index);
234        self.length -= 1;
235        let node = self.root.take_root().unwrap().into_dying();
236        unsafe { Some(node.into_data(self.alloc.deref_mut()).0) }
237    }
Source§

impl<S> NodeRef<Owned, S>
where S: SplaySpec,

Source

pub fn splay_by<Seeker>(self, seeker: Seeker) -> (Ordering, Self)
where Seeker: SplaySeeker<S = S>,

cmp(key): Ordering between splaying and key

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 457)
450    pub fn merge(mut self, mut other: Self) -> Self {
451        if other.reborrow().left().is_none() {
452            S::top_down(other.borrow_datamut());
453            other.borrow_mut().set_left(Some(self));
454            S::bottom_up(other.borrow_datamut());
455            other
456        } else {
457            self = self.splay_by(SeekRight::new()).1;
458            self.borrow_mut().set_right(Some(other));
459            S::bottom_up(self.borrow_datamut());
460            self
461        }
462    }
463}
464
465impl<S> Root<S>
466where
467    S: SplaySpec,
468{
469    pub fn new(root: Option<NodeRef<marker::Owned, S>>) -> Self {
470        Self { root }
471    }
472    pub unsafe fn from_single_nodes(nodes: Vec<NodeRef<marker::Owned, S>>) -> Self {
473        unsafe { Self::from_single_nodes_inner(&nodes) }
474    }
475    unsafe fn from_single_nodes_inner(nodes: &[NodeRef<marker::Owned, S>]) -> Self {
476        if nodes.is_empty() {
477            Self::new(None)
478        } else {
479            let m = nodes.len() / 2;
480            let left = unsafe { Self::from_single_nodes_inner(&nodes[..m]) };
481            let right = unsafe { Self::from_single_nodes_inner(&nodes[m + 1..]) };
482            let mut node = NodeRef::new(nodes[m].node);
483            node.borrow_mut().set_left(left.root);
484            node.borrow_mut().set_right(right.root);
485            S::bottom_up(node.borrow_datamut());
486            Self::new(Some(node))
487        }
488    }
489    pub fn is_empty(&self) -> bool {
490        self.root.is_none()
491    }
492    pub fn root(&self) -> Option<NodeRef<marker::Immut<'_>, S>> {
493        Some(self.root.as_ref()?.reborrow())
494    }
495    pub fn root_data_mut(&mut self) -> Option<NodeRef<marker::DataMut<'_>, S>> {
496        Some(self.root.as_mut()?.borrow_datamut())
497    }
498    pub fn splay_by<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
499    where
500        Seeker: SplaySeeker<S = S>,
501    {
502        let (ord, root) = self.root.take()?.splay_by(seeker);
503        self.root = Some(root);
504        Some(ord)
505    }
506    pub fn insert_left(&mut self, mut node: NodeRef<marker::Owned, S>) {
507        self.root = Some(match self.root.take() {
508            Some(root) => root.insert_left(node),
509            None => {
510                S::bottom_up(node.borrow_datamut());
511                node
512            }
513        });
514    }
515    pub fn insert_right(&mut self, mut node: NodeRef<marker::Owned, S>) {
516        self.root = Some(match self.root.take() {
517            Some(root) => root.insert_right(node),
518            None => {
519                S::bottom_up(node.borrow_datamut());
520                node
521            }
522        });
523    }
524    pub fn insert_first(&mut self, mut node: NodeRef<marker::Owned, S>) {
525        self.root = Some(match self.root.take() {
526            Some(root) => root.insert_first(node),
527            None => {
528                S::bottom_up(node.borrow_datamut());
529                node
530            }
531        });
532    }
533    pub fn insert_last(&mut self, mut node: NodeRef<marker::Owned, S>) {
534        self.root = Some(match self.root.take() {
535            Some(root) => root.insert_last(node),
536            None => {
537                S::bottom_up(node.borrow_datamut());
538                node
539            }
540        });
541    }
542    pub fn take_root(&mut self) -> Option<NodeRef<marker::Owned, S>> {
543        let mut root = self.root.take()?;
544        let right = root.borrow_mut().take_right();
545        self.root = root.borrow_mut().take_left();
546        self.append(&mut Self::new(right));
547        Some(root)
548    }
549    pub fn take_first(&mut self) -> Option<NodeRef<marker::Owned, S>> {
550        let mut root = self.root.take()?.splay_by(SeekLeft::new()).1;
551        let right = root.borrow_mut().take_right();
552        self.root = right;
553        Some(root)
554    }
555    pub fn take_last(&mut self) -> Option<NodeRef<marker::Owned, S>> {
556        let mut root = self.root.take()?.splay_by(SeekRight::new()).1;
557        let left = root.borrow_mut().take_left();
558        self.root = left;
559        Some(root)
560    }
Source

pub fn insert_left(self, node: Self) -> Self

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 508)
506    pub fn insert_left(&mut self, mut node: NodeRef<marker::Owned, S>) {
507        self.root = Some(match self.root.take() {
508            Some(root) => root.insert_left(node),
509            None => {
510                S::bottom_up(node.borrow_datamut());
511                node
512            }
513        });
514    }
Source

pub fn insert_right(self, node: Self) -> Self

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 517)
515    pub fn insert_right(&mut self, mut node: NodeRef<marker::Owned, S>) {
516        self.root = Some(match self.root.take() {
517            Some(root) => root.insert_right(node),
518            None => {
519                S::bottom_up(node.borrow_datamut());
520                node
521            }
522        });
523    }
Source

pub fn insert_first(self, node: Self) -> Self

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 526)
524    pub fn insert_first(&mut self, mut node: NodeRef<marker::Owned, S>) {
525        self.root = Some(match self.root.take() {
526            Some(root) => root.insert_first(node),
527            None => {
528                S::bottom_up(node.borrow_datamut());
529                node
530            }
531        });
532    }
Source

pub fn insert_last(self, node: Self) -> Self

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 535)
533    pub fn insert_last(&mut self, mut node: NodeRef<marker::Owned, S>) {
534        self.root = Some(match self.root.take() {
535            Some(root) => root.insert_last(node),
536            None => {
537                S::bottom_up(node.borrow_datamut());
538                node
539            }
540        });
541    }
Source

pub fn merge(self, other: Self) -> Self

Examples found in repository?
crates/competitive/src/data_structure/splay_tree/node.rs (line 584)
581    pub fn append(&mut self, other: &mut Self) {
582        self.root = match (self.root.take(), other.root.take()) {
583            (Some(node), None) | (None, Some(node)) => Some(node),
584            (Some(left), Some(right)) => Some(left.merge(right)),
585            (None, None) => None,
586        }
587    }

Trait Implementations§

Source§

impl<'a, S> Clone for NodeRef<Immut<'a>, S>
where S: SplaySpec, S::T: 'a,

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a, S> Copy for NodeRef<Immut<'a>, S>
where S: SplaySpec, S::T: 'a,

Auto Trait Implementations§

§

impl<B, S> Freeze for NodeRef<B, S>

§

impl<B, S> RefUnwindSafe for NodeRef<B, S>

§

impl<B, S> !Send for NodeRef<B, S>

§

impl<B, S> !Sync for NodeRef<B, S>

§

impl<B, S> Unpin for NodeRef<B, S>
where B: Unpin,

§

impl<B, S> UnwindSafe for NodeRef<B, S>
where B: UnwindSafe, <S as SplaySpec>::T: RefUnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.