Skip to content

Commit

Permalink
GLib based (un)quoting in C++
Browse files Browse the repository at this point in the history
  • Loading branch information
mchf committed Jun 18, 2012
1 parent f913505 commit c456a6e
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 1 deletion.
4 changes: 3 additions & 1 deletion agent-ini/src/Makefile.am
Expand Up @@ -13,7 +13,9 @@ liby2ag_ini_la_SOURCES = \
IniParser.cc \
IniParser.h \
IniFile.cc \
IniFile.h
IniFile.h \
quotes.cc \
quotes.h

liby2ag_ini_la_LDFLAGS = -version-info 2:0
liby2ag_ini_la_LIBADD = @AGENT_LIBADD@
Expand Down
110 changes: 110 additions & 0 deletions agent-ini/src/quotes.cc
@@ -0,0 +1,110 @@
#include "quotes.h"

using namespace std;

string quote( string & unquoted_string)
{
string dest = "'";

for( string::iterator sit = unquoted_string.begin(); sit < unquoted_string.end(); sit++)
if( *sit == '\'')
dest += "'\\''";
else
dest += *sit;

dest += "'";

return dest;
}

// helper
// preconditions:
// - starts with ['"]
// - as a consequence: size > 0
bool parse_quoted_string( string::iterator & sit, string::iterator last, string & ret)
{
char quote_char = *( sit++);

if( quote_char == '"')
{
while( sit < last)
{
switch( *sit)
{
case '"':
return true;

case '\\':
switch( *(++sit))
{
case '"':
case '\\':
case '`':
case '$':
case '\n':
ret += *(sit++);
break;

default:
ret += '\\';
break;
}
break;

default:
ret += *(sit++);
break;
}
}
}
else
{
while( sit < last)
{
if( *sit == '\'')
{
return true;
}
else
{
ret += *(sit++);
}
}
}

// missing closing quote
return false;
}

string unquote( string & quoted_string)
{
string res;
string::iterator sit = quoted_string.begin();

while( sit < quoted_string.end())
{
while( sit < quoted_string.end() &&
*sit != '"' &&
*sit != '\'')
{
if( *sit == '\\')
{
if( *(++sit) != '\n')
res += *sit;
}
else
res += *sit;

sit++;
}

if( !( sit < quoted_string.end()))
break;

string substr;
if( parse_quoted_string( sit, quoted_string.end(), substr))
res += substr;
sit++;
}
return res;
}
9 changes: 9 additions & 0 deletions agent-ini/src/quotes.h
@@ -0,0 +1,9 @@
#ifndef __QUOTES_H__
#define __QUOTES_H__

#include <string>

std::string quote( std::string & unquoted_string);
std::string unquote( std::string & unquoted_string);

#endif

0 comments on commit c456a6e

Please sign in to comment.