add unit tests, make code more obvious

master
leitner 10 months ago
parent 0d788fb946
commit 1644367743

@ -1,19 +1,21 @@
#include "str.h"
size_t str_chr(const char *in, char needle) {
#if 0
register const char* t=in;
register const char c=needle;
for (;;) {
if (!*t || *t==c) break;
++t;
if (!*t || *t==c) break;
++t;
if (!*t || *t==c) break;
++t;
if (!*t || *t==c) break;
++t;
if (!*t || *t==c) break; else ++t;
if (!*t || *t==c) break; else ++t;
if (!*t || *t==c) break; else ++t;
if (!*t || *t==c) break; else ++t;
}
return (size_t)(t-in);
#else
size_t i;
for (i=0; in[i] && in[i]!=needle; ++i) ;
return i;
#endif
}
#ifdef UNITTEST

@ -23,3 +23,16 @@ int str_diffn(const char* a, const char* b, size_t limit) {
}
return j;
}
#ifdef UNITTEST
#include <assert.h>
#include <string.h>
int main() {
assert(str_diffn("foo","foo",3)==0);
assert(str_diffn("foo","fob",3)==('o'-'b'));
assert(str_diffn("foo","foox",4)==(-'x'));
assert(str_diffn("foox","foo",4)=='x');
assert(str_diffn("foo","fob",2)==0);
}
#endif

@ -15,3 +15,13 @@ size_t str_len(const char* in) {
}
return (size_t)(t-in);
}
#ifdef UNITTEST
#include <assert.h>
int main() {
assert(str_len("foo")==3);
assert(str_len("")==0);
assert(str_len("fnord")==5);
return 0;
}
#endif

@ -1,6 +1,11 @@
#include "str.h"
size_t str_rchr(const char *in, char needle) {
#if 1
size_t i,j=-1;
for (i=0; in[i]; ++i) if (in[i]==needle) j=i;
return i<j ? i : j;
#else
register const char* t=in;
register const char c=needle;
register const char* found=0;
@ -22,4 +27,15 @@ size_t str_rchr(const char *in, char needle) {
++t;
}
return (size_t)((found?found:t)-in);
#endif
}
#ifdef UNITTEST
#include <assert.h>
int main() {
assert(str_rchr("fnord",'r')==3);
assert(str_rchr("frord",'r')==3);
assert(str_rchr("fnord",'x')==5);
return 0;
}
#endif

@ -2,6 +2,14 @@
/* str_start returns 1 if the b is a prefix of a, 0 otherwise */
int str_start(const char* a, const char* b) {
#if 1
size_t i;
for (i=0; ; ++i) {
if (!b[i]) return 1;
if (a[i]!=b[i]) break;
}
return 0;
#else
register const char* s=a;
register const char* t=b;
for (;;) {
@ -19,4 +27,16 @@ int str_start(const char* a, const char* b) {
++s; ++t;
}
return 0;
#endif
}
#ifdef UNITTEST
#include <assert.h>
int main() {
assert(str_start("fnord","no")==0);
assert(str_start("fnord","fno")==1);
assert(str_start("fnord","fnord")==1);
assert(str_start("fnord","fnord1")==0);
return 0;
}
#endif

Loading…
Cancel
Save