1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief Miscellaneous utility functions
6 // Author: Lasse Collin
8 // This file has been put into the public domain.
9 // You can do whatever you want with this file.
11 ///////////////////////////////////////////////////////////////////////////////
17 xrealloc(void *ptr, size_t size)
21 ptr = realloc(ptr, size);
23 message_fatal("%s", strerror(errno));
30 xstrdup(const char *src)
33 const size_t size = strlen(src) + 1;
34 char *dest = xmalloc(size);
35 return memcpy(dest, src, size);
40 str_to_uint64(const char *name, const char *value, uint64_t min, uint64_t max)
45 while (*value == ' ' || *value == '\t')
48 if (*value < '0' || *value > '9')
49 message_fatal(_("%s: Value is not a non-negative "
50 "decimal integer"), value);
54 if (result > (UINT64_MAX - 9) / 10)
58 result += *value - '0';
60 } while (*value >= '0' && *value <= '9');
68 { "k", UINT64_C(1000) },
69 { "kB", UINT64_C(1000) },
70 { "M", UINT64_C(1000000) },
71 { "MB", UINT64_C(1000000) },
72 { "G", UINT64_C(1000000000) },
73 { "GB", UINT64_C(1000000000) },
74 { "Ki", UINT64_C(1024) },
75 { "KiB", UINT64_C(1024) },
76 { "Mi", UINT64_C(1048576) },
77 { "MiB", UINT64_C(1048576) },
78 { "Gi", UINT64_C(1073741824) },
79 { "GiB", UINT64_C(1073741824) }
82 uint64_t multiplier = 0;
83 for (size_t i = 0; i < ARRAY_SIZE(suffixes); ++i) {
84 if (strcmp(value, suffixes[i].name) == 0) {
85 multiplier = suffixes[i].multiplier;
90 if (multiplier == 0) {
91 message(V_ERROR, _("%s: Invalid multiplier suffix. "
92 "Valid suffixes:"), value);
93 message_fatal("`k' (10^3), `M' (10^6), `G' (10^9) "
94 "`Ki' (2^10), `Mi' (2^20), "
98 // Don't overflow here either.
99 if (result > UINT64_MAX / multiplier)
102 result *= multiplier;
105 if (result < min || result > max)
111 message_fatal(_("Value of the option `%s' must be in the range "
112 "[%" PRIu64 ", %" PRIu64 "]"),
118 /// \brief Simple quoting to get rid of ASCII control characters
120 /// This is not so cool and locale-dependent, but should be good enough
121 /// At least we don't print any control characters on the terminal.
124 str_quote(const char *str)
127 bool has_ctrl = false;
129 while (str[dest_len] != '\0')
130 if (*(unsigned char *)(str + dest_len++) < 0x20)
133 char *dest = malloc(dest_len + 1);
136 for (size_t i = 0; i < dest_len; ++i)
137 if (*(unsigned char *)(str + i) < 0x20)
142 dest[dest_len] = '\0';
145 // Usually there are no control characters,
146 // so we can optimize.
147 memcpy(dest, str, dest_len + 1);
157 is_empty_filename(const char *filename)
159 if (filename[0] == '\0') {
160 message_error(_("Empty filename, skipping"));
171 const bool ret = isatty(STDIN_FILENO);
174 message_error(_("Compressed data not read from a terminal "
175 "unless `--force' is used."));
184 const bool ret = isatty(STDOUT_FILENO);
187 message_error(_("Compressed data not written to a terminal "
188 "unless `--force' is used."));