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
/*