]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/hashcomp.h
Add functor that does strict weak ordering based on national_case_insensitive_map
[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         /** This class returns true if two strings match.
102          * Case sensitivity is ignored, and the RFC 'character set'
103          * is adhered to
104          */
105         struct CoreExport StrHashComp
106         {
107                 /** The operator () does the actual comparison in hash_map
108                  */
109                 bool operator()(const std::string& s1, const std::string& s2) const;
110         };
111
112         struct insensitive
113         {
114                 size_t CoreExport operator()(const std::string &s) const;
115         };
116
117         struct insensitive_swo
118         {
119                 bool CoreExport operator()(const std::string& a, const std::string& b) const;
120         };
121
122         /** The irc_char_traits class is used for RFC-style comparison of strings.
123          * This class is used to implement irc::string, a case-insensitive, RFC-
124          * comparing string class.
125          */
126         struct CoreExport irc_char_traits : public std::char_traits<char>
127         {
128                 /** Check if two chars match.
129                  * @param c1st First character
130                  * @param c2nd Second character
131                  * @return true if the characters are equal
132                  */
133                 static bool eq(char c1st, char c2nd);
134
135                 /** Check if two chars do NOT match.
136                  * @param c1st First character
137                  * @param c2nd Second character
138                  * @return true if the characters are unequal
139                  */
140                 static bool ne(char c1st, char c2nd);
141
142                 /** Check if one char is less than another.
143                  * @param c1st First character
144                  * @param c2nd Second character
145                  * @return true if c1st is less than c2nd
146                  */
147                 static bool lt(char c1st, char c2nd);
148
149                 /** Compare two strings of size n.
150                  * @param str1 First string
151                  * @param str2 Second string
152                  * @param n Length to compare to
153                  * @return similar to strcmp, zero for equal, less than zero for str1
154                  * being less and greater than zero for str1 being greater than str2.
155                  */
156                 static int compare(const char* str1, const char* str2, size_t n);
157
158                 /** Find a char within a string up to position n.
159                  * @param s1 String to find in
160                  * @param n Position to search up to
161                  * @param c Character to search for
162                  * @return Pointer to the first occurance of c in s1
163                  */
164                 static const char* find(const char* s1, int  n, char c);
165         };
166
167         /** This typedef declares irc::string based upon irc_char_traits.
168          */
169         typedef std::basic_string<char, irc_char_traits, std::allocator<char> > string;
170
171         /** irc::stringjoiner joins string lists into a string, using
172          * space as the separator.
173          * This class can join a vector of std::string.
174          */
175         class CoreExport stringjoiner
176         {
177          private:
178
179                 /** Output string
180                  */
181                 std::string joined;
182
183          public:
184
185                 /** Join all elements of a vector, in the resulting string
186                  * each element will be seperated by a single space character.
187                  * @param sequence Zero or more items to seperate
188                  */
189                 stringjoiner(const std::vector<std::string>& sequence);
190
191                 /** Get the joined sequence
192                  * @return A constant reference to the joined string
193                  */
194                 const std::string& GetJoined() const { return joined; }
195         };
196
197         /** irc::modestacker stacks mode sequences into a list.
198          * It can then reproduce this list, clamped to a maximum of MAXMODES
199          * values per line.
200          */
201         class CoreExport modestacker
202         {
203          private:
204                 /** The mode sequence and its parameters
205                  */
206                 std::deque<std::string> sequence;
207
208                 /** True if the mode sequence is initially adding
209                  * characters, false if it is initially removing
210                  * them
211                  */
212                 bool adding;
213          public:
214
215                 /** Construct a new modestacker.
216                  * @param add True if the stack is adding modes,
217                  * false if it is removing them
218                  */
219                 modestacker(bool add);
220
221                 /** Push a modeletter and its parameter onto the stack.
222                  * No checking is performed as to if this mode actually
223                  * requires a parameter. If you stack invalid mode
224                  * sequences, they will be tidied if and when they are
225                  * passed to a mode parser.
226                  * @param modeletter The mode letter to insert
227                  * @param parameter The parameter for the mode
228                  */
229                 void Push(char modeletter, const std::string &parameter);
230
231                 /** Push a modeletter without parameter onto the stack.
232                  * No checking is performed as to if this mode actually
233                  * requires a parameter. If you stack invalid mode
234                  * sequences, they will be tidied if and when they are
235                  * passed to a mode parser.
236                  * @param modeletter The mode letter to insert
237                  */
238                 void Push(char modeletter);
239
240                 /** Push a '+' symbol onto the stack.
241                  */
242                 void PushPlus();
243
244                 /** Push a '-' symbol onto the stack.
245                  */
246                 void PushMinus();
247
248                 /** Return zero or more elements which form the
249                  * mode line. This will be clamped to a max of
250                  * MAXMODES items (MAXMODES-1 mode parameters and
251                  * one mode sequence string), and max_line_size
252                  * characters. As specified below, this function
253                  * should be called in a loop until it returns zero,
254                  * indicating there are no more modes to return.
255                  * @param result The vector to populate. This will not
256                  * be cleared before it is used.
257                  * @param max_line_size The maximum size of the line
258                  * to build, in characters, seperate to MAXMODES.
259                  * @return The number of elements in the deque.
260                  * The function should be called repeatedly until it
261                  * returns 0, in case there are multiple lines of
262                  * mode changes to be obtained.
263                  */
264                 int GetStackedLine(std::vector<std::string> &result, int max_line_size = 360);
265
266         };
267
268         /** irc::sepstream allows for splitting token seperated lists.
269          * Each successive call to sepstream::GetToken() returns
270          * the next token, until none remain, at which point the method returns
271          * an empty string.
272          */
273         class CoreExport sepstream
274         {
275          protected:
276                 /** Original string.
277                  */
278                 std::string tokens;
279                 /** Separator value
280                  */
281                 char sep;
282                 /** Current string position
283                  */
284                 size_t pos;
285                 /** If set then GetToken() can return an empty string
286                  */
287                 bool allow_empty;
288          public:
289                 /** Create a sepstream and fill it with the provided data
290                  */
291                 sepstream(const std::string &source, char separator, bool allowempty = false);
292
293                 /** Fetch the next token from the stream
294                  * @param token The next token from the stream is placed here
295                  * @return True if tokens still remain, false if there are none left
296                  */
297                 bool GetToken(std::string& token);
298
299                 /** Fetch the entire remaining stream, without tokenizing
300                  * @return The remaining part of the stream
301                  */
302                 const std::string GetRemaining();
303
304                 /** Returns true if the end of the stream has been reached
305                  * @return True if the end of the stream has been reached, otherwise false
306                  */
307                 bool StreamEnd();
308         };
309
310         /** A derived form of sepstream, which seperates on commas
311          */
312         class CoreExport commasepstream : public sepstream
313         {
314          public:
315                 /** Initialize with comma separator
316                  */
317                 commasepstream(const std::string &source, bool allowempty = false) : sepstream(source, ',', allowempty)
318                 {
319                 }
320         };
321
322         /** A derived form of sepstream, which seperates on spaces
323          */
324         class CoreExport spacesepstream : public sepstream
325         {
326          public:
327                 /** Initialize with space separator
328                  */
329                 spacesepstream(const std::string &source, bool allowempty = false) : sepstream(source, ' ', allowempty)
330                 {
331                 }
332         };
333
334         /** irc::tokenstream reads a string formatted as per RFC1459 and RFC2812.
335          * It will split the string into 'tokens' each containing one parameter
336          * from the string.
337          * For instance, if it is instantiated with the string:
338          * "PRIVMSG #test :foo bar baz qux"
339          * then each successive call to tokenstream::GetToken() will return
340          * "PRIVMSG", "#test", "foo bar baz qux", "".
341          * Note that if the whole string starts with a colon this is not taken
342          * to mean the string is all one parameter, and the first item in the
343          * list will be ":item". This is to allow for parsing 'source' fields
344          * from data.
345          */
346         class CoreExport tokenstream : private spacesepstream
347         {
348          public:
349                 /** Create a tokenstream and fill it with the provided data
350                  */
351                 tokenstream(const std::string &source);
352
353                 /** Fetch the next token from the stream as a std::string
354                  * @param token The next token available, or an empty string if none remain
355                  * @return True if tokens are left to be read, false if the last token was just retrieved.
356                  */
357                 bool GetToken(std::string &token);
358
359                 /** Fetch the next token from the stream as an irc::string
360                  * @param token The next token available, or an empty string if none remain
361                  * @return True if tokens are left to be read, false if the last token was just retrieved.
362                  */
363                 bool GetToken(irc::string &token);
364
365                 /** Fetch the next token from the stream as an integer
366                  * @param token The next token available, or undefined if none remain
367                  * @return True if tokens are left to be read, false if the last token was just retrieved.
368                  */
369                 bool GetToken(int &token);
370
371                 /** Fetch the next token from the stream as a long integer
372                  * @param token The next token available, or undefined if none remain
373                  * @return True if tokens are left to be read, false if the last token was just retrieved.
374                  */
375                 bool GetToken(long &token);
376         };
377
378         /** The portparser class seperates out a port range into integers.
379          * A port range may be specified in the input string in the form
380          * "6660,6661,6662-6669,7020". The end of the stream is indicated by
381          * a return value of 0 from portparser::GetToken(). If you attempt
382          * to specify an illegal range (e.g. one where start >= end, or
383          * start or end < 0) then GetToken() will return the first element
384          * of the pair of numbers.
385          */
386         class CoreExport portparser
387         {
388          private:
389
390                 /** Used to split on commas
391                  */
392                 commasepstream sep;
393
394                 /** Current position in a range of ports
395                  */
396                 long in_range;
397
398                 /** Starting port in a range of ports
399                  */
400                 long range_begin;
401
402                 /** Ending port in a range of ports
403                  */
404                 long range_end;
405
406                 /** Allow overlapped port ranges
407                  */
408                 bool overlapped;
409
410                 /** Used to determine overlapping of ports
411                  * without O(n) algorithm being used
412                  */
413                 std::set<long> overlap_set;
414
415                 /** Returns true if val overlaps an existing range
416                  */
417                 bool Overlaps(long val);
418          public:
419
420                 /** Create a portparser and fill it with the provided data
421                  * @param source The source text to parse from
422                  * @param allow_overlapped Allow overlapped ranges
423                  */
424                 portparser(const std::string &source, bool allow_overlapped = true);
425
426                 /** Fetch the next token from the stream
427                  * @return The next port number is returned, or 0 if none remain
428                  */
429                 long GetToken();
430         };
431
432         struct hash
433         {
434                 /** Hash an irc::string using RFC1459 case sensitivity rules
435                  * @param s A string to hash
436                  * @return The hash value
437                  */
438                 size_t CoreExport operator()(const irc::string &s) const;
439         };
440 }
441
442 /* Define operators for using >> and << with irc::string to an ostream on an istream. */
443 /* This was endless fun. No. Really. */
444 /* It was also the first core change Ommeh made, if anyone cares */
445
446 /** Operator << for irc::string
447  */
448 inline std::ostream& operator<<(std::ostream &os, const irc::string &str) { return os << str.c_str(); }
449
450 /** Operator >> for irc::string
451  */
452 inline std::istream& operator>>(std::istream &is, irc::string &str)
453 {
454         std::string tmp;
455         is >> tmp;
456         str = tmp.c_str();
457         return is;
458 }
459
460 /* Define operators for + and == with irc::string to std::string for easy assignment
461  * and comparison
462  *
463  * Operator +
464  */
465 inline std::string operator+ (std::string& leftval, irc::string& rightval)
466 {
467         return leftval + std::string(rightval.c_str());
468 }
469
470 /* Define operators for + and == with irc::string to std::string for easy assignment
471  * and comparison
472  *
473  * Operator +
474  */
475 inline irc::string operator+ (irc::string& leftval, std::string& rightval)
476 {
477         return leftval + irc::string(rightval.c_str());
478 }
479
480 /* Define operators for + and == with irc::string to std::string for easy assignment
481  * and comparison
482  *
483  * Operator ==
484  */
485 inline bool operator== (const std::string& leftval, const irc::string& rightval)
486 {
487         return (leftval.c_str() == rightval);
488 }
489
490 /* Define operators for + and == with irc::string to std::string for easy assignment
491  * and comparison
492  *
493  * Operator ==
494  */
495 inline bool operator== (const irc::string& leftval, const std::string& rightval)
496 {
497         return (leftval == rightval.c_str());
498 }
499
500 /* Define operators != for irc::string to std::string for easy comparison
501  */
502 inline bool operator!= (const irc::string& leftval, const std::string& rightval)
503 {
504         return !(leftval == rightval.c_str());
505 }
506
507 /* Define operators != for std::string to irc::string for easy comparison
508  */
509 inline bool operator!= (const std::string& leftval, const irc::string& rightval)
510 {
511         return !(leftval.c_str() == rightval);
512 }
513
514 /** Assign an irc::string to a std::string.
515  */
516 inline std::string assign(const irc::string &other) { return other.c_str(); }
517
518 /** Assign a std::string to an irc::string.
519  */
520 inline irc::string assign(const std::string &other) { return other.c_str(); }
521
522 /** Trim the leading and trailing spaces from a std::string.
523  */
524 inline std::string& trim(std::string &str)
525 {
526         std::string::size_type start = str.find_first_not_of(" ");
527         std::string::size_type end = str.find_last_not_of(" ");
528         if (start == std::string::npos || end == std::string::npos)
529                 str = "";
530         else
531                 str = str.substr(start, end-start+1);
532
533         return str;
534 }