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