diff --git a/mx_util.c b/mx_util.c index e79e467..abd53a4 100644 --- a/mx_util.c +++ b/mx_util.c @@ -1171,6 +1171,66 @@ char **mx_strvec_from_str(char *str) return strvec; } +int mx_str_to_cpuset(cpu_set_t* cpuset_ptr,char *str) +{ + char c; + int cpu_low; + int cpu_high; + char *next; + int i; + + CPU_ZERO(cpuset_ptr); + + while (1) { + c=*str; + if (c=='\0') { + break; + } else if (c>='0' && c<='9') { + cpu_low=strtol(str,&next,10); + str=next; + } else { + return -(errno=EINVAL); + } + + if (cpu_low<0 || cpu_low>=CPU_SETSIZE) { + return -(errno=EINVAL); + } + + c=*str; + if (c=='\0') { + CPU_SET(cpu_low,cpuset_ptr); + break; + } else if (c==',') { + CPU_SET(cpu_low,cpuset_ptr); + str++; + } else if (c=='-') { + c=*++str; + if (c>='0' && c<='9') { + cpu_high=strtol(str,&next,10); + str=next; + if (cpu_high<0 || cpu_high>=CPU_SETSIZE || cpu_high=CPU_SETSIZE) break; + if (CPU_ISSET(cpu,cpuset_ptr)) { + cpu_low=cpu++; + while (1) { + if (cpu>=CPU_SETSIZE || !CPU_ISSET(cpu,cpuset_ptr)) break; + cpu++; + } + cpu_high=cpu-1; + if (cpu_low==cpu_high) { + mx_asprintf_forever(&str,"%d",cpu_low); + } else { + mx_asprintf_forever(&str,"%d-%d",cpu_low,cpu_high); + } + res=mx_strvec_push_str(&strvec,str); + if (!res) { + mx_strvec_free(strvec); + return NULL; + } + } else { + cpu++; + } + } + + out=mx_strvec_join(",",strvec); + mx_strvec_free(strvec); + return out; +} diff --git a/mx_util.h b/mx_util.h index 9ab0ee5..aeb2489 100644 --- a/mx_util.h +++ b/mx_util.h @@ -6,6 +6,7 @@ #include #include #include +#include #include "mx_log.h" @@ -192,4 +193,7 @@ char** mx_strvec_from_str(char *str); void mx_strvec_free(char **strvec); char* mx_strvec_join(char *sep,char **strvec); +char* mx_cpuset_to_str(cpu_set_t* cpuset_ptr); +int mx_str_to_cpuset(cpu_set_t* cpuset_ptr,char *str); + #endif diff --git a/test_mx_util.c b/test_mx_util.c index f89135c..b290490 100644 --- a/test_mx_util.c +++ b/test_mx_util.c @@ -392,6 +392,27 @@ static void test_mx_strvec() { mx_strvec_free(strvec); } +static void test_mx_cpuset(void) +{ + cpu_set_t cpuset; + char *str; + + assert(mx_str_to_cpuset(&cpuset,"1,2,3,10,11,12,100-102")==0); + assert((str=mx_cpuset_to_str(&cpuset))); + assert(strcmp(str,"1-3,10-12,100-102")==0); + free(str); + + assert(mx_str_to_cpuset(&cpuset,"")==0); + assert((str=mx_cpuset_to_str(&cpuset))); + assert(strcmp(str,"")==0); + free(str); + + assert(mx_str_to_cpuset(&cpuset,"bla")<0); + assert(mx_str_to_cpuset(&cpuset,"5-4")<0); + assert(mx_str_to_cpuset(&cpuset,"-4")<0); + assert(mx_str_to_cpuset(&cpuset,"4-")<0); +} + int main(int argc, char *argv[]) { test_mx_strskipwhitespaces(); @@ -408,5 +429,6 @@ int main(int argc, char *argv[]) test_mx_read_first_line_from_file(); test_mx_strscan(); test_mx_strvec(); + test_mx_cpuset(); return 0; }