Last active
December 3, 2016 01:27
-
-
Save a-square/c4c67897903fc3e44119a2f172a8b42f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* gcc -O3 -std=c99 -o match match.c */ | |
#include <unistd.h> | |
char* VALUES[] = { "false\n", "true\n" }; | |
unsigned long SIZES[] = { 6, 5 }; | |
int match(const char* restrict str, const char* restrict pattern) { | |
const char* sBegin; | |
const char* sCur; | |
const char* pCur; | |
char sC; | |
char pC; | |
for (sBegin = str; *sBegin; ++sBegin) { | |
sCur = sBegin; | |
pCur = pattern; | |
sC = *sCur; | |
pC = *pCur; | |
while (sC && pC && sC == pC) { | |
sC = *(++sCur); | |
pC = *(++pCur); | |
} | |
/* | |
* sC, pC | |
* 0, 0 => 1 - both ran out (match) | |
* 0, x => 0 - str ran out first => strlen(sBegin) < strlen(pattern) | |
* x, 0 => 1 - pattern ran out first (match) | |
* x, y => ? - didn't match, but there is hope | |
*/ | |
if (!sC || !pC) | |
return !pC; | |
} | |
/* the str was empty */ | |
return !*pattern; | |
} | |
/* | |
void test_match(char* str, char* pattern, int result) { | |
int m; | |
m = match(str, pattern); | |
printf("match(\"%s\", \"%s\") == %s [expected %s]\n", str, pattern, VALUES[m], VALUES[result]); | |
} | |
*/ | |
int main(int argc, char** argv) { | |
/* | |
test_match("", "", 1); | |
test_match("12345", "", 1); | |
test_match("", "1", 0); | |
test_match("12345", "123", 1); | |
test_match("12345", "12_", 0); | |
test_match("12345", "34", 1); | |
test_match("12345", "_4", 0); | |
test_match("12345", "5", 1); | |
*/ | |
int result = match(argv[1], argv[2]); | |
ssize_t written = write(1, VALUES[result], SIZES[result]); | |
(void)written; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment