Add basic input parsing

master
Nick Krichevsky 2019-09-21 21:30:07 -04:00
parent 0ba6de5532
commit 8ec844245a
2 changed files with 99 additions and 0 deletions

82
main.c Normal file
View File

@ -0,0 +1,82 @@
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "mailbox.h"
#include "main.h"
/**
* Parse a line of input into an input struct.
*
* @param input_line A line of input.
* @param res An already allocated input struct to store the result in.
*
* @return int -1 if the input is malformed, and 0 otherwise.
*/
static int parse_input_line(char *input_line, struct input *res) {
// if tmp has anything in it, then we know that extra values have been entered.
char tmp[2];
int num_matched = sscanf(input_line, " %d %d %1s", &(res->value), &(res->recipient), tmp);
return num_matched == 2 ? 0 : -1;
}
/**
* Convert the given input to an array of input structs.
*
* @param num_threads The number of threads that the program has been spawned with.
* @param res A pointer that will be allocated as an array of inputs. Must be freed by the caller.
*
* @return int the number of input lines that were read.
*/
static int get_input(int num_threads, struct input **res) {
int input_index = 0;
int current_buffer_size = BUFFER_SIZE;
char *input_buffer = malloc(current_buffer_size);
// Keep reaidng until we hit an EOF
while (true) {
char *read_result;
while((read_result = fgets(input_buffer, current_buffer_size, stdin))) {
int read_size = strlen(input_buffer);
if (input_buffer[read_size - 1] == '\n') {
break;
}
// Grow our buffer if we nede to read more input.
current_buffer_size *= 2;
input_buffer = realloc(input_buffer, current_buffer_size);
}
if (read_result == NULL) {
break;
}
struct input current_input;
int parse_result = parse_input_line(input_buffer, &current_input);
if (parse_result == -1) {
// On bad input, we should assume an EOF and stop.
break;
} else if (current_input.recipient >= num_threads || current_input.recipient < 0) {
printf("Invalid recipient id.\n");
continue;
}
*res = realloc(*res, sizeof(struct input));
memcpy(*res + input_index, &current_input, sizeof(struct input));
input_index++;
}
free(input_buffer);
return input_index;
}
int main(int argc, char *argv[]) {
struct input *inputs = NULL;
// TODO: Get input to get actual number of inputs. 5 is just for funzies.
int num_inputs = get_input(5, &inputs);
for (int i = 0; i < num_inputs; i++) {
printf("#%d recipient=%d value=%d\n", i, inputs[i].recipient, inputs[i].value);
}
free(inputs);
}

17
main.h Normal file
View File

@ -0,0 +1,17 @@
#ifndef MAIN_H
#define MAIN_H
// The max number of threads that can be used at once
#define MAXTHREAD 10
// The max size of the input buffer
#define BUFFER_SIZE 128
// input represents a pair of values inputted at the command line
struct input {
// The mailbox index of the recipient.
int recipient;
// The value to send to the mailbox.
int value;
};
#endif