Merge branch 'master' into jennifer/trp-devel
[trust_router.git] / common / tr_name.c
index b5e1526..8837b02 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 
-#include <tr_name.h>
+#include <trust_router/tr_name.h>
 
-TR_NAME *tr_new_name (char *name) 
+void tr_free_name (TR_NAME *name)
+{
+  if (name->buf) {
+    free (name->buf);
+    name->buf = NULL;
+  }
+
+  free(name);
+}
+
+TR_NAME *tr_new_name (const char *name) 
 {
   TR_NAME *new;
 
-  if (new = malloc(sizeof(TR_NAME))) { 
+  if (new = malloc(sizeof(TR_NAME))) {
     new->len = strlen(name);
     if (new->buf = malloc((new->len)+1)) {
       strcpy(new->buf, name);
+    } else {
+      free(new);
+      new=NULL;
     }
   }
   return new;
 }
 
-TR_NAME *tr_dup_name (TR_NAME *from) 
+TR_NAME *tr_dup_name (TR_NAME *from)
 {
   TR_NAME *to;
 
-  if (to = malloc(sizeof(TR_NAME))) {
+  if (!from) {
+    return NULL;
+  }
+
+  if (NULL != (to = malloc(sizeof(TR_NAME)))) {
     to->len = from->len;
-    if (to->buf = malloc(to->len+1)) {
+    if (NULL != (to->buf = malloc(to->len+1))) {
       strncpy(to->buf, from->buf, from->len);
       to->buf[to->len] = 0;    /* NULL terminate for debugging printf()s */
     }
   }
-
   return to;
 }
+
+int tr_name_cmp(TR_NAME *one, TR_NAME *two)
+{
+  int len=one->len;
+  int cmp=0;
+
+  if (two->len<one->len)
+    len=two->len; /* len now min(one->len,two->len) */
+
+  cmp=strncmp(one->buf, two->buf, len);
+  if (cmp==0) {
+    if (one->len<two->len)
+      return -1;
+    else if (one->len==two->len)
+      return 0;
+    else
+      return 1;
+  }
+  return cmp;
+}
+
+void tr_name_strlcat(char *dest, const TR_NAME *src, size_t len)
+{
+  size_t used_len;
+  if (src->len >= len)
+    used_len = len-1;
+  else used_len = src->len;
+  if (used_len > 0)
+    strncat(dest, src->buf, used_len);
+  else dest[0] = '\0';
+}
+
+  
+char * tr_name_strdup(TR_NAME *src)
+{
+  char *s = calloc(src->len+1, 1);
+  if (s) {
+    memcpy(s, src->buf, src->len);
+    s[src->len] = '\0';
+  }
+  return s;
+}