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