]> pd.if.org Git - zpackage/commitdiff
add zpm function to quote a string for sqlite
authorNathan Wagner <nw@hydaspes.if.org>
Sat, 15 Sep 2018 08:03:29 +0000 (08:03 +0000)
committerNathan Wagner <nw@hydaspes.if.org>
Mon, 17 Sep 2018 12:13:04 +0000 (12:13 +0000)
lib/quote.c [new file with mode: 0644]

diff --git a/lib/quote.c b/lib/quote.c
new file mode 100644 (file)
index 0000000..61d28c3
--- /dev/null
@@ -0,0 +1,35 @@
+#include <stddef.h>
+
+#include "sqlite3.h"
+
+int zpm_quote(char *value, char *dest, size_t n) {
+       size_t dlen = 0;
+       int nch = 0;
+       char *s;
+
+       /* figure out length of quoted string */
+       for (s = value; *s; s++) {
+               dlen++;
+               if (*s == '\'') dlen++;
+       }
+
+       /* if there's enough room for the string and the terminating null
+        * byte, quote the string
+        */
+       if (dest && dlen < n) {
+               while (*value) {
+                       if (*value == '\'') {
+                               *dest++ = '\'';
+                               nch++;
+                       }
+                       *dest++ = *value++;
+                       nch++;
+               }
+               dest[nch] = 0;
+       }
+
+       /* returns either the number of characters written or would
+        * be written
+        */
+       return dlen;
+}