]> PatchyGit - patchyircd.git/commitdiff
map: use algorithms
authorEgor <egor@patchysicp.xyz>
Thu, 5 Jun 2025 17:58:25 +0000 (20:58 +0300)
committerEgor <egor@patchysicp.xyz>
Thu, 5 Jun 2025 17:58:25 +0000 (20:58 +0300)
src/map.cpp

index fe70d96..dfe6ae0 100644 (file)
@@ -4,24 +4,13 @@
 #include "map.h"
 #include <stdlib.h>
 #include <string.h>
+#include <algorithm>
 static int ent_find(map_base *root, const char *key, int *found)
 {
-       int lo = 0;
-       int hi = root->len;
-       while (lo != hi) {
-               int mid = (lo+hi)/2;
-               int cmp = strcmp(root->ptr[mid].key, key);
-               if (cmp == 0) {
-                       *found = 1;
-                       return mid;
-               } if (cmp > 0) {
-                       hi = mid;
-               } else {
-                       lo = mid+1;
-               }
-       }
-       *found = 0;
-       return lo;
+       auto it = std::partition_point(root->ptr, root->ptr + root->len,
+                       [key](const auto &p){ return strcmp(p.key, key) < 0; });
+       *found = it != root->ptr + root->len && !strcmp(it->key, key);
+       return it - root->ptr;
 }
 void *map_base::_get(const char *key)
 {
@@ -38,7 +27,7 @@ int map_base::_set(const char *key, const void *value, void **oldvalue)
                        *oldvalue = ptr[i].value;
                if (!value) {
                        free(ptr[i].key);
-                       memmove(ptr+i, ptr+i+1, sizeof(map_value)*(len-(i+1)));
+                       std::copy(ptr+i+1, ptr+len, ptr+i);
                        len--;
                } else {
                        ptr[i].value = (void *)value;
@@ -60,7 +49,7 @@ int map_base::_set(const char *key, const void *value, void **oldvalue)
                        if (!nkey)
                                return -1;
                        memcpy(nkey, key, slen);
-                       memmove(ptr+i+1, ptr+i, sizeof(map_value)*(len-i));
+                       std::copy_backward(ptr+i, ptr+len, ptr+len+1);
                        len++;
                        ptr[i].key = nkey;
                        ptr[i].value = (void *)value;