text
stringlengths
0
357
* This function will not convert anything else in the future, so it can be used
* safely for marking thinks to remove by `\r` and call this function afterwards.
*
* @param buf The buffer to convert.
* @return None.
*/
void dc_remove_cr_chars(char* buf)
{
const char* p1 = buf; /* search for first `\r` */
while (*p1) {
if (*p1=='\r') {
break;
}
p1++;
}
char* p2 = (char*)p1; /* p1 is `\r` or null-byte; start removing `\r` */
while (*p1) {
if (*p1!='\r') {
*p2 = *p1;
p2++;
}
p1++;
}
/* add trailing null-byte */
*p2 = 0;
}
/**
* Unify the lineends in the given null-terminated buffer to a simple `\n` (LF, ^J).
* Carriage return characters (`\r`, CR, ^M) are removed.
*
* This function does _not_ convert only-CR linefeeds; AFAIK, they only came from
* Mac OS 9 and before and should not be in use for nearly 20 year, so maybe this
* is no issue. However, this could be easily added to the function as needed
* by converting all `\r` to `\n` if there is no single `\n` in the original buffer.
*
* @param buf The buffer to convert.
* @return None.
*/
void dc_unify_lineends(char* buf)
{
// this function may be extended to do more linefeed unification, do not mess up
// with dc_remove_cr_chars() which does only exactly removing CR.
dc_remove_cr_chars(buf);
}
void dc_replace_bad_utf8_chars(char* buf)
{
if (buf==NULL) {
return;
}
unsigned char* p1 = (unsigned char*)buf; /* force unsigned - otherwise the `> ' '` comparison will fail */
int p1len = strlen(buf);
int c = 0;
int i = 0;
int ix = 0;
int n = 0;
int j = 0;
for (i=0, ix=p1len; i < ix; i++)
{
c = p1[i];
if (c > 0 && c <= 0x7f) { n=0; } /* 0bbbbbbb */
else if ((c & 0xE0) == 0xC0) { n=1; } /* 110bbbbb */
else if (c==0xed && i<(ix-1) && (p1[i+1] & 0xa0)==0xa0) { goto error; } /* U+d800 to U+dfff */
else if ((c & 0xF0) == 0xE0) { n=2; } /* 1110bbbb */
else if ((c & 0xF8) == 0xF0) { n=3; } /* 11110bbb */
//else if ((c & 0xFC) == 0xF8) { n=4; } /* 111110bb - not valid in https://tools.ietf.org/html/rfc3629 */
//else if ((c & 0xFE) == 0xFC) { n=5; } /* 1111110b - not valid in https://tools.ietf.org/html/rfc3629 */
else { goto error; }
for (j = 0; j < n && i < ix; j++) { /* n bytes matching 10bbbbbb follow ? */
if ((++i == ix) || (( p1[i] & 0xC0) != 0x80)) {
goto error;
}
}
}
/* everything is fine */
return;
error:
/* there are errors in the string -> replace potential errors by the character `_`
(to avoid problems in filenames, we do not use eg. `?`) */
while (*p1) {
if (*p1 > 0x7f) {
*p1 = '_';
}
p1++;
}
}
size_t dc_utf8_strlen(const char* s)
{