2 * Helpers for formatting and printing strings
4 * Copyright 31 August 2008 James Bottomley
5 * Copyright (C) 2013, Intel Corporation
7 #include <linux/kernel.h>
8 #include <linux/math64.h>
9 #include <linux/export.h>
10 #include <linux/ctype.h>
11 #include <linux/string_helpers.h>
14 * string_get_size - get the size in the specified units
15 * @size: The size to be converted
16 * @units: units to use (powers of 1000 or 1024)
17 * @buf: buffer to format to
18 * @len: length of buffer
20 * This function returns a string formatted to 3 significant figures
21 * giving the size in the required units. Returns 0 on success or
22 * error on failure. @buf is always zero terminated.
25 int string_get_size(u64 size, const enum string_size_units units,
28 static const char *units_10[] = { "B", "kB", "MB", "GB", "TB", "PB",
29 "EB", "ZB", "YB", NULL};
30 static const char *units_2[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB",
31 "EiB", "ZiB", "YiB", NULL };
32 static const char **units_str[] = {
33 [STRING_UNITS_10] = units_10,
34 [STRING_UNITS_2] = units_2,
36 static const unsigned int divisor[] = {
37 [STRING_UNITS_10] = 1000,
38 [STRING_UNITS_2] = 1024,
41 u64 remainder = 0, sf_cap;
46 if (size >= divisor[units]) {
47 while (size >= divisor[units] && units_str[units][i]) {
48 remainder = do_div(size, divisor[units]);
53 for (j = 0; sf_cap*10 < 1000; j++)
58 do_div(remainder, divisor[units]);
59 snprintf(tmp, sizeof(tmp), ".%03lld",
60 (unsigned long long)remainder);
65 snprintf(buf, len, "%lld%s %s", (unsigned long long)size,
66 tmp, units_str[units][i]);
70 EXPORT_SYMBOL(string_get_size);
72 static bool unescape_space(char **src, char **dst)
74 char *p = *dst, *q = *src;
100 static bool unescape_octal(char **src, char **dst)
102 char *p = *dst, *q = *src;
105 if (isodigit(*q) == 0)
109 while (num < 32 && isodigit(*q) && (q - *src < 3)) {
119 static bool unescape_hex(char **src, char **dst)
121 char *p = *dst, *q = *src;
128 num = digit = hex_to_bin(*q++);
132 digit = hex_to_bin(*q);
135 num = (num << 4) | digit;
143 static bool unescape_special(char **src, char **dst)
145 char *p = *dst, *q = *src;
168 int string_unescape(char *src, char *dst, size_t size, unsigned int flags)
172 while (*src && --size) {
173 if (src[0] == '\\' && src[1] != '\0' && size > 1) {
177 if (flags & UNESCAPE_SPACE &&
178 unescape_space(&src, &out))
181 if (flags & UNESCAPE_OCTAL &&
182 unescape_octal(&src, &out))
185 if (flags & UNESCAPE_HEX &&
186 unescape_hex(&src, &out))
189 if (flags & UNESCAPE_SPECIAL &&
190 unescape_special(&src, &out))
201 EXPORT_SYMBOL(string_unescape);