Untitled

mail@pastecode.io avatar
unknown
c_cpp
3 years ago
3.0 kB
3
Indexable
Never
/***
 Parses a name to get rid of all leading, trailing, and in between white space and inputs it into output_str
 ex:
     Flash      Light      -> Flash Light
 */
static void parse_name(char *string, char *output_str){
  if (!(string && output_str))
    return;

  char *token = strtok(string, " ");
  if (!token)
      return;
  

  strcpy(output_str, strip_whitespace(token));
  token = strtok(NULL, " ");
  if (!token)
    return;

  size_t len = strlen(output_str);
  //add space in between
  output_str[len] = ' ';
  ++len;

  strcpy(output_str + len, strip_whitespace(token));

  //convert name to uppercase
  for (char *p = output_str; *p; ++p){
    *p = toupper(*p);
  }

}

//returns 1 if invalid else 0
int invalid_id(const char *id){
  if (strlen(id) != 4)
    return 1;

  for (const char *p = id; *p; ++p){
    if (!isdigit(*p))
      return 1;
  }
  return 0;
}

//returns 1 if invalid else 0
int invalid_name(const char *name){
  if (strlen(name) > 20)
    return 1;

  for (const char *p = name; *p; ++p){
    if (!(isalpha(*p) || *p == ' ' || *p == '(' || *p == ')'))
      return 1;
  } 
  return 0;
}


int invalid_qty(const char *qty){

   for (const char *p = qty; *p; ++p){
    if (!(isdigit(*p) || *p == '\n'))
      return 1;
  }
  return 0;
}


int parse_input(char *buffer, HARDWARE *input){

  const char *const delim = ",:";

  //id
  char *token = strtok(buffer, delim);
  if (!token){
    puts("line 248");
    return 1;
    }

  char temp_id[HRDWARE_ID_LEN + 1];
  strcpy(temp_id, strip_whitespace(token));
  if (invalid_id(temp_id)){
    puts("line 253");
    return 1;
    }

  strncpy(input->id, temp_id, HRDWARE_ID_LEN + 1);
  input->id[HRDWARE_ID_LEN + 1] = '\0';

  //name
  char *name_token = strtok(NULL, delim);
  if (!name_token){
    puts("line 262");
    return 1;
    }

  //qty
  token = strtok(NULL, delim);
  if (!token){
    puts("line 268");
    return 1;
    }

  char *qty = strdup(token);
  //need to store original to free it because strip whitespace reassigns it
  char *original_qty = qty;
  qty = strip_whitespace(qty);
  if (invalid_qty(qty)){
    puts("line 302");
    free(original_qty);
    original_qty = NULL;
    return 1;
  }


  if (sscanf(qty, "%d", &input->qty) < 1){
    puts("line 272");
    free(original_qty);
    original_qty = NULL;
    return 1;
  }
  free(original_qty);
  original_qty = NULL;

  char temp_name[MAX_HRDWARE_NAME_LEN + 1];
  //to not alter original string
  name_token = strdup(name_token);
  //we have to parse it later as to not interfere with main strtok as it stores static variable
  parse_name(name_token, temp_name);
  //strdup dynamically allocates and hence needs to be freed
  free(name_token);
  if (invalid_name(temp_name)){
    puts("line 284");
    return 1;
    }
  
  strcpy(input->name, temp_name);

  return 0;
}