/common/escapery.c
/* Blerg is (C) 2011 The Dominion of Awesome, and is distributed under a
 * BSD-style license.  Please see the COPYING file for details.
 */
#include <string.h>
#include <stdlib.h>
#include "escapery.h"

char *xml_escape(const char *str) {
	return xml_escape_data(str, strlen(str));
}

char *xml_escape_data(const char *str, int len) {
	char *r = malloc(len * 5 + 1);  /* Up to 5x the space if they're all &'s */
	int i, j;

	for (i = 0, j = 0; i < len; i++) {
		switch(str[i]) {
		case '<':
			memcpy(r + j, "&lt;", 4);
			j += 4;
			break;
		case '>':
			memcpy(r + j, "&gt;", 4);
			j += 4;
			break;
		case '&':
			memcpy(r + j, "&amp;", 5);
			j += 5;
			break;
		default:
			r[j] = str[i];
			j += 1;
		}
	}
	r[j] = 0;

	return r;
}