#include "width.h" #include static int horizontal(unsigned char value) { return value == ' ' || value == '\t' || value == '\r'; } int pw_decimal(const char *data, size_t length, int32_t *value) { if (length == 0) { return 1; } size_t cursor = 0; int negative = 0; if (data[cursor] == '+' || data[cursor] == '-') { negative = data[cursor] == '-'; ++cursor; } if (cursor == length) { return 1; } uint32_t magnitude = 0; uint32_t limit = negative ? UINT32_C(2147483648) : INT32_MAX; for (; cursor < length; ++cursor) { unsigned char ch = (unsigned char)data[cursor]; if (ch < '0' || ch > '9') { return 1; } uint32_t digit = ch - '0'; if (magnitude > limit / 10 || (magnitude == limit / 10 && digit > limit % 10)) { return 1; } magnitude = magnitude * 10 + digit; } if (negative && magnitude == UINT32_C(2147483648)) { *value = INT32_MIN; } else if (negative) { *value = -(int32_t)magnitude; } else { *value = (int32_t)magnitude; } return 0; } static int parse_values(const char *data, size_t length, int32_t *values, size_t count) { size_t cursor = 0; for (size_t field = 0; field < count; ++field) { while (cursor < length && horizontal((unsigned char)data[cursor])) { ++cursor; } size_t start = cursor; while (cursor < length && !horizontal((unsigned char)data[cursor])) { ++cursor; } if (pw_decimal(data + start, cursor - start, &values[field]) != 0) { return 1; } } while (cursor < length && horizontal((unsigned char)data[cursor])) { ++cursor; } return cursor == length ? 0 : 1; } int pw_parse_request(const char *data, size_t length, PWRequest *request) { int32_t values[5]; if (parse_values(data, length, values, 5) != 0) { return 1; } request->op = values[0]; request->lane = values[1]; request->a = values[2]; request->b = values[3]; request->c = values[4]; return 0; } int pw_parse_seed(const char *data, size_t length, int32_t *seed) { return parse_values(data, length, seed, 1); }