]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/hashcomp.h
df36eefde30526484629f1c0ee311c2491ddf1e2
[user/henk/code/inspircd.git] / include / hashcomp.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #ifndef _HASHCOMP_H_
15 #define _HASHCOMP_H_
16
17 #include <cstring>
18 #include <string>
19 #include <vector>
20 #include <deque>
21 #include <map>
22 #include <set>
23 #include "hash_map.h"
24
25 /*******************************************************
26  * This file contains classes and templates that deal
27  * with the comparison and hashing of 'irc strings'.
28  * An 'irc string' is a string which compares in a
29  * case insensitive manner, and as per RFC 1459 will
30  * treat [ identical to {, ] identical to }, and \
31  * as identical to |.
32  *
33  * Our hashing functions are designed  to accept
34  * std::string and compare/hash them as type irc::string
35  * by converting them internally. This makes them
36  * backwards compatible with other code which is not
37  * aware of irc::string.
38  *******************************************************/
39
40 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
41  * if it must.
42  *
43  * This is provided as a pointer so that modules can change it to their custom mapping tables,
44  * e.g. for national character support.
45  */
46 CoreExport extern unsigned const char *national_case_insensitive_map;
47
48 /** A mapping of uppercase to lowercase, including scandinavian
49  * 'oddities' as specified by RFC1459, e.g. { -> [, and | -> \
50  */
51 CoreExport extern unsigned const char rfc_case_insensitive_map[256];
52
53 /** Case insensitive map, ASCII rules.
54  * That is;
55  * [ != {, but A == a.
56  */
57 CoreExport extern unsigned const char ascii_case_insensitive_map[256];
58
59 /** Case sensitive (identity) map.
60  */
61 CoreExport extern unsigned const char rfc_case_sensitive_map[256];
62
63 template<typename T> const T& SearchAndReplace(T& text, const T& pattern, const T& replace)
64 {
65         T replacement;
66         if ((!pattern.empty()) && (!text.empty()))
67         {
68                 for (std::string::size_type n = 0; n != text.length(); ++n)
69                 {
70                         if (text.length() >= pattern.length() && text.substr(n, pattern.length()) == pattern)
71                         {
72                                 /* Found the pattern in the text, replace it, and advance */
73                                 replacement.append(replace);
74                                 n = n + pattern.length() - 1;
75                         }
76                         else
77                         {
78                                 replacement += text[n];
79                         }
80                 }
81         }
82         text = replacement;
83         return text;
84 }
85
86 /** The irc namespace contains a number of helper classes.
87  */
88 namespace irc
89 {
90
91         /** This class returns true if two strings match.
92          * Case sensitivity is ignored, and the RFC 'character set'
93          * is adhered to
94          */
95         struct StrHashComp
96         {
97                 /** The operator () does the actual comparison in hash_map
98                  */
99                 bool operator()(const std::string& s1, const std::string& s2) const;
100         };
101
102         /** The irc_char_traits class is used for RFC-style comparison of strings.
103          * This class is used to implement irc::string, a case-insensitive, RFC-
104          * comparing string class.
105          */
106         struct irc_char_traits : std::char_traits<char> {
107
108                 /** Check if two chars match.
109                  * @param c1st First character
110                  * @param c2nd Second character
111                  * @return true if the characters are equal
112                  */
113                 static bool eq(char c1st, char c2nd);
114
115                 /** Check if two chars do NOT match.
116                  * @param c1st First character
117                  * @param c2nd Second character
118                  * @return true if the characters are unequal
119                  */
120                 static bool ne(char c1st, char c2nd);
121
122                 /** Check if one char is less than another.
123                  * @param c1st First character
124                  * @param c2nd Second character
125                  * @return true if c1st is less than c2nd
126                  */
127                 static bool lt(char c1st, char c2nd);
128
129                 /** Compare two strings of size n.
130                  * @param str1 First string
131                  * @param str2 Second string
132                  * @param n Length to compare to
133                  * @return similar to strcmp, zero for equal, less than zero for str1
134                  * being less and greater than zero for str1 being greater than str2.
135                  */
136                 static CoreExport int compare(const char* str1, const char* str2, size_t n);
137
138                 /** Find a char within a string up to position n.
139                  * @param s1 String to find in
140                  * @param n Position to search up to
141                  * @param c Character to search for
142                  * @return Pointer to the first occurance of c in s1
143                  */
144                 static CoreExport const char* find(const char* s1, int  n, char c);
145         };
146
147         /** Compose a hex string from raw data.
148          * @param raw The raw data to compose hex from
149          * @pram rawsz The size of the raw data buffer
150          * @return The hex string.
151          */
152         CoreExport std::string hex(const unsigned char *raw, size_t rawsz);
153
154         /** This typedef declares irc::string based upon irc_char_traits.
155          */
156         typedef std::basic_string<char, irc_char_traits, std::allocator<char> > string;
157
158         /** irc::stringjoiner joins string lists into a string, using
159          * the given seperator string.
160          * This class can join a vector of std::string, a deque of
161          * std::string, or a const char* const* array, using overloaded
162          * constructors.
163          */
164         class CoreExport stringjoiner
165         {
166          private:
167
168                 /** Output string
169                  */
170                 std::string joined;
171
172          public:
173
174                 /** Join elements of a vector, between (and including) begin and end
175                  * @param seperator The string to seperate values with
176                  * @param sequence One or more items to seperate
177                  * @param begin The starting element in the sequence to be joined
178                  * @param end The ending element in the sequence to be joined
179                  */
180                 stringjoiner(const std::string &seperator, const std::vector<std::string> &sequence, int begin, int end);
181
182                 /** Join elements of a deque, between (and including) begin and end
183                  * @param seperator The string to seperate values with
184                  * @param sequence One or more items to seperate
185                  * @param begin The starting element in the sequence to be joined
186                  * @param end The ending element in the sequence to be joined
187                  */
188                 stringjoiner(const std::string &seperator, const std::deque<std::string> &sequence, int begin, int end);
189
190                 /** Join elements of an array of char arrays, between (and including) begin and end
191                  * @param seperator The string to seperate values with
192                  * @param sequence One or more items to seperate
193                  * @param begin The starting element in the sequence to be joined
194                  * @param end The ending element in the sequence to be joined
195                  */
196                 stringjoiner(const std::string &seperator, const char* const* sequence, int begin, int end);
197
198                 /** Get the joined sequence
199                  * @return A reference to the joined string
200                  */
201                 std::string& GetJoined();
202         };
203
204         /** irc::modestacker stacks mode sequences into a list.
205          * It can then reproduce this list, clamped to a maximum of MAXMODES
206          * values per line.
207          */
208         class CoreExport modestacker
209         {
210          private:
211                 /** The mode sequence and its parameters
212                  */
213                 std::deque<std::string> sequence;
214
215                 /** True if the mode sequence is initially adding
216                  * characters, false if it is initially removing
217                  * them
218                  */
219                 bool adding;
220          public:
221
222                 /** Construct a new modestacker.
223                  * @param add True if the stack is adding modes,
224                  * false if it is removing them
225                  */
226                 modestacker(bool add);
227
228                 /** Push a modeletter and its parameter onto the stack.
229                  * No checking is performed as to if this mode actually
230                  * requires a parameter. If you stack invalid mode
231                  * sequences, they will be tidied if and when they are
232                  * passed to a mode parser.
233                  * @param modeletter The mode letter to insert
234                  * @param parameter The parameter for the mode
235                  */
236                 void Push(char modeletter, const std::string &parameter);
237
238                 /** Push a modeletter without parameter onto the stack.
239                  * No checking is performed as to if this mode actually
240                  * requires a parameter. If you stack invalid mode
241                  * sequences, they will be tidied if and when they are
242                  * passed to a mode parser.
243                  * @param modeletter The mode letter to insert
244                  */
245                 void Push(char modeletter);
246
247                 /** Push a '+' symbol onto the stack.
248                  */
249                 void PushPlus();
250
251                 /** Push a '-' symbol onto the stack.
252                  */
253                 void PushMinus();
254
255                 /** Return zero or more elements which form the
256                  * mode line. This will be clamped to a max of
257                  * MAXMODES items (MAXMODES-1 mode parameters and
258                  * one mode sequence string), and max_line_size
259                  * characters. As specified below, this function
260                  * should be called in a loop until it returns zero,
261                  * indicating there are no more modes to return.
262                  * @param result The vector to populate. This will not
263                  * be cleared before it is used.
264                  * @param max_line_size The maximum size of the line
265                  * to build, in characters, seperate to MAXMODES.
266                  * @return The number of elements in the deque.
267                  * The function should be called repeatedly until it
268                  * returns 0, in case there are multiple lines of
269                  * mode changes to be obtained.
270                  */
271                 int GetStackedLine(std::vector<std::string> &result, int max_line_size = 360);
272
273                 /** deprecated compatability interface - TODO remove */
274                 int GetStackedLine(std::deque<std::string> &result, int max_line_size = 360) {
275                         std::vector<std::string> r;
276                         int n = GetStackedLine(r, max_line_size);
277                         result.clear();
278                         result.insert(result.end(), r.begin(), r.end());
279                         return n;
280                 }
281         };
282
283         /** irc::tokenstream reads a string formatted as per RFC1459 and RFC2812.
284          * It will split the string into 'tokens' each containing one parameter
285          * from the string.
286          * For instance, if it is instantiated with the string:
287          * "PRIVMSG #test :foo bar baz qux"
288          * then each successive call to tokenstream::GetToken() will return
289          * "PRIVMSG", "#test", "foo bar baz qux", "".
290          * Note that if the whole string starts with a colon this is not taken
291          * to mean the string is all one parameter, and the first item in the
292          * list will be ":item". This is to allow for parsing 'source' fields
293          * from data.
294          */
295         class CoreExport tokenstream
296         {
297          private:
298
299                 /** Original string
300                  */
301                 std::string tokens;
302
303                 /** Last position of a seperator token
304                  */
305                 std::string::iterator last_starting_position;
306
307                 /** Current string position
308                  */
309                 std::string::iterator n;
310
311                 /** True if the last value was an ending value
312                  */
313                 bool last_pushed;
314          public:
315
316                 /** Create a tokenstream and fill it with the provided data
317                  */
318                 tokenstream(const std::string &source);
319
320                 /** Destructor
321                  */
322                 ~tokenstream();
323
324                 /** Fetch the next token from the stream as a std::string
325                  * @param token The next token available, or an empty string if none remain
326                  * @return True if tokens are left to be read, false if the last token was just retrieved.
327                  */
328                 bool GetToken(std::string &token);
329
330                 /** Fetch the next token from the stream as an irc::string
331                  * @param token The next token available, or an empty string if none remain
332                  * @return True if tokens are left to be read, false if the last token was just retrieved.
333                  */
334                 bool GetToken(irc::string &token);
335
336                 /** Fetch the next token from the stream as an integer
337                  * @param token The next token available, or undefined if none remain
338                  * @return True if tokens are left to be read, false if the last token was just retrieved.
339                  */
340                 bool GetToken(int &token);
341
342                 /** Fetch the next token from the stream as a long integer
343                  * @param token The next token available, or undefined if none remain
344                  * @return True if tokens are left to be read, false if the last token was just retrieved.
345                  */
346                 bool GetToken(long &token);
347         };
348
349         /** irc::sepstream allows for splitting token seperated lists.
350          * Each successive call to sepstream::GetToken() returns
351          * the next token, until none remain, at which point the method returns
352          * an empty string.
353          */
354         class CoreExport sepstream
355         {
356          private:
357                 /** Original string.
358                  */
359                 std::string tokens;
360                 /** Last position of a seperator token
361                  */
362                 std::string::iterator last_starting_position;
363                 /** Current string position
364                  */
365                 std::string::iterator n;
366                 /** Seperator value
367                  */
368                 char sep;
369          public:
370                 /** Create a sepstream and fill it with the provided data
371                  */
372                 sepstream(const std::string &source, char seperator);
373
374                 /** Destructor
375                  */
376                 virtual ~sepstream();
377
378                 /** Fetch the next token from the stream
379                  * @param token The next token from the stream is placed here
380                  * @return True if tokens still remain, false if there are none left
381                  */
382                 virtual bool GetToken(std::string &token);
383
384                 /** Fetch the entire remaining stream, without tokenizing
385                  * @return The remaining part of the stream
386                  */
387                 virtual const std::string GetRemaining();
388
389                 /** Returns true if the end of the stream has been reached
390                  * @return True if the end of the stream has been reached, otherwise false
391                  */
392                 virtual bool StreamEnd();
393         };
394
395         /** A derived form of sepstream, which seperates on commas
396          */
397         class CoreExport commasepstream : public sepstream
398         {
399          public:
400                 /** Initialize with comma seperator
401                  */
402                 commasepstream(const std::string &source) : sepstream(source, ',')
403                 {
404                 }
405         };
406
407         /** A derived form of sepstream, which seperates on spaces
408          */
409         class CoreExport spacesepstream : public sepstream
410         {
411          public:
412                 /** Initialize with space seperator
413                  */
414                 spacesepstream(const std::string &source) : sepstream(source, ' ')
415                 {
416                 }
417         };
418
419         /** The portparser class seperates out a port range into integers.
420          * A port range may be specified in the input string in the form
421          * "6660,6661,6662-6669,7020". The end of the stream is indicated by
422          * a return value of 0 from portparser::GetToken(). If you attempt
423          * to specify an illegal range (e.g. one where start >= end, or
424          * start or end < 0) then GetToken() will return the first element
425          * of the pair of numbers.
426          */
427         class CoreExport portparser
428         {
429          private:
430
431                 /** Used to split on commas
432                  */
433                 commasepstream* sep;
434
435                 /** Current position in a range of ports
436                  */
437                 long in_range;
438
439                 /** Starting port in a range of ports
440                  */
441                 long range_begin;
442
443                 /** Ending port in a range of ports
444                  */
445                 long range_end;
446
447                 /** Allow overlapped port ranges
448                  */
449                 bool overlapped;
450
451                 /** Used to determine overlapping of ports
452                  * without O(n) algorithm being used
453                  */
454                 std::map<long, bool> overlap_set;
455
456                 /** Returns true if val overlaps an existing range
457                  */
458                 bool Overlaps(long val);
459          public:
460
461                 /** Create a portparser and fill it with the provided data
462                  * @param source The source text to parse from
463                  * @param allow_overlapped Allow overlapped ranges
464                  */
465                 portparser(const std::string &source, bool allow_overlapped = true);
466
467                 /** Frees the internal commasepstream object
468                  */
469                 ~portparser();
470
471                 /** Fetch the next token from the stream
472                  * @return The next port number is returned, or 0 if none remain
473                  */
474                 long GetToken();
475         };
476
477         /** Turn _ characters in a string into spaces
478          * @param n String to translate
479          * @return The new value with _ translated to space.
480          */
481         CoreExport const char* Spacify(const char* n);
482 }
483
484 /* Define operators for using >> and << with irc::string to an ostream on an istream. */
485 /* This was endless fun. No. Really. */
486 /* It was also the first core change Ommeh made, if anyone cares */
487
488 /** Operator << for irc::string
489  */
490 inline std::ostream& operator<<(std::ostream &os, const irc::string &str) { return os << str.c_str(); }
491
492 /** Operator >> for irc::string
493  */
494 inline std::istream& operator>>(std::istream &is, irc::string &str)
495 {
496         std::string tmp;
497         is >> tmp;
498         str = tmp.c_str();
499         return is;
500 }
501
502 /* Define operators for + and == with irc::string to std::string for easy assignment
503  * and comparison
504  *
505  * Operator +
506  */
507 inline std::string operator+ (std::string& leftval, irc::string& rightval)
508 {
509         return leftval + std::string(rightval.c_str());
510 }
511
512 /* Define operators for + and == with irc::string to std::string for easy assignment
513  * and comparison
514  *
515  * Operator +
516  */
517 inline irc::string operator+ (irc::string& leftval, std::string& rightval)
518 {
519         return leftval + irc::string(rightval.c_str());
520 }
521
522 /* Define operators for + and == with irc::string to std::string for easy assignment
523  * and comparison
524  *
525  * Operator ==
526  */
527 inline bool operator== (const std::string& leftval, const irc::string& rightval)
528 {
529         return (leftval.c_str() == rightval);
530 }
531
532 /* Define operators for + and == with irc::string to std::string for easy assignment
533  * and comparison
534  *
535  * Operator ==
536  */
537 inline bool operator== (const irc::string& leftval, const std::string& rightval)
538 {
539         return (leftval == rightval.c_str());
540 }
541
542 /* Define operators != for irc::string to std::string for easy comparison
543  */
544 inline bool operator!= (const irc::string& leftval, const std::string& rightval)
545 {
546         return !(leftval == rightval.c_str());
547 }
548
549 /* Define operators != for std::string to irc::string for easy comparison
550  */
551 inline bool operator!= (const std::string& leftval, const irc::string& rightval)
552 {
553         return !(leftval.c_str() == rightval);
554 }
555
556 /** Assign an irc::string to a std::string.
557  */
558 inline std::string assign(const irc::string &other) { return other.c_str(); }
559
560 /** Assign a std::string to an irc::string.
561  */
562 inline irc::string assign(const std::string &other) { return other.c_str(); }
563
564 /** Trim the leading and trailing spaces from a std::string.
565  */
566 inline std::string& trim(std::string &str)
567 {
568         std::string::size_type start = str.find_first_not_of(" ");
569         std::string::size_type end = str.find_last_not_of(" ");
570         if (start == std::string::npos || end == std::string::npos)
571                 str = "";
572         else
573                 str = str.substr(start, end-start+1);
574
575         return str;
576 }
577
578 /** Hashing stuff is totally different on vc++'s hash_map implementation, so to save a buttload of
579  * #ifdefs we'll just do it all at once. Except, of course, with TR1, when it's the same as GCC.
580  */
581 BEGIN_HASHMAP_NAMESPACE
582
583         /** Hashing function to hash irc::string
584          */
585 #if defined(WINDOWS) && !defined(HAS_TR1_UNORDERED)
586         template<> class CoreExport hash_compare<irc::string, std::less<irc::string> >
587         {
588         public:
589                 enum { bucket_size = 4, min_buckets = 8 }; /* Got these numbers from the CRT source, if anyone wants to change them feel free. */
590
591                 /** Compare two irc::string values for hashing in hash_map
592                  */
593                 bool operator()(const irc::string & s1, const irc::string & s2) const
594                 {
595                         if(s1.length() != s2.length()) return true;
596                         return (irc::irc_char_traits::compare(s1.c_str(), s2.c_str(), (size_t)s1.length()) < 0);
597                 }
598
599                 /** Hash an irc::string value for hash_map
600                  */
601                 size_t operator()(const irc::string & s) const;
602         };
603
604         template<> class CoreExport hash_compare<std::string, std::less<std::string> >
605         {
606         public:
607                 enum { bucket_size = 4, min_buckets = 8 }; /* Again, from the CRT source */
608
609                 /** Compare two std::string values for hashing in hash_map
610                  */
611                 bool operator()(const std::string & s1, const std::string & s2) const
612                 {
613                         if(s1.length() != s2.length()) return true;
614                         return (irc::irc_char_traits::compare(s1.c_str(), s2.c_str(), (size_t)s1.length()) < 0);
615                 }
616
617                 /** Hash a std::string using RFC1459 case sensitivity rules
618                 * @param s A string to hash
619                 * @return The hash value
620                 */
621                 size_t operator()(const std::string & s) const;
622         };
623 #else
624
625         template<> struct hash<irc::string>
626         {
627                 /** Hash an irc::string using RFC1459 case sensitivity rules
628                  * @param s A string to hash
629                  * @return The hash value
630                  */
631                 size_t CoreExport operator()(const irc::string &s) const;
632         };
633
634         /* XXX FIXME: Implement a hash function overriding std::string's that works with TR1! */
635
636 #ifdef HASHMAP_DEPRECATED
637         struct insensitive
638 #else
639         CoreExport template<> struct hash<std::string>
640 #endif
641         {
642                 size_t CoreExport operator()(const std::string &s) const;
643         };
644
645 #endif
646
647         /** Convert a string to lower case respecting RFC1459
648         * @param n A string to lowercase
649         */
650         void strlower(char *n);
651
652 END_HASHMAP_NAMESPACE
653
654 #endif