MCPcopy Index your code
hub / github.com/douchuan/algorithm / insert

Function insert

src/tree/binary/bst.rs:69–103  ·  view source on GitHub ↗

Ok(inserted node) Err(()): element exists # Safety This is highly unsafe, due to pointer

(
    root: Option<NonNull<Node<K, V>>>,
    key: K,
    val: V,
)

Source from the content-addressed store, hash-verified

67///
68/// This is highly unsafe, due to pointer
69pub unsafe fn insert<K, V>(
70 root: Option<NonNull<Node<K, V>>>,
71 key: K,
72 val: V,
73) -> Result<NonNull<Node<K, V>>, ()>
74where
75 K: Ord,
76{
77 let mut nq = NodeQuery::new(root);
78 let mut parent = None;
79 while nq.is_some() {
80 parent = nq.node;
81 match key.cmp(nq.get_key().unwrap()) {
82 Ordering::Less => nq = nq.left(),
83 Ordering::Greater => nq = nq.right(),
84 Ordering::Equal => {
85 nq.set_entry((key, Some(val))); // update val
86 return Err(());
87 }
88 }
89 }
90
91 //插入x
92 let mut x = Node::new_entry(key, val);
93 if let Some(mut node) = parent {
94 if x.as_ref().key < node.as_ref().key {
95 node.as_mut().left = Some(x);
96 } else {
97 node.as_mut().right = Some(x);
98 }
99 x.as_mut().parent = parent;
100 }
101
102 Ok(x)
103}
104
105/// # Safety
106///

Callers 1

insertMethod · 0.70

Calls 7

ErrEnum · 0.85
is_someMethod · 0.80
get_keyMethod · 0.80
set_entryMethod · 0.80
cmpMethod · 0.45
leftMethod · 0.45
rightMethod · 0.45

Tested by

no test coverage detected