mailinfo.c currently has a convert_to_utf8 function that overrides its
argument and prints an error message when the decoding fails. Refactor
it, creating another function that does not override anything and does
not print an error message when the decoding fails. This is to be used
by a subsequent patch.

Signed-off-by: Jonathan Tan <jonathanta...@google.com>
---
 mailinfo.c | 42 +++++++++++++++++++++++++++++++++---------
 1 file changed, 33 insertions(+), 9 deletions(-)

diff --git a/mailinfo.c b/mailinfo.c
index 0c4738a..aadad09 100644
--- a/mailinfo.c
+++ b/mailinfo.c
@@ -340,23 +340,47 @@ static struct strbuf *decode_b_segment(const struct 
strbuf *b_seg)
        return out;
 }
 
+/*
+ * Attempts to convert line into UTF-8.
+ *
+ * This differs from convert_to_utf8 in that no inputs are overridden, and that
+ * conversion non-success is not considered an error case - mi->input_error is
+ * not set, and no error message is printed.
+ *
+ * If the conversion is unnecessary, returns 1 and stores NULL in result.
+ *
+ * If the conversion is successful, returns 1 and stores the converted string
+ * in result.
+ *
+ * If the conversion is unsuccessful, returns 0 and stores NULL in result.
+ */
+static int try_convert_to_utf8(const struct mailinfo *mi, const char *line,
+                              const char *charset, char **result)
+{
+       if (!mi->metainfo_charset || !charset || !*charset ||
+           same_encoding(mi->metainfo_charset, charset)) {
+               *result = NULL;
+               return 1;
+       }
+
+       *result = reencode_string(line, mi->metainfo_charset, charset);
+       return !!*result;
+}
+
+/*
+ * Converts line into UTF-8, setting mi->input_error to -1 upon failure.
+ */
 static int convert_to_utf8(struct mailinfo *mi,
                           struct strbuf *line, const char *charset)
 {
        char *out;
-
-       if (!mi->metainfo_charset || !charset || !*charset)
-               return 0;
-
-       if (same_encoding(mi->metainfo_charset, charset))
-               return 0;
-       out = reencode_string(line->buf, mi->metainfo_charset, charset);
-       if (!out) {
+       if (!try_convert_to_utf8(mi, line->buf, charset, &out)) {
                mi->input_error = -1;
                return error("cannot convert from %s to %s",
                             charset, mi->metainfo_charset);
        }
-       strbuf_attach(line, out, strlen(out), strlen(out));
+       if (out)
+               strbuf_attach(line, out, strlen(out), strlen(out));
        return 0;
 }
 
-- 
2.10.0.rc2.20.g5b18e70

Reply via email to