independ roll(1)

This commit is contained in:
2022-09-13 00:02:15 -04:00
parent 261f2d46d7
commit 07e7768399
6 changed files with 112 additions and 87 deletions
-75
View File
@@ -1,75 +0,0 @@
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <sysexits.h>
#include <time.h>
#include "libio.h"
static char *program_name = "roll";
int main(int argc, char *argv[]){
char *argv0;
char *argvc;
int r; /* rolls */
int s; /* sides */
argv0 = argv[0];
if(argc < 2){
fprintf(stderr,
"Usage: %s [dice...]\n"
"\tDice should be formatted [rolls]d[sides], e.g. 1d3, 5d6...\n",
argv0 == NULL ? program_name : argv0
);
return EX_USAGE;
}
srand(time(NULL));
while(--argc > 0){
argvc = *++argv;
/* Parse out [rolls]d[sides] */
if(!isdigit(**argv)){
error: fprintf(stderr,
"%s: %s: Improperly formatted die (should be"
" [rolls]d[sides]).\n",
argv0, argvc
);
return EX_USAGE;
}
r = parse_uint(*argv);
while(isdigit(**argv))
++*argv;
if(*((*argv)++) != 'd' || !isdigit(**argv))
goto error;
s = parse_uint(*argv);
while(isdigit(**argv))
++*argv;
if(**argv != '\0')
goto error;
/* On 2022-08-19 I experimented with using fprintf(3) instead
* of libio's fdputd(3) to see if stdio was faster, thinking
* the buffering would make a difference. stdio flushes its
* buffer after every newline so in this particular code it
* cannot improve performance unless fdputd(3)'s implementation
* really sucked - no beans!
* It also is an issue where every benchmark reports 0.00 real
* / user / sys times for execution because this program does
* very little - but if you fire up strace(3) you will find the
* system calls (which are nowadays usually the slowest part of
* a given small UNIX utility) are the same either way.
* I'm keeping this little option here in case someone wants to
* peer review; no harm in it. */
while(--r >= 0)
#ifdef USE_STDIO
fprintf(stdout, "%d\n",
#else
fdputd(1,
#endif
rand() % s + 1);
}
return EX_OK;
}