From f37c3bf013063883c60da0faa828b58876269ec5 Mon Sep 17 00:00:00 2001 From: YuQing <384681@qq.com> Date: Sat, 17 Apr 2021 21:51:27 +0800 Subject: [PATCH] parse_bytes function more graceful --- HISTORY | 3 ++- src/shared_func.c | 51 +++++++++++++++++++++++++++++++++-------------- 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/HISTORY b/HISTORY index ee0c79e..7884bbf 100644 --- a/HISTORY +++ b/HISTORY @@ -1,5 +1,5 @@ -Version 1.49 2021-04-09 +Version 1.49 2021-04-17 * add macros: FC_ABS and FC_NEGATIVE * uniq_skiplist.c: add uniq_skiplist_pair struct and init function * add functions: fc_mkdirs and str_replace @@ -8,6 +8,7 @@ Version 1.49 2021-04-09 * add function: fc_check_filename_ex * add functions: fc_queue_push_queue_to_tail etc. * add file locked_list.h + * parse_bytes function more graceful Version 1.48 2021-02-01 * fast_buffer.[hc]: add function fast_buffer_append_binary diff --git a/src/shared_func.c b/src/shared_func.c index 9bffc1e..c3b2315 100644 --- a/src/shared_func.c +++ b/src/shared_func.c @@ -2172,46 +2172,67 @@ int cmp_by_ip_addr_t(const void *p1, const void *p2) int parse_bytes(const char *pStr, const int default_unit_bytes, int64_t *bytes) { char *pReservedEnd; + int result; pReservedEnd = NULL; *bytes = strtol(pStr, &pReservedEnd, 10); if (*bytes < 0) - { - logError("file: "__FILE__", line: %d, " \ - "bytes: %"PRId64" < 0, input string: %s", - __LINE__, *bytes, pStr); - return EINVAL; - } + { + logError("file: "__FILE__", line: %d, " \ + "bytes: %"PRId64" < 0, input string: %s", + __LINE__, *bytes, pStr); + return EINVAL; + } if (pReservedEnd == NULL || *pReservedEnd == '\0') { *bytes *= default_unit_bytes; + return 0; } - else if (*pReservedEnd == 'T' || *pReservedEnd == 't') + + if (*pReservedEnd == 'T' || *pReservedEnd == 't') { *bytes *= 1024 * 1024 * 1024 * 1024LL; + result = 0; } else if (*pReservedEnd == 'G' || *pReservedEnd == 'g') { *bytes *= 1024 * 1024 * 1024; + result = 0; } else if (*pReservedEnd == 'M' || *pReservedEnd == 'm') { *bytes *= 1024 * 1024; + result = 0; } else if (*pReservedEnd == 'K' || *pReservedEnd == 'k') - { - *bytes *= 1024; - } + { + *bytes *= 1024; + result = 0; + } else { - logError("file: "__FILE__", line: %d, " - "unkown byte unit: %c (0x%02x), input string: %s", - __LINE__, *pReservedEnd, *pReservedEnd, pStr); - return EINVAL; + result = EINVAL; } - return 0; + if (result == 0) + { + if (*(pReservedEnd + 1) == '\0') + { + return 0; + } + if ((*(pReservedEnd + 1) == 'B' || *(pReservedEnd + 1) == 'b') && + (*(pReservedEnd + 2) == '\0')) + { + return 0; + } + result = EINVAL; + } + + logError("file: "__FILE__", line: %d, " + "unkown byte unit: %s, input string: %s", + __LINE__, pReservedEnd, pStr); + return result; } int set_rand_seed()