1 /* PSPP - computes sample statistics.
2 Copyright (C) 2007 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23 #include <libpspp/str.h>
24 #include <libpspp/assertion.h>
28 #include "syntax-gen.h"
32 has_single_quote (const struct string *str)
34 return (SIZE_MAX != ds_find_char (str, '\''));
38 has_double_quote (const struct string *str)
40 return (SIZE_MAX != ds_find_char (str, '"'));
44 Quotes the string STR. If STR contains no '\'' character, then
45 the returned value will be enclosed in single quotes. Else, if STR
46 contains no '"' character, then it will be enclosed in double
47 quotes. Otherwise, it will be enclosed in single quotes, and each
48 '\'' will be padded with another '\''.
50 STR must be encoded in UTF-8, and the quoted result will also be
54 gen_quoted_string (struct string *str)
57 static const char single_quote[] = "'";
58 static const char double_quote[] = "\"";
60 struct string quoted_str;
62 bool pad_single_quotes = false;
63 const char *delimiter ;
64 char *s = ds_cstr (str);
66 if ( has_double_quote (str))
68 delimiter = single_quote;
69 if ( has_single_quote (str))
70 pad_single_quotes = true;
74 delimiter = double_quote;
77 /* This seemingly simple implementation is possible, because UTF-8
78 guarantees that bytes corresponding to basic characters (such as
79 '\'') cannot appear in a multi-byte character sequence except to
80 represent that basic character.
82 assert (is_basic ('\''));
84 /* Initialise with the opening delimiter */
85 ds_init_cstr ("ed_str, delimiter);
88 ds_put_char ("ed_str, c);
90 /* If c is a single quote, then append another one */
91 if ( c == '\'' && pad_single_quotes)
92 ds_put_char ("ed_str, c);
95 /* Add the closing delimiter */
96 ds_put_cstr ("ed_str, delimiter);
98 /* Copy the quoted string into str */
99 ds_swap (str, "ed_str);
100 ds_destroy ("ed_str);