units.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include "units.h"
  3. #include <inttypes.h>
  4. #include <limits.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <linux/kernel.h>
  8. #include <linux/time64.h>
  9. unsigned long parse_tag_value(const char *str, struct parse_tag *tags)
  10. {
  11. struct parse_tag *i = tags;
  12. while (i->tag) {
  13. char *s = strchr(str, i->tag);
  14. if (s) {
  15. unsigned long int value;
  16. char *endptr;
  17. value = strtoul(str, &endptr, 10);
  18. if (s != endptr)
  19. break;
  20. if (value > ULONG_MAX / i->mult)
  21. break;
  22. value *= i->mult;
  23. return value;
  24. }
  25. i++;
  26. }
  27. return (unsigned long) -1;
  28. }
  29. unsigned long convert_unit(unsigned long value, char *unit)
  30. {
  31. *unit = ' ';
  32. if (value > 1000) {
  33. value /= 1000;
  34. *unit = 'K';
  35. }
  36. if (value > 1000) {
  37. value /= 1000;
  38. *unit = 'M';
  39. }
  40. if (value > 1000) {
  41. value /= 1000;
  42. *unit = 'G';
  43. }
  44. return value;
  45. }
  46. int unit_number__scnprintf(char *buf, size_t size, u64 n)
  47. {
  48. char unit[4] = "BKMG";
  49. int i = 0;
  50. while (((n / 1024) > 1) && (i < 3)) {
  51. n /= 1024;
  52. i++;
  53. }
  54. return scnprintf(buf, size, "%" PRIu64 "%c", n, unit[i]);
  55. }