improved util_header_callback by using sstr_t

Thu, 15 Oct 2015 16:36:07 +0200

author
Mike Becker <universe@uap-core.de>
date
Thu, 15 Oct 2015 16:36:07 +0200
changeset 173
947843245525
parent 171
254326cbc1bc
child 174
e7e56c56d126

improved util_header_callback by using sstr_t

libidav/utils.c file | annotate | diff | comparison | revisions
--- a/libidav/utils.c	Thu Oct 15 16:16:44 2015 +0200
+++ b/libidav/utils.c	Thu Oct 15 16:36:07 2015 +0200
@@ -286,65 +286,44 @@
 static size_t util_header_callback(char *buffer, size_t size,
         size_t nitems, void *data) {
     
-    char *duped; // local variable for string duplicates
+    sstr_t sbuffer = sstrn(buffer, size*nitems);
     
     UcxMap *map = (UcxMap*) data;
     
     // if we get a status line, clear the map and exit
-    if(size*nitems >= 5 && !strncmp("HTTP/", buffer, 5)) {
+    if(sstrprefix(sbuffer, S("HTTP/"))) {
         ucx_map_free_content(map, free);
         ucx_map_clear(map);
         return size*nitems;
     }
     
     // if we get the terminating CRLF, just exit
-    if (size*nitems == 2 && !strncmp("\r\n", buffer, 2)) {
+    if(!sstrcmp(sbuffer, S("\r\n"))) {
         return 2;
     }
     
+    sstr_t key = sbuffer;
+    sstr_t value = sstrchr(sbuffer, ':');
     
-    // get header key
-    size_t s = 0;
-    do {
-        s++;
-    } while(buffer[s] != ':');
-    char *value = buffer+s+1;
-    
-    // remove trailing spaces
-    while(isspace(buffer[s-1])) {
-        s--;
+    if(value.length == 0) {
+        return 0; // invalid header line
     }
     
-    // save key as all lower case
-    duped = malloc(s);
-    for(size_t i = 0;i<s;i++) {
-        duped[i] = tolower(buffer[i]);
-    }
-    UcxKey key = ucx_key(duped, s);
+    key.length = value.ptr - key.ptr;
+    value.ptr++; value.length--;
     
-    // get trimmed header value
-    while(isspace(*value)) {
-        value++;
-    }
-    s = size*nitems - (value - buffer);
-    while(isspace(value[s-1])) {
-        s--;
+    key = sstrdup(sstrtrim(key));
+    value = sstrdup(sstrtrim(value));
+    
+    for(size_t i = 0;i<key.length;i++) {
+        key.ptr[i] = tolower(key.ptr[i]);
     }
     
-    // copy header value and append NULL byte (curl does not provide one)
-    duped = malloc(s+1);
-    memcpy(duped, value, s+1);
-    duped[s] = '\0';
+    ucx_map_sstr_put(map, key, value.ptr);
     
-    char *oldval = ucx_map_get(map, key);
-    if(oldval) {
-        free(oldval);
-    }
+    free(key.ptr);
     
-    ucx_map_put(map, key, duped);
-    free(key.data); // ucx_map_put made a copy, so we free this memory
-    
-    return nitems * size;    
+    return sbuffer.length;
 }
 
 void util_capture_header(CURL *handle, UcxMap* map) {

mercurial