Skip to content

Commit

Permalink
imap-send.c: simplify logic in lf_to_crlf()
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
Michael Haggerty authored and Junio C Hamano committed Jan 15, 2013
1 parent 636fd66 commit 3691031
Showing 1 changed file with 23 additions and 29 deletions.
52 changes: 23 additions & 29 deletions imap-send.c
Original file line number Diff line number Diff line change
Expand Up @@ -1091,42 +1091,36 @@ static struct imap_store *imap_open_store(struct imap_server_conf *srvc)
return NULL;
}

/*
* Insert CR characters as necessary in *msg to ensure that every LF
* character in *msg is preceded by a CR.
*/
static void lf_to_crlf(struct strbuf *msg)
{
size_t new_len;
char *new;
int i, j, lfnum = 0;

if (msg->buf[0] == '\n')
lfnum++;
for (i = 1; i < msg->len; i++) {
if (msg->buf[i - 1] != '\r' && msg->buf[i] == '\n')
lfnum++;
size_t i, j;
char lastc;

/* First pass: tally, in j, the size of the new string: */
for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
if (msg->buf[i] == '\n' && lastc != '\r')
j++; /* a CR will need to be added here */
lastc = msg->buf[i];
j++;
}

new_len = msg->len + lfnum;
new = xmalloc(new_len + 1);
if (msg->buf[0] == '\n') {
new[0] = '\r';
new[1] = '\n';
i = 1;
j = 2;
} else {
new[0] = msg->buf[0];
i = 1;
j = 1;
}
for ( ; i < msg->len; i++) {
if (msg->buf[i] != '\n') {
new[j++] = msg->buf[i];
continue;
}
if (msg->buf[i - 1] != '\r')
new = xmalloc(j + 1);

/*
* Second pass: write the new string. Note that this loop is
* otherwise identical to the first pass.
*/
for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
if (msg->buf[i] == '\n' && lastc != '\r')
new[j++] = '\r';
/* otherwise it already had CR before */
new[j++] = '\n';
lastc = new[j++] = msg->buf[i];
}
strbuf_attach(msg, new, new_len, new_len + 1);
strbuf_attach(msg, new, j, j + 1);
}

/*
Expand Down

0 comments on commit 3691031

Please sign in to comment.