Repository navigation
Expand file tree
/
Copy pathtri_insert_indicator_parse.c
More file actions
61 lines (49 loc) · 2.32 KB
/
Copy pathtri_insert_indicator_parse.c
File metadata and controls
61 lines (49 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#define MAX_INDICATOR_LEN 512 // Define a sane limit
void ti_insert_indicator_sparse(TrieNode *root, const char *indicator) {
TrieNode *current = root;
int length = strlen(indicator);
for (int i = 0; i < length; i++) {
char key_char = indicator[i];
// 1. Search for Existing Child using Binary Search (Faster than linear)
ChildPair *found_pair = (ChildPair *)bsearch(
&key_char,
current->children,
current->num_children,
sizeof(ChildPair),
compare_child_pairs
);
if (found_pair != NULL) {
// Path exists: Move to the next node and continue loop
current = found_pair->node;
continue;
}
// 2. Path DOES NOT exist: Prepare to insert a NEW ChildPair
// Find the index where the new char should go to maintain sorted order
int insert_idx = find_insertion_index(current, key_char);
// Check for and handle array capacity limit
if (!grow_children_array(current)) {
fprintf(stderr, "Fatal error: Could not grow array during insertion.\n");
return;
}
// 3. Shift elements using memmove (OPTIMIZATION)
// Move all elements from insert_idx to the end, one position right
// This creates a "hole" at insert_idx.
if (insert_idx < current->num_children) {
size_t bytes_to_shift = (current->num_children - insert_idx) * sizeof(ChildPair);
// memmove handles overlapping memory regions safely
memmove(
¤t->children[insert_idx + 1], // Destination (shifted one right)
¤t->children[insert_idx], // Source
bytes_to_shift
);
}
// 4. Create and Insert the New ChildPair
current->children[insert_idx].key_char = key_char;
current->children[insert_idx].node = create_sparse_trie_node(); // Create a new node!
current->num_children++; // Increment the count
// Move to the newly created node
current = current->children[insert_idx].node;
}
// Mark the final node as the end of a complete malicious indicator
current->is_malicious_indicator = 1;
}