| 1 |
|
|---|
| 2 |
#include "tst.h" |
|---|
| 3 |
#include <stdio.h> |
|---|
| 4 |
#include <stdlib.h> |
|---|
| 5 |
#include <assert.h> |
|---|
| 6 |
|
|---|
| 7 |
void *tst_search(unsigned char *key, struct tst *tst, int *prefix_len) |
|---|
| 8 |
{ |
|---|
| 9 |
struct node *current_node; |
|---|
| 10 |
void *longest_match = NULL; |
|---|
| 11 |
int key_index; |
|---|
| 12 |
|
|---|
| 13 |
assert(key != NULL && "key can't be NULL"); |
|---|
| 14 |
assert(tst != NULL && "tst can't be NULL"); |
|---|
| 15 |
|
|---|
| 16 |
if(key[0] == 0) |
|---|
| 17 |
return NULL; |
|---|
| 18 |
|
|---|
| 19 |
if(tst->head[(int)key[0]] == NULL) |
|---|
| 20 |
return NULL; |
|---|
| 21 |
|
|---|
| 22 |
|
|---|
| 23 |
if(prefix_len) *prefix_len = 0; |
|---|
| 24 |
current_node = tst->head[(int)key[0]]; |
|---|
| 25 |
key_index = 1; |
|---|
| 26 |
|
|---|
| 27 |
while (current_node != NULL) |
|---|
| 28 |
{ |
|---|
| 29 |
if(key[key_index] == current_node->value) |
|---|
| 30 |
{ |
|---|
| 31 |
if(current_node->value == 0) { |
|---|
| 32 |
if(prefix_len) *prefix_len = key_index; |
|---|
| 33 |
return current_node->middle; |
|---|
| 34 |
} else { |
|---|
| 35 |
current_node = current_node->middle; |
|---|
| 36 |
if(current_node && current_node->value == 0) { |
|---|
| 37 |
if(prefix_len) *prefix_len = key_index+1; |
|---|
| 38 |
longest_match = current_node->middle; |
|---|
| 39 |
} |
|---|
| 40 |
|
|---|
| 41 |
key_index++; |
|---|
| 42 |
continue; |
|---|
| 43 |
} |
|---|
| 44 |
} |
|---|
| 45 |
else if( ((current_node->value == 0) && (key[key_index] < 64)) || |
|---|
| 46 |
((current_node->value != 0) && (key[key_index] < |
|---|
| 47 |
current_node->value)) ) |
|---|
| 48 |
{ |
|---|
| 49 |
if(current_node->value == 0) { |
|---|
| 50 |
if(prefix_len) *prefix_len = key_index; |
|---|
| 51 |
longest_match = current_node->middle; |
|---|
| 52 |
} |
|---|
| 53 |
current_node = current_node->left; |
|---|
| 54 |
continue; |
|---|
| 55 |
} |
|---|
| 56 |
else |
|---|
| 57 |
{ |
|---|
| 58 |
if(current_node->value == 0) { |
|---|
| 59 |
if(prefix_len) *prefix_len = key_index; |
|---|
| 60 |
longest_match = current_node->middle; |
|---|
| 61 |
} |
|---|
| 62 |
current_node = current_node->right; |
|---|
| 63 |
continue; |
|---|
| 64 |
} |
|---|
| 65 |
} |
|---|
| 66 |
|
|---|
| 67 |
return longest_match; |
|---|
| 68 |
} |
|---|