summaryrefslogtreecommitdiffstats
path: root/lasso/utils.c
blob: c036923cebc76e86cd2df68770dbe06f6dc8c7da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* $Id$
 *
 * Lasso - A free implementation of the Liberty Alliance specifications.
 *
 * Copyright (C) 2004-2007 Entr'ouvert
 * http://lasso.entrouvert.org
 *
 * Authors: See AUTHORS file in top-level directory.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <glib.h>
#include "./utils.h"

gchar*
lasso_safe_prefix_string(const gchar *str, gsize length)
{
	GString *output;
	gchar *ret;
	gsize outputted = 0, i = 0;

	fprintf (stderr, "Coin %s\n", str);
	if (str == NULL) {
		return strdup("NULL");
	}
	output = g_string_sized_new(length);
	for (i = 0; i < length && str[i] && outputted < length; i++) {
		gchar c = 0;
		guint len;

		if ((guchar)str[i] < 128 && (guchar)str[i] > 31) {
			g_string_append_c(output, str[i]);
			outputted++;
			continue;
		}
		switch (str[i]) {
			case '\n':
				c = 'n';
				break;
			case '\t':
				c = 't';
				break;
			case '\r':
				c = 'r';
		}
		if (c) {
			if (outputted - length > 1) {
				g_string_append_c(output, '\\');
				g_string_append_c(output, c);
				outputted += 2;
				continue;
			}
		}
		if (c < 8) {
			len = 3;
		} else if (c < 64) {
			len = 4;
		} else {
			len = 5;
		}
		if (outputted - length >= len) {
			g_string_append_c(output, '\\');
			g_string_append_printf(output, "%o", (guint)str[i]);
		}
		break;
	}
	ret = output->str;
	g_string_free(output, FALSE);
	return ret;
}