shithub: scc

Download patch

ref: e15a440b400655c6457fd2486c9636bd53419631
parent: e0710377d1a0134913d8e52cb5eb41f3badde147
author: Roberto E. Vargas Caballero <k0ga@shike2.com>
date: Tue Sep 11 04:44:21 EDT 2018

[lib/c] Improve strspn and strcspn

Avoid cuadratic behaviour.

--- a/lib/c/strcspn.c
+++ b/lib/c/strcspn.c
@@ -4,15 +4,16 @@
 size_t
 strcspn(const char *s1, const char *s2)
 {
+	char buf[256];
+	unsigned char ch;
 	size_t n;
-	int c;
-	const char *p;
 
-	for (n = 0; c = *s1++; ++n) {
-		for (p = s2; *p && *p != c; ++p)
-			;
-		if (*p == c)
-			break;
-	}
+	memset(buf, 0, sizeof(buf));
+	while (ch = *s2++)
+		buf[ch] = 1;
+
+	for (n = 0; (ch = *s1++) && !buf[ch]; ++n)
+		;
+
 	return n;
 }
--- a/lib/c/strspn.c
+++ b/lib/c/strspn.c
@@ -4,15 +4,16 @@
 size_t
 strspn(const char *s1, const char *s2)
 {
+	char buf[256];
+	unsigned char ch;
 	size_t n;
-	int c;
-	const char *p;
 
-	for (n = 0; c = *s1++; ++n) {
-		for (p = s2; *p && *p != c; ++p)
-			;
-		if (*p == '\0')
-			break;
-	}
+	memset(buf, 0, sizeof(buf));
+	while (ch = *s2++)
+		buf[ch] = 1;
+
+	for (n = 0; (ch = *s1++) && buf[ch]; ++n)
+		;
+
 	return n;
 }