radare2/libr/util/name.c

99 lines
2.0 KiB
C
Raw Normal View History

2018-04-11 08:25:22 +00:00
/* radare - LGPL - Copyright 2009-2018 - pancake */
#include <r_util.h>
R_API int r_name_validate_char(const char ch) {
2018-04-11 08:25:22 +00:00
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (IS_DIGIT(ch))) {
2016-07-12 20:15:19 +00:00
return true;
2018-04-11 08:25:22 +00:00
}
switch (ch) {
2015-01-02 01:10:20 +00:00
case ':':
case '.':
case '_':
2016-07-12 20:15:19 +00:00
return true;
}
2016-07-12 20:15:19 +00:00
return false;
}
R_API int r_name_check(const char *name) {
/* Cannot start by number */
2018-04-11 08:25:22 +00:00
if (!name || !*name || IS_DIGIT (*name)) {
2016-07-12 20:15:19 +00:00
return false;
2018-04-11 08:25:22 +00:00
}
/* Cannot contain non-alphanumeric chars + [:._] */
2018-04-11 08:25:22 +00:00
for (; *name != '\0'; name++) {
if (!r_name_validate_char (*name)) {
2016-07-12 20:15:19 +00:00
return false;
2018-04-11 08:25:22 +00:00
}
}
2016-07-12 20:15:19 +00:00
return true;
}
static inline bool is_special_char (char *name) {
const char n = *name;
return (n == 'b' || n == 'f' || n == 'n' || n == 'r' || n == 't' || n == 'v' || n == 'a');
}
R_API int r_name_filter(char *name, int maxlen) {
2017-12-20 10:29:51 +00:00
int i;
size_t len;
char *oname;
2018-04-11 08:25:22 +00:00
if (!name) {
return 0;
}
2015-12-08 12:24:21 +00:00
if (maxlen < 0) {
maxlen = strlen (name);
}
name = oname = r_str_trim_head_tail (name);
2015-12-08 12:24:21 +00:00
for (i = 0; *name; name++, i++) {
if (maxlen && i > maxlen) {
*name = '\0';
break;
}
if (!r_name_validate_char (*name) && *name != '\\') {
*name = '_';
2015-12-08 12:24:21 +00:00
// r_str_ccpy (name, name+1, 0);
//name--;
}
}
while (i > 0) {
if (*(name - 1) == '\\' && is_special_char (name)) {
*name = '_';
*(name - 1) = '_';
}
if (*name == '\\') {
*name = '_';
}
name--;
i--;
}
if (*name == '\\') {
*name = '_';
}
// trimming trailing and leading underscores
len = strlen (name);
2017-12-20 10:29:51 +00:00
for (; len > 0 && *(name + len - 1) == '_'; len--);
2017-12-19 14:18:00 +00:00
if (!len) { // name consists only of underscores
return r_name_check (oname);
}
for (i = 0; *(name + i) == '_'; i++, len--);
memmove (name, name + i, len);
*(name + len) = '\0';
return r_name_check (oname);
}
R_API char *r_name_filter2(const char *name) {
int i;
char *res;
2018-04-11 08:25:22 +00:00
while (!IS_PRINTABLE (*name)) {
name++;
2018-04-11 08:25:22 +00:00
}
res = strdup (name);
2015-12-08 12:24:21 +00:00
for (i = 0; res[i]; i++) {
if (!r_name_validate_char (res[i])) {
res[i] = '_';
}
}
return res;
}