1 /*
2  * Copyright 2005-2007 Gerald Schmidt.
3  *
4  * This file is part of Xml Copy Editor.
5  *
6  * Xml Copy Editor is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * Xml Copy Editor is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Xml Copy Editor; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  */
20 
21 #include <cstdio>
22 #include <cstring>
23 #include "replace.h"
24 
run(std::string & buffer,const std::string & find,const std::string & replace,bool matchCase)25 int Replace::run (
26     std::string& buffer,
27     const std::string& find,
28     const std::string& replace,
29     bool matchCase )
30 {
31 	if ( buffer.empty() || find.empty() )
32 		return 0;
33 
34 	std::string output;
35 	size_t capacity = buffer.size();
36 	int diff = replace.size() - find.size();
37 	if ( diff > 0 )
38 		capacity += diff * BUFSIZ;
39 
40 	output.reserve ( capacity );
41 	size_t findLength = find.size();
42 	int matchCount = 0;
43 
44 	// comparison function pointer
45 	int ( *comp ) ( const char *, const char *, size_t ) =
46 #ifdef __WXMSW__
47 	    ( matchCase ) ? strncmp : strnicmp;
48 #else
49 	    ( matchCase ) ? strncmp : strncasecmp;
50 #endif
51 
52 	char *bufferPtr;
53 	const char *findPtr, *replacePtr;
54 	bufferPtr = ( char * ) buffer.c_str();
55 	findPtr = find.c_str();
56 	replacePtr = replace.c_str();
57 
58 	while ( *bufferPtr )
59 	{
60 		if ( !comp ( ( const char * ) bufferPtr, findPtr, findLength ) )
61 		{
62 			++matchCount;
63 			output += replacePtr;
64 			bufferPtr += findLength;
65 		}
66 		else
67 		{
68 			output += *bufferPtr;
69 			++bufferPtr;
70 		}
71 	}
72 	if ( !matchCount )
73 		return 0;
74 	buffer = output;
75 	return matchCount;
76 }
77