Last active
September 30, 2024 15:23
-
-
Save develhox/abfe15c40f2d9daebc35 to your computer and use it in GitHub Desktop.
Switch operand implementation for the strings
This file contains 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
#ifndef __SWITCHS_H__ | |
#define __SWITCHS_H__ | |
#include <string.h> | |
#include <regex.h> | |
#include <stdbool.h> | |
/** Begin a switch for the string x */ | |
#define switchs(x) \ | |
{ char *ss__sw = (x); bool ss__done = false; bool ss__cont = false; \ | |
regex_t ss__regex; regcomp(&ss__regex, ".*", 0); do { | |
/** Check if the string matches the cases argument (case sensitive) */ | |
#define cases(x) } if ( ss__cont || !strcmp ( ss__sw, x ) ) \ | |
{ ss__done = true; ss__cont = true; | |
/** Check if the string matches the icases argument (case insensitive) */ | |
#define icases(x) } if ( ss__cont || !strcasecmp ( ss__sw, x ) ) { \ | |
ss__done = true; ss__cont = true; | |
/** Check if the string matches the specified regular expression using regcomp(3) */ | |
#define cases_re(x,flags) } regfree ( &ss__regex ); if ( ss__cont || ( \ | |
0 == regcomp ( &ss__regex, x, flags ) && \ | |
0 == regexec ( &ss__regex, ss__sw, 0, NULL, 0 ) ) ) { \ | |
ss__done = true; ss__cont = true; | |
/** Default behaviour */ | |
#define defaults } if ( !ss__done || ss__cont ) { | |
/** Close the switchs */ | |
#define switchs_end } while ( 0 ); regfree(&ss__regex); } | |
#endif // __SWITCHS_H__ |
This file contains 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
#include <stdio.h> | |
#include "switchs.h" | |
int main(int argc, char **argv) { | |
switchs(argv[1]) { | |
cases("foo") | |
cases("bar") | |
printf("foo or bar (case sensitive)\n"); | |
break; | |
icases("pi") | |
printf("pi or Pi or pI or PI (case insensitive)\n"); | |
break; | |
cases_re("^D.*",0) | |
printf("Something that start with D (case sensitive)\n"); | |
break; | |
cases_re("^E.*",REG_ICASE) | |
printf("Something that start with E (case insensitive)\n"); | |
break; | |
cases("1") | |
printf("1\n"); | |
cases("2") | |
printf("2\n"); | |
break; | |
defaults | |
printf("No match\n"); | |
break; | |
} switchs_end; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
LOVE this. just comment out the regex line for embedded systems without
glibc
, etc!