/* Convert a string representing an amount of memory into the number of * bytes, so for instance memtoll("1Gb") will return 1073741824 that is * (1024*1024*1024). * * On parsing error, if *err is not NULL, it's set to 1, otherwise it's * set to 0. On error the function return value is 0, regardless of the * fact 'err' is NULL or not. */ long long memtoll(const char *p, int *err) { const char *u; char buf[128]; long mul; /* unit multiplier */ long long val; unsigned int digits; if (err) *err = 0; /* Search the first non digit character. */ u = p; if (*u == '-') u++; while(*u && isdigit(*u)) u++; if (*u == '\0' || !strcasecmp(u,"b")) { // 调用strcasecmp不区分大小比较 mul = 1; } else if (!strcasecmp(u,"k")) { mul = 1000; // 不带尾巴B或b的 } else if (!strcasecmp(u,"kb")) { mul = 1024; // 带尾巴B或b的 } else if (!strcasecmp(u,"m")) { mul = 1000*1000; // 不带尾巴B或b的 } else if (!strcasecmp(u,"mb")) { mul = 1024*1024; // 带尾巴B或b的 } else if (!strcasecmp(u,"g")) { mul = 1000L*1000*1000; // 不带尾巴B或b的 } else if (!strcasecmp(u,"gb")) { mul = 1024L*1024*1024; // 带尾巴B或b的 } else { if (err) *err = 1; return 0; } /* Copy the digits into a buffer, we'll use strtoll() to convert * the digit (without the unit) into a number. */ digits = u-p; if (digits >= sizeof(buf)) { if (err) *err = 1; return 0; } memcpy(buf,p,digits); buf[digits] = '\0'; char *endptr; errno = 0; val = strtoll(buf,&endptr,10); if ((val == 0 && errno == EINVAL) || *endptr != '\0') { if (err) *err = 1; return 0; } return val*mul; } // 有关REdis内存策略的实现,请参见REdis源码文件evict.c。
|