Skip to content

Commit 3691031

Browse files
mhaggergitster
authored andcommitted
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 <[email protected]> Reviewed-by: Jonathan Nieder <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 636fd66 commit 3691031

File tree

1 file changed

+23
-29
lines changed

1 file changed

+23
-29
lines changed

imap-send.c

Lines changed: 23 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1091,42 +1091,36 @@ static struct imap_store *imap_open_store(struct imap_server_conf *srvc)
10911091
return NULL;
10921092
}
10931093

1094+
/*
1095+
* Insert CR characters as necessary in *msg to ensure that every LF
1096+
* character in *msg is preceded by a CR.
1097+
*/
10941098
static void lf_to_crlf(struct strbuf *msg)
10951099
{
1096-
size_t new_len;
10971100
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++;
11051110
}
11061111

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')
11251120
new[j++] = '\r';
1126-
/* otherwise it already had CR before */
1127-
new[j++] = '\n';
1121+
lastc = new[j++] = msg->buf[i];
11281122
}
1129-
strbuf_attach(msg, new, new_len, new_len + 1);
1123+
strbuf_attach(msg, new, j, j + 1);
11301124
}
11311125

11321126
/*

0 commit comments

Comments
 (0)