nasmlib: added string replace (strrep) utility function
authorKeith Kanios <keith@kanios.net>
Fri, 8 Apr 2011 05:23:21 +0000 (00:23 -0500)
committerKeith Kanios <keith@kanios.net>
Fri, 8 Apr 2011 05:23:21 +0000 (00:23 -0500)
nasmlib.c
nasmlib.h

index d70f6c2..538223f 100644 (file)
--- a/nasmlib.c
+++ b/nasmlib.c
@@ -290,6 +290,86 @@ char *nasm_strsep(char **stringp, const char *delim)
 }
 #endif
 
+char *nasm_strrep(const char *str, const char *sub, char *lin, bool casesense)
+{
+    char *outline = lin;
+    char *temp1 = NULL;
+    char *temp2 = NULL;
+    char *l, *lp, *lt, *ls;
+    int count = 0;
+    int str_len, sub_len, lin_len;
+    int i, c;
+
+    str_len = strlen(str);
+    sub_len = strlen(sub);
+    lin_len = strlen(lin);
+
+    if ((str_len > 0) && (lin_len > 0)) {
+        if (casesense == false) {
+            l = nasm_strdup(lin);
+            for (i = 0; i < lin_len; i++) {
+                l[i] = (char)nasm_tolower_tab[(int)l[i]];
+            }
+            ls = nasm_strdup(str);
+            for (i = 0; i < str_len; i++) {
+                ls[i] = (char)nasm_tolower_tab[(int)ls[i]];
+            }
+            temp1 = l;
+            temp2 = ls;
+        } else {
+            l = lin;
+            ls = (char *)str;
+        }
+
+        lt = l;
+
+        do {
+            l = strstr(l, ls);
+            if (l != NULL) {
+                count ++;
+                l += str_len;
+            }
+        } while (l != NULL);
+
+        if (count > 0) {
+            i = (lin_len - (count * str_len));
+            i += (count * sub_len);
+            outline = nasm_zalloc(i);
+
+            l = lt;
+
+            for (i = 0; i < count; i ++) {
+                lp = l;
+                l = strstr(l, ls);
+                c = (lp - l);
+                if (c > 0) {
+                    strncat(outline, lt, c);
+                }
+                strncat(outline, sub, sub_len);
+                l += str_len;
+                lt += str_len;
+            }
+
+            c = (l - lin);
+            if (c < lin_len) {
+                strcat(outline, lt);
+            }
+
+            if (temp2 != NULL) {
+                nasm_free(temp2);
+            }
+
+            if (temp1 != NULL) {
+                nasm_free(temp1);
+            }
+
+            nasm_free(lin);
+        }
+    }
+
+    return outline;
+}
+
 
 #define lib_isnumchar(c)   (nasm_isalnum(c) || (c) == '$' || (c) == '_')
 #define numvalue(c)  ((c)>='a' ? (c)-'a'+10 : (c)>='A' ? (c)-'A'+10 : (c)-'0')
index 2c335e1..12f9ca1 100644 (file)
--- a/nasmlib.h
+++ b/nasmlib.h
@@ -205,6 +205,11 @@ int nasm_memicmp(const char *, const char *, size_t);
 char *nasm_strsep(char **stringp, const char *delim);
 #endif
 
+/*
+ * Replace all instances of `str` with `sub` in `lin`
+ */
+char *nasm_strrep(const char *str, const char *sub, char *lin, bool casesense);
+
 
 /*
  * Convert a string into a number, using NASM number rules. Sets