MINOR: cpu-set: add a new function to print cpu-sets in human-friendly mode

The new function "print_cpu_set()" will print cpu sets in a human-friendly
way, with commas and dashes for intervals. The goal is to keep them compact
enough.
This commit is contained in:
Willy Tarreau 2025-03-31 14:35:09 +02:00
parent 3955f151b1
commit 571573874a
2 changed files with 62 additions and 0 deletions

View File

@ -60,6 +60,14 @@ int ha_cpuset_size(void);
*/
int parse_cpu_set(const char **args, struct hap_cpuset *cpu_set, char **err);
/* Print a cpu-set as compactly as possible and returns the output length.
* Returns >size if it cannot emit anything due to length constraints, in which
* case it will match what is at least needed to go further, and may return 0
* for an empty set. It will emit series of comma-delimited ranges in the form
* "beg[-end]".
*/
int print_cpu_set(char *output, size_t size, const struct hap_cpuset *cpu_set);
/* Parse a linux cpu map string representing to a numeric cpu mask map
* The cpu map string is a list of 4-byte hex strings separated by commas, with
* most-significant byte first, one bit per cpu number.

View File

@ -213,6 +213,60 @@ int parse_cpu_set(const char **args, struct hap_cpuset *cpu_set, char **err)
return 0;
}
/* Print a cpu-set as compactly as possible and returns the output length.
* Returns >size if it cannot emit anything due to length constraints, in which
* case it will match what is at least needed to go further, and may return 0
* for an empty set. It will emit series of comma-delimited ranges in the form
* "beg[-end]".
*/
int print_cpu_set(char *output, size_t size, const struct hap_cpuset *cpu_set)
{
struct hap_cpuset set = *cpu_set;
int cpus = ha_cpuset_size();
int first = -1;
int len = 0;
int cpu;
for (cpu = 0; cpu < cpus; cpu++) {
if (!ha_cpuset_isset(&set, cpu))
continue;
ha_cpuset_clr(&set, cpu);
/* check if first of a series*/
if (first < 0) {
first = cpu;
len += snprintf(output + len, size - len, "%d", cpu);
if (len >= size)
return len + 1;
/* check if belongs to a range */
if (cpu < cpus - 1 && ha_cpuset_isset(&set, cpu + 1)) {
if (len + 1 >= size)
return len + 2;
output[len++] = '-';
output[len] = 0;
} else
first = -1;
}
else if (cpu >= cpus - 1 || !ha_cpuset_isset(&set, cpu + 1)) {
/* end of a series and not first */
len += snprintf(output + len, size - len, "%d", cpu);
if (len >= size)
return len + 1;
first = -1;
}
if (first < 0 && ha_cpuset_count(&set) > 0) {
if (len + 1 >= size)
return len + 2;
output[len++] = ',';
output[len] = 0;
}
}
return len;
}
/* Parse a linux cpu map string representing to a numeric cpu mask map
* The cpu map string is a list of 4-byte hex strings separated by commas, with
* most-significant byte first, one bit per cpu number.