]> git.ipfire.org Git - location/libloc.git/commitdiff
network-list: Check last element before doing binary search
authorMichael Tremer <michael.tremer@ipfire.org>
Tue, 24 Nov 2020 19:39:35 +0000 (19:39 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Tue, 24 Nov 2020 19:39:35 +0000 (19:39 +0000)
This is helpful because very often we walk through a list in
order and are most interested in the last element.

Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/network-list.c

index 7e8b5f3a616f08f3d2ee793947e1efa6e0f05f68..c86ad07dc35d51bb30dac8185e31ad6abafba92e 100644 (file)
@@ -137,8 +137,26 @@ static off_t loc_network_list_find(struct loc_network_list* list,
                struct loc_network* network, int* found) {
        off_t lo = 0;
        off_t hi = list->size - 1;
+       int result;
 
-       *found = 0;
+       // Since we are working on an ordered list, there is often a good chance that
+       // the network we are looking for is at the end or has to go to the end.
+       if (hi >= 0) {
+               result = loc_network_cmp(network, list->elements[hi]);
+
+               // Match, so we are done
+               if (result == 0) {
+                       *found = 1;
+
+                       return hi;
+
+               // This needs to be added after the last one
+               } else if (result > 0) {
+                       *found = 0;
+
+                       return hi + 1;
+               }
+       }
 
 #ifdef ENABLE_DEBUG
        // Save start time
@@ -151,7 +169,7 @@ static off_t loc_network_list_find(struct loc_network_list* list,
                i = (lo + hi) / 2;
 
                // Check if this is a match
-               int result = loc_network_cmp(network, list->elements[i]);
+               result = loc_network_cmp(network, list->elements[i]);
 
                if (result == 0) {
                        *found = 1;
@@ -173,6 +191,8 @@ static off_t loc_network_list_find(struct loc_network_list* list,
                        hi = i - 1;
        }
 
+       *found = 0;
+
 #ifdef ENABLE_DEBUG
        clock_t end = clock();