]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/hashcomp.h
Create irc::equals() from StrHashComp
[user/henk/code/inspircd.git] / include / hashcomp.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2011 Adam <Adam@anope.org>
5  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
6  *   Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
7  *   Copyright (C) 2005-2009 Craig Edwards <craigedwards@brainbox.cc>
8  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
9  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
10  *
11  * This file is part of InspIRCd.  InspIRCd is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU General Public
13  * License as published by the Free Software Foundation, version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24
25 #pragma once
26
27 #include <cstring>
28 #include <string>
29 #include <vector>
30 #include <deque>
31 #include <map>
32 #include <set>
33 #include "inspircd.h"
34
35 /*******************************************************
36  * This file contains classes and templates that deal
37  * with the comparison and hashing of 'irc strings'.
38  * An 'irc string' is a string which compares in a
39  * case insensitive manner, and as per RFC 1459 will
40  * treat [ identical to {, ] identical to }, and \
41  * as identical to |.
42  *
43  * Our hashing functions are designed  to accept
44  * std::string and compare/hash them as type irc::string
45  * by converting them internally. This makes them
46  * backwards compatible with other code which is not
47  * aware of irc::string.
48  *******************************************************/
49
50 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
51  * if it must.
52  *
53  * This is provided as a pointer so that modules can change it to their custom mapping tables,
54  * e.g. for national character support.
55  */
56 CoreExport extern unsigned const char *national_case_insensitive_map;
57
58 /** A mapping of uppercase to lowercase, including scandinavian
59  * 'oddities' as specified by RFC1459, e.g. { -> [, and | -> \
60  */
61 CoreExport extern unsigned const char rfc_case_insensitive_map[256];
62
63 /** Case insensitive map, ASCII rules.
64  * That is;
65  * [ != {, but A == a.
66  */
67 CoreExport extern unsigned const char ascii_case_insensitive_map[256];
68
69 /** Case sensitive (identity) map.
70  */
71 CoreExport extern unsigned const char rfc_case_sensitive_map[256];
72
73 template<typename T> const T& SearchAndReplace(T& text, const T& pattern, const T& replace)
74 {
75         T replacement;
76         if ((!pattern.empty()) && (!text.empty()))
77         {
78                 for (std::string::size_type n = 0; n != text.length(); ++n)
79                 {
80                         if (text.length() >= pattern.length() && text.substr(n, pattern.length()) == pattern)
81                         {
82                                 // Found the pattern in the text, replace it, and advance
83                                 replacement.append(replace);
84                                 n = n + pattern.length() - 1;
85                         }
86                         else
87                         {
88                                 replacement += text[n];
89                         }
90                 }
91         }
92         text = replacement;
93         return text;
94 }
95
96 /** The irc namespace contains a number of helper classes.
97  */
98 namespace irc
99 {
100
101         /** Check if two IRC object (e.g. nick or channel) names are equal.
102          * This function uses national_case_insensitive_map to determine equality, which, by default does comparison
103          * according to RFC 1459, treating certain otherwise non-identical characters as identical.
104          * @param s1 First string to compare
105          * @param s2 Second string to compare
106          * @return True if the two names are equal, false otherwise
107          */
108         CoreExport bool equals(const std::string& s1, const std::string& s2);
109
110         /** This class returns true if two strings match.
111          * Case sensitivity is ignored, and the RFC 'character set'
112          * is adhered to
113          */
114         struct StrHashComp
115         {
116                 /** The operator () does the actual comparison in hash_map
117                  */
118                 bool operator()(const std::string& s1, const std::string& s2) const
119                 {
120                         return equals(s1, s2);
121                 }
122         };
123
124         struct insensitive
125         {
126                 size_t CoreExport operator()(const std::string &s) const;
127         };
128
129         struct insensitive_swo
130         {
131                 bool CoreExport operator()(const std::string& a, const std::string& b) const;
132         };
133
134         /** The irc_char_traits class is used for RFC-style comparison of strings.
135          * This class is used to implement irc::string, a case-insensitive, RFC-
136          * comparing string class.
137          */
138         struct CoreExport irc_char_traits : public std::char_traits<char>
139         {
140                 /** Check if two chars match.
141                  * @param c1st First character
142                  * @param c2nd Second character
143                  * @return true if the characters are equal
144                  */
145                 static bool eq(char c1st, char c2nd);
146
147                 /** Check if two chars do NOT match.
148                  * @param c1st First character
149                  * @param c2nd Second character
150                  * @return true if the characters are unequal
151                  */
152                 static bool ne(char c1st, char c2nd);
153
154                 /** Check if one char is less than another.
155                  * @param c1st First character
156                  * @param c2nd Second character
157                  * @return true if c1st is less than c2nd
158                  */
159                 static bool lt(char c1st, char c2nd);
160
161                 /** Compare two strings of size n.
162                  * @param str1 First string
163                  * @param str2 Second string
164                  * @param n Length to compare to
165                  * @return similar to strcmp, zero for equal, less than zero for str1
166                  * being less and greater than zero for str1 being greater than str2.
167                  */
168                 static int compare(const char* str1, const char* str2, size_t n);
169
170                 /** Find a char within a string up to position n.
171                  * @param s1 String to find in
172                  * @param n Position to search up to
173                  * @param c Character to search for
174                  * @return Pointer to the first occurance of c in s1
175                  */
176                 static const char* find(const char* s1, int  n, char c);
177         };
178
179         /** This typedef declares irc::string based upon irc_char_traits.
180          */
181         typedef std::basic_string<char, irc_char_traits, std::allocator<char> > string;
182
183         /** Joins the contents of a vector to a string.
184          * @param sequence Zero or more items to join.
185          * @separator The character to place between the items.
186          */
187         std::string CoreExport stringjoiner(const std::vector<std::string>& sequence, char separator = ' ');
188
189         /** irc::sepstream allows for splitting token seperated lists.
190          * Each successive call to sepstream::GetToken() returns
191          * the next token, until none remain, at which point the method returns
192          * an empty string.
193          */
194         class CoreExport sepstream
195         {
196          protected:
197                 /** Original string.
198                  */
199                 std::string tokens;
200                 /** Separator value
201                  */
202                 char sep;
203                 /** Current string position
204                  */
205                 size_t pos;
206                 /** If set then GetToken() can return an empty string
207                  */
208                 bool allow_empty;
209          public:
210                 /** Create a sepstream and fill it with the provided data
211                  */
212                 sepstream(const std::string &source, char separator, bool allowempty = false);
213
214                 /** Fetch the next token from the stream
215                  * @param token The next token from the stream is placed here
216                  * @return True if tokens still remain, false if there are none left
217                  */
218                 bool GetToken(std::string& token);
219
220                 /** Fetch the entire remaining stream, without tokenizing
221                  * @return The remaining part of the stream
222                  */
223                 const std::string GetRemaining();
224
225                 /** Returns true if the end of the stream has been reached
226                  * @return True if the end of the stream has been reached, otherwise false
227                  */
228                 bool StreamEnd();
229         };
230
231         /** A derived form of sepstream, which seperates on commas
232          */
233         class CoreExport commasepstream : public sepstream
234         {
235          public:
236                 /** Initialize with comma separator
237                  */
238                 commasepstream(const std::string &source, bool allowempty = false) : sepstream(source, ',', allowempty)
239                 {
240                 }
241         };
242
243         /** A derived form of sepstream, which seperates on spaces
244          */
245         class CoreExport spacesepstream : public sepstream
246         {
247          public:
248                 /** Initialize with space separator
249                  */
250                 spacesepstream(const std::string &source, bool allowempty = false) : sepstream(source, ' ', allowempty)
251                 {
252                 }
253         };
254
255         /** irc::tokenstream reads a string formatted as per RFC1459 and RFC2812.
256          * It will split the string into 'tokens' each containing one parameter
257          * from the string.
258          * For instance, if it is instantiated with the string:
259          * "PRIVMSG #test :foo bar baz qux"
260          * then each successive call to tokenstream::GetToken() will return
261          * "PRIVMSG", "#test", "foo bar baz qux", "".
262          * Note that if the whole string starts with a colon this is not taken
263          * to mean the string is all one parameter, and the first item in the
264          * list will be ":item". This is to allow for parsing 'source' fields
265          * from data.
266          */
267         class CoreExport tokenstream : private spacesepstream
268         {
269          public:
270                 /** Create a tokenstream and fill it with the provided data
271                  */
272                 tokenstream(const std::string &source);
273
274                 /** Fetch the next token from the stream as a std::string
275                  * @param token The next token available, or an empty string if none remain
276                  * @return True if tokens are left to be read, false if the last token was just retrieved.
277                  */
278                 bool GetToken(std::string &token);
279
280                 /** Fetch the next token from the stream as an integer
281                  * @param token The next token available, or undefined if none remain
282                  * @return True if tokens are left to be read, false if the last token was just retrieved.
283                  */
284                 bool GetToken(int &token);
285
286                 /** Fetch the next token from the stream as a long integer
287                  * @param token The next token available, or undefined if none remain
288                  * @return True if tokens are left to be read, false if the last token was just retrieved.
289                  */
290                 bool GetToken(long &token);
291         };
292
293         /** The portparser class seperates out a port range into integers.
294          * A port range may be specified in the input string in the form
295          * "6660,6661,6662-6669,7020". The end of the stream is indicated by
296          * a return value of 0 from portparser::GetToken(). If you attempt
297          * to specify an illegal range (e.g. one where start >= end, or
298          * start or end < 0) then GetToken() will return the first element
299          * of the pair of numbers.
300          */
301         class CoreExport portparser
302         {
303          private:
304
305                 /** Used to split on commas
306                  */
307                 commasepstream sep;
308
309                 /** Current position in a range of ports
310                  */
311                 long in_range;
312
313                 /** Starting port in a range of ports
314                  */
315                 long range_begin;
316
317                 /** Ending port in a range of ports
318                  */
319                 long range_end;
320
321                 /** Allow overlapped port ranges
322                  */
323                 bool overlapped;
324
325                 /** Used to determine overlapping of ports
326                  * without O(n) algorithm being used
327                  */
328                 std::set<long> overlap_set;
329
330                 /** Returns true if val overlaps an existing range
331                  */
332                 bool Overlaps(long val);
333          public:
334
335                 /** Create a portparser and fill it with the provided data
336                  * @param source The source text to parse from
337                  * @param allow_overlapped Allow overlapped ranges
338                  */
339                 portparser(const std::string &source, bool allow_overlapped = true);
340
341                 /** Fetch the next token from the stream
342                  * @return The next port number is returned, or 0 if none remain
343                  */
344                 long GetToken();
345         };
346 }
347
348 /* Define operators for using >> and << with irc::string to an ostream on an istream. */
349 /* This was endless fun. No. Really. */
350 /* It was also the first core change Ommeh made, if anyone cares */
351
352 /** Operator << for irc::string
353  */
354 inline std::ostream& operator<<(std::ostream &os, const irc::string &str) { return os << str.c_str(); }
355
356 /** Operator >> for irc::string
357  */
358 inline std::istream& operator>>(std::istream &is, irc::string &str)
359 {
360         std::string tmp;
361         is >> tmp;
362         str = tmp.c_str();
363         return is;
364 }
365
366 /* Define operators for + and == with irc::string to std::string for easy assignment
367  * and comparison
368  *
369  * Operator +
370  */
371 inline std::string operator+ (std::string& leftval, irc::string& rightval)
372 {
373         return leftval + std::string(rightval.c_str());
374 }
375
376 /* Define operators for + and == with irc::string to std::string for easy assignment
377  * and comparison
378  *
379  * Operator +
380  */
381 inline irc::string operator+ (irc::string& leftval, std::string& rightval)
382 {
383         return leftval + irc::string(rightval.c_str());
384 }
385
386 /* Define operators for + and == with irc::string to std::string for easy assignment
387  * and comparison
388  *
389  * Operator ==
390  */
391 inline bool operator== (const std::string& leftval, const irc::string& rightval)
392 {
393         return (leftval.c_str() == rightval);
394 }
395
396 /* Define operators for + and == with irc::string to std::string for easy assignment
397  * and comparison
398  *
399  * Operator ==
400  */
401 inline bool operator== (const irc::string& leftval, const std::string& rightval)
402 {
403         return (leftval == rightval.c_str());
404 }
405
406 /* Define operators != for irc::string to std::string for easy comparison
407  */
408 inline bool operator!= (const irc::string& leftval, const std::string& rightval)
409 {
410         return !(leftval == rightval.c_str());
411 }
412
413 /* Define operators != for std::string to irc::string for easy comparison
414  */
415 inline bool operator!= (const std::string& leftval, const irc::string& rightval)
416 {
417         return !(leftval.c_str() == rightval);
418 }
419
420 /** Assign an irc::string to a std::string.
421  */
422 inline std::string assign(const irc::string &other) { return other.c_str(); }
423
424 /** Assign a std::string to an irc::string.
425  */
426 inline irc::string assign(const std::string &other) { return other.c_str(); }