Skip to content

Commit

Permalink
Add strset_truncated which sets as much of the string as possible
Browse files Browse the repository at this point in the history
  • Loading branch information
Meiguro committed Feb 27, 2016
1 parent dc4849f commit 2ad75b8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/simply/simply_ui.c
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ void simply_ui_set_style(SimplyUi *self, int style_index) {
void simply_ui_set_text(SimplyUi *self, SimplyUiTextfieldId textfield_id, const char *str) {
SimplyUiTextfield *textfield = &self->ui_layer.textfields[textfield_id];
char **str_field = &textfield->text;
strset(str_field, str);
strset_truncated(str_field, str);
mark_dirty(self);
}

Expand Down
24 changes: 18 additions & 6 deletions src/util/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,41 @@ static inline bool is_string(const char *str) {
return str && str[0];
}

static inline char *strdup2(const char *str) {
static inline char *strndup2(const char *str, size_t n) {
if (!str) {
return NULL;
}

size_t n = strlen(str);
char *buffer = malloc(n + 1);
if (!buffer) {
return NULL;
}

strncpy(buffer, str, n + 1);
buffer[n] = '\0';
return buffer;
}

static inline void strset(char **str_field, const char *str) {
static inline char *strdup2(const char *str) {
return strndup2(str, strlen(str));
}

static inline bool strnset(char **str_field, const char *str, size_t n) {
free(*str_field);
*str_field = NULL;

if (!is_string(str)) {
*str_field = NULL;
return;
return true;
}

*str_field = strdup2(str);
return (*str_field = strndup2(str, n));
}

static inline bool strset(char **str_field, const char *str) {
return strnset(str_field, str, strlen(str));
}

static inline void strset_truncated(char **str_field, const char *str) {
size_t n = strlen(str);
for (; !strnset(str_field, str, n) && n > 1; n /= 2) {}
}

0 comments on commit 2ad75b8

Please sign in to comment.