imap-send.c: simplify logic in lf_to_crlf()

* The first character in the string used to be special-cased to get around the fact that msg->buf[i - 1] is not defined for i == 0. Instead, keep track of the previous character in a separate variable, "lastc", initialized in such a way to let the loop handle i == 0 correctly. * Make the two loops over the string look as similar as possible to make it more obvious that the count computed in the first pass agrees with the true length of the new string written in the second pass. As a side effect, this makes it possible to use the "j" counter in place of lfnum and new_len. Signed-off-by: Michael Haggerty <mhagger@alum.mit.edu> Reviewed-by: Jonathan Nieder <jrnieder@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Michael Haggerty committed Jan 15, 2013 at 09:06 UTC 3691031cb33922ce49448518aa06e33eded3368e
1 file changed +23 -29
imap-send.c
+23 -29
@@ -1091,42 +1091,36 @@ bail:
1091 return NULL;
1092 }
1093
1094 +/*
1095 + * Insert CR characters as necessary in *msg to ensure that every LF
1096 + * character in *msg is preceded by a CR.
1097 + */
1098 static void lf_to_crlf(struct strbuf *msg)
1099 {
1096 - size_t new_len;
1100 char *new;
1098 - int i, j, lfnum = 0;
1099 -
1100 - if (msg->buf[0] == '\n')
1101 - lfnum++;
1102 - for (i = 1; i < msg->len; i++) {
1103 - if (msg->buf[i - 1] != '\r' && msg->buf[i] == '\n')
1104 - lfnum++;
1101 + size_t i, j;
1102 + char lastc;
1103 +
1104 + /* First pass: tally, in j, the size of the new string: */
1105 + for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1106 + if (msg->buf[i] == '\n' && lastc != '\r')
1107 + j++; /* a CR will need to be added here */
1108 + lastc = msg->buf[i];
1109 + j++;
1110 }
1111
1107 - new_len = msg->len + lfnum;
1108 - new = xmalloc(new_len + 1);
1109 - if (msg->buf[0] == '\n') {
1110 - new[0] = '\r';
1111 - new[1] = '\n';
1112 - i = 1;
1113 - j = 2;
1114 - } else {
1115 - new[0] = msg->buf[0];
1116 - i = 1;
1117 - j = 1;
1118 - }
1119 - for ( ; i < msg->len; i++) {
1120 - if (msg->buf[i] != '\n') {
1121 - new[j++] = msg->buf[i];
1122 - continue;
1123 - }
1124 - if (msg->buf[i - 1] != '\r')
1112 + new = xmalloc(j + 1);
1113 +
1114 + /*
1115 + * Second pass: write the new string. Note that this loop is
1116 + * otherwise identical to the first pass.
1117 + */
1118 + for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1119 + if (msg->buf[i] == '\n' && lastc != '\r')
1120 new[j++] = '\r';
1126 - /* otherwise it already had CR before */
1127 - new[j++] = '\n';
1121 + lastc = new[j++] = msg->buf[i];
1122 }
1129 - strbuf_attach(msg, new, new_len, new_len + 1);
1123 + strbuf_attach(msg, new, j, j + 1);
1124 }
1125
1126 /*