returns NULL if successful, existing cb_node if duplicate */
| 33 | |
| 34 | /* returns NULL if successful, existing cb_node if duplicate */ |
| 35 | struct cb_node *cb_insert(struct cb_tree *t, struct cb_node *node, size_t klen) |
| 36 | { |
| 37 | size_t newbyte, newotherbits; |
| 38 | uint8_t c; |
| 39 | int newdirection; |
| 40 | struct cb_node **wherep, *p; |
| 41 | uint8_t *node_key, *p_key; |
| 42 | |
| 43 | assert(!((uintptr_t)node & 1)); /* allocations must be aligned */ |
| 44 | |
| 45 | if (!t->root) { /* insert into empty tree */ |
| 46 | t->root = node; |
| 47 | return NULL; /* success */ |
| 48 | } |
| 49 | |
| 50 | node_key = cb_node_key(t, node); |
| 51 | |
| 52 | /* see if a node already exists */ |
| 53 | p = cb_internal_best_match(t->root, node_key, klen); |
| 54 | p_key = cb_node_key(t, p); |
| 55 | |
| 56 | /* find first differing byte */ |
| 57 | for (newbyte = 0; newbyte < klen; newbyte++) { |
| 58 | if (p_key[newbyte] != node_key[newbyte]) |
| 59 | goto different_byte_found; |
| 60 | } |
| 61 | return p; /* element exists, let user deal with it */ |
| 62 | |
| 63 | different_byte_found: |
| 64 | newotherbits = p_key[newbyte] ^ node_key[newbyte]; |
| 65 | newotherbits |= newotherbits >> 1; |
| 66 | newotherbits |= newotherbits >> 2; |
| 67 | newotherbits |= newotherbits >> 4; |
| 68 | newotherbits = (newotherbits & ~(newotherbits >> 1)) ^ 255; |
| 69 | c = p_key[newbyte]; |
| 70 | newdirection = (1 + (newotherbits | c)) >> 8; |
| 71 | |
| 72 | node->byte = newbyte; |
| 73 | node->otherbits = newotherbits; |
| 74 | node->child[1 - newdirection] = node; |
| 75 | |
| 76 | /* find a place to insert it */ |
| 77 | wherep = &t->root; |
| 78 | for (;;) { |
| 79 | struct cb_node *q; |
| 80 | size_t direction; |
| 81 | |
| 82 | p = *wherep; |
| 83 | if (!(1 & (uintptr_t)p)) |
| 84 | break; |
| 85 | q = cb_node_of(p); |
| 86 | if (q->byte > newbyte) |
| 87 | break; |
| 88 | if (q->byte == newbyte && q->otherbits > newotherbits) |
| 89 | break; |
| 90 | c = q->byte < klen ? node_key[q->byte] : 0; |
| 91 | direction = (1 + (q->otherbits | c)) >> 8; |
| 92 | wherep = q->child + direction; |
no test coverage detected