/* Distributed Checksum Clearinghouse
 *
 * --C-LICENSE--
 * $Revision: 1.3 $
 */

#include "dcc_defs.h"


char *
escstr(char *buf0, int buf_len, const char *src, int src_len)
{
	char *buf, *buf_end;
	u_char ascii;
	u_char c;

	if (buf_len < 4)
		dcc_logbad(EX_SOFTWARE, "bad escstr() buffer");

	ascii = 1;
	buf = buf0;
	buf_end = buf+buf_len-4;
	while (--src_len >= 0) {
		c = *src++;
		if (buf >= buf_end) {
			strcpy(buf, "...");
			return buf0;
		}
		if (c >= ' ' && c <= 0x7f) {
			if (c == '\\' || c == '"')
				*buf++ = '\\';
			*buf++ = c;
			continue;
		}
		if (ascii && c == '\0' && !memcmp(src, src-1, src_len))
			break;
		buf += sprintf(buf, "\\%03o", c);
		ascii = 0;
	}
	*buf = '\0';
	return buf0;
}



/* not thread safe */
const char *
esc_magic(const char *src, int src_len)
{
	static char magic_buf[256];

	return escstr(magic_buf, sizeof(magic_buf), src, src_len);
}
