refactor code

This commit is contained in:
2022-11-20 20:23:39 -05:00
parent a2ae9d1ae8
commit 19f091eead
4 changed files with 103 additions and 74 deletions
+10 -53
View File
@@ -1,12 +1,14 @@
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#ifndef DONT_USE_SYSTEM_SYSEXITS
# include <sysexits.h>
#else
# include "../include/sysexits.h"
# include "../sysexits/sysexits.h"
#endif /* ifndef DONT_USE_SYSTEM_SYSEXITS */
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include "psargs.h"
static char *program_name = "pscat";
@@ -16,56 +18,21 @@ static char *program_name = "pscat";
# define L_PAREN '['
# define R_PAREN ']'
#else
# include "../include/ascii.h"
# include "../ascii/ascii.h"
# define L_PAREN ASCII_LEFT_SQUARE_BRACKET
# define R_PAREN ASCII_RIGHT_SQUARE_BRACKET
#endif /* ifndef USE_ASCII_H */
/* Test string containing { c, '\0' } without iteration.
* Theoretically saves a little bit of time compared to strcmp(3). */
#define SCMPFLAT(a, b) (*(a) != '\0' && *((a)+1) == '\0' && *(a) == (b))
/* Verifies arguments to pscat are sensible. */
static int
check_arg(char **argv){
enum {
UNINITIALIZED = 0,
NORMAL = 1,
INLPAREN = 2
} s;
int terms;
for(s = UNINITIALIZED, terms = 0; *argv != NULL; ++argv)
switch(s){
case UNINITIALIZED: case NORMAL:
if(SCMPFLAT(*argv, L_PAREN))
s = INLPAREN;
else
return 0; /* syntax error */
break;
default: /* >= INLPAREN */
if(argv[0][1] == '\0'){
s -= (argv[0][0] == R_PAREN);
terms += (argv[0][0] == R_PAREN && s == NORMAL);
s += (argv[0][0] == L_PAREN);
}
break;
}
return terms;
}
int main(int argc, char *argv[]){
char **psstart;
int child;
int i;
int p;
int retval;
int terms;
retval = 0;
if((terms = check_arg(++argv)) == 0){
if((terms = check_arg(++argv, L_PAREN, R_PAREN)) == 0){
fprintf(stderr,
"Usage: %s \"[\" [utility [argument...]] \"]\" ...\n",
argv[0] == NULL ? program_name : argv[0]
@@ -75,18 +42,8 @@ int main(int argc, char *argv[]){
/* loop starts with *argv -> the next L_PAREN */
for(i = 0; i < terms; ++i){
psstart = ++argv;
p = 1;
while(p > 0){
++argv;
/* branching here potentially saves a comparison.
* this seems like the most optimal way to do this,
* maybe it isn't, i don't care too much */
if(SCMPFLAT(*argv, L_PAREN))
++p;
else if(SCMPFLAT(*argv, R_PAREN))
--p;
}
psstart = argv + 1;
argv = corresponding_arg(argv, L_PAREN, R_PAREN);
/* *argv -> the corresponding R_PAREN. turn it into NULL to
* terminate the argument list to send to execvp(3) */
*argv = NULL;