1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 *
6 * Copyright 1997 - July 2008 CWI, August 2008 - 2019 MonetDB B.V.
7 */
8
9/*
10 * (c) M. Kersten
11 * Passing strings between front-end and kernel often require marshalling.
12 */
13#include "monetdb_config.h"
14#include "mal_utils.h"
15
16void
17mal_unquote(char *msg)
18{
19 char *p = msg, *s;
20
21 s = p;
22 while (*p) {
23 if (*p == '\\') {
24 p++;
25 switch (*p) {
26 case 'n':
27 *s = '\n';
28 break;
29 case 't':
30 *s = '\t';
31 break;
32 case 'r':
33 *s = '\r';
34 break;
35 case 'f':
36 *s = '\f';
37 break;
38 case '0':
39 case '1':
40 case '2':
41 case '3':
42 /* this could be the start of
43 an octal sequence, check it
44 out */
45 if (p[1] && p[2] && p[1] >= '0' && p[1] <= '7' && p[2] >= '0' && p[2] <= '7') {
46 *s = (char)(((p[0] - '0') << 6) | ((p[1] - '0') << 3) | (p[2] - '0'));
47 p += 2;
48 break;
49 }
50 /* fall through */
51 default:
52 *s = *p;
53 break;
54 }
55 p++;
56 } else {
57 *s = *p++;
58 }
59 s++;
60 }
61 *s = 0; /* close string */
62}
63
64char *
65mal_quote(const char *msg, size_t size)
66{
67 char *s = GDKmalloc(size * 2 + 1); /* we absolutely don't need more than this (until we start producing octal escapes */
68 char *t = s;
69
70 if ( s == NULL)
71 return NULL;
72 while (size > 0) {
73 size--;
74 switch (*msg) {
75 case '"':
76 *t++ = '\\';
77 *t++ = '"';
78 break;
79 case '\n':
80 *t++ = '\\';
81 *t++ = 'n';
82 break;
83 case '\t':
84 *t++ = '\\';
85 *t++ = 't';
86 break;
87 case '\\':
88 *t++ = '\\';
89 *t++ = '\\';
90 break;
91 default:
92 *t++ = *msg;
93 break;
94 }
95 msg++;
96 /* also deal with binaries */
97 }
98 *t = 0;
99 return s;
100}
101