formats/csv/m_csv.c
/* Helper function for M_csv_output_headers_buf() and M_csv_output_rows_buf().
 *
 * Adds required quotes, escapes and trailing delimiter to the given cell value, then writes it to output buffer.
 *
 * If cell value is empty, still adds the trailing delimiter.
 */


If cell value is empty, still adds the trailing delimiter.
If cell value is empty still adds the trailing delimiter .
static void add_cell(M_buf_t *buf, char delim, char quote, const char *cell)
{
	if (!M_str_isempty(cell)) {
		char        chars_to_quote[5] = {'\0', '\0', '\n', '\r', '\0'};
		M_bool      needs_quotes      = M_FALSE;
		const char *next_quote;
		size_t      len               = M_str_len(cell);
		size_t      chars_to_add;
		chars_to_quote[0] = delim;
		chars_to_quote[1] = quote;
		if (M_chr_isspace(*cell) || M_chr_isspace(cell[len - 1])
			|| M_str_find_first_from_charset(cell, chars_to_quote) != NULL) {
			needs_quotes = M_TRUE;
			M_buf_add_char(buf, quote);
		}
		do {
			next_quote   = M_mem_chr(cell, (M_uint8)quote, len);
			chars_to_add = (next_quote == NULL)? len : (size_t)(next_quote - cell) + 1;
			M_buf_add_bytes(buf, cell, chars_to_add);
			len  -= chars_to_add;
			cell += chars_to_add;
			if (next_quote != NULL) {
				M_buf_add_char(buf, quote);
			}
		} while (len > 0);
		if (needs_quotes) {
			M_buf_add_char(buf, quote);
		}
	}
	M_buf_add_char(buf, delim);
}
static void add_cell ( M_buf_t * buf , char delim , char quote , const char * cell ) { if ( ! M_str_isempty ( cell ) ) { char chars_to_quote [ 5 ] = { ' \0 ' , ' \0 ' , ' \n ' , ' \r ' , ' \0 ' } ; M_bool needs_quotes = M_FALSE ; const char * next_quote ; size_t len = M_str_len ( cell ) ; size_t chars_to_add ; chars_to_quote [ 0 ] = delim ; chars_to_quote [ 1 ] = quote ; if ( M_chr_isspace ( * cell ) || M_chr_isspace ( cell [ len - 1 ] ) || M_str_find_first_from_charset ( cell , chars_to_quote ) != NULL ) { needs_quotes = M_TRUE ; M_buf_add_char ( buf , quote ) ; } do { next_quote = M_mem_chr ( cell , ( M_uint8 ) quote , len ) ; chars_to_add = ( next_quote == NULL ) ? len : ( size_t ) ( next_quote - cell ) + 1 ; M_buf_add_bytes ( buf , cell , chars_to_add ) ; len -= chars_to_add ; cell += chars_to_add ; if ( next_quote != NULL ) { M_buf_add_char ( buf , quote ) ; } } while ( len > 0 ) ; if ( needs_quotes ) { M_buf_add_char ( buf , quote ) ; } } M_buf_add_char ( buf , delim ) ; }
Helper function for M_csv_output_headers_buf() and M_csv_output_rows_buf().
Helper function for M_csv_output_headers_buf () and M_csv_output_rows_buf () .
/*set to delim below*/ /*set to quote below*/ /* If cell value starts/ends with whitespace, or if it contains delimiter, newline chars, or quotes,
		 * it needs to be wrapped in quotes.
		 */ /* If cell value contains any quote chars, we'll need to escape them by adding a second quote character
		 * right after it.
		 */ /* Always add delimiter character at end, even if cell is empty. */