Skip to content

Commit 50e7757

Browse files
committed
Lib(fix): rewrite string transcoding function
- For to_codeset, we only need UTF-8 is need, because GTK only supports UTF-8 - Deal with invalid UTF-8 sequence - Prevent uncessary convertion when from_codeset is UTF-8 as well
1 parent 7aaddd1 commit 50e7757

File tree

3 files changed

+17
-11
lines changed

3 files changed

+17
-11
lines changed

src/inc/srain.h

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,6 @@ typedef gboolean bool;
3333
#define SRN_TRUE TRUE
3434
#define SRN_FALSE FALSE
3535

36-
/* All strings in Srain should be utf-8 sequence */
37-
#define SRN_ENCODING "utf-8"
38-
#define SRN_FALLBACK_CHAR "�"
36+
#define SRN_CODESET "UTF-8"
3937

4038
#endif /* __SRAIN_H */

src/inc/utils.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,6 @@ time_t get_current_time_s(void);
2727
void time_to_str(time_t time, char *timestr, size_t size, const char *fmt);
2828
void str_assign(char **left, const char *right);
2929
bool str_is_empty(const char *str);
30-
void str_transcoding(char **str, const char *to, const char *from, const char *fallback);
30+
void str_transcoding(char **str, const char *from_codeset);
3131

3232
#endif /* __UTILS_H */

src/lib/utils.c

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -86,19 +86,27 @@ bool str_is_empty(const char *str){
8686
return TRUE;
8787
}
8888

89-
void str_transcoding(char **str, const char *to, const char *from, const char *fallback){
90-
char *tmp;
91-
GError *err;
92-
89+
void str_transcoding(char **str, const char *from_codeset){
9390
if (!*str) return;
9491

95-
err = NULL;
96-
tmp = g_convert_with_fallback(*str, -1, to, from, fallback, NULL, NULL, &err);
92+
if (g_ascii_strcasecmp(from_codeset, SRN_CODESET) == 0) {
93+
// UTF-8 to UTF-8, just make sure it is valid
94+
if (g_utf8_validate(*str, -1, NULL)) {
95+
return;
96+
}
97+
// If invalid, make it valid
98+
str_assign(str, g_utf8_make_valid(*str, -1));
99+
return;
100+
}
101+
102+
// To other codeset
103+
GError *err = NULL;
104+
char *tmp = g_convert_with_fallback(*str, -1, SRN_CODESET, from_codeset, "�", NULL, NULL, &err);
97105
if (tmp){
98106
str_assign(str, tmp);
99107
}
100108
if (err) {
101-
WARN_FR("Failed to convert line from %s to %s: %s", from, to, err->message);
109+
WARN_FR("Failed to convert line from %s to %s: %s", from_codeset, SRN_CODESET, err->message);
102110
g_error_free(err);
103111
}
104112
}

0 commit comments

Comments
 (0)