OLD | NEW |
1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 // | 4 // |
5 // This file defines utility functions for working with strings. | 5 // This file defines utility functions for working with strings. |
6 | 6 |
7 #ifndef BASE_STRING_UTIL_H_ | 7 #ifndef BASE_STRING_UTIL_H_ |
8 #define BASE_STRING_UTIL_H_ | 8 #define BASE_STRING_UTIL_H_ |
9 | 9 |
| 10 #include <string> |
10 #include <string.h> | 11 #include <string.h> |
11 | 12 |
12 namespace base { | 13 namespace base { |
13 | 14 |
| 15 #ifdef WIN32 |
14 // Compare the two strings s1 and s2 without regard to case using | 16 // Compare the two strings s1 and s2 without regard to case using |
15 // the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if | 17 // the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if |
16 // s2 > s1 according to a lexicographic comparison. | 18 // s2 > s1 according to a lexicographic comparison. |
17 inline int strcasecmp(const char* s1, const char* s2) { | 19 inline int strcasecmp(const char* s1, const char* s2) { |
18 return _stricmp(s1, s2); | 20 return _stricmp(s1, s2); |
19 } | 21 } |
| 22 #else |
| 23 inline int strcasecmp(const char* s1, const char* s2) { |
| 24 return strcasecmp(s1, s2); |
| 25 } |
| 26 #endif |
| 27 |
| 28 // This is mpcomplete's pattern for saving a string copy when dealing with |
| 29 // a function that writes results into a wchar_t[] and wanting the result to |
| 30 // end up in a std::wstring. It ensures that the std::wstring's internal |
| 31 // buffer has enough room to store the characters to be written into it, and |
| 32 // sets its .length() attribute to the right value. |
| 33 // |
| 34 // The reserve() call allocates the memory required to hold the string |
| 35 // plus a terminating null. This is done because resize() isn't |
| 36 // guaranteed to reserve space for the null. The resize() call is |
| 37 // simply the only way to change the string's 'length' member. |
| 38 // |
| 39 // XXX-performance: the call to wide.resize() takes linear time, since it fills |
| 40 // the string's buffer with nulls. I call it to change the length of the |
| 41 // string (needed because writing directly to the buffer doesn't do this). |
| 42 // Perhaps there's a constant-time way to change the string's length. |
| 43 template <class string_type> |
| 44 inline typename string_type::value_type* WriteInto(string_type* str, |
| 45 size_t length_with_null) { |
| 46 str->reserve(length_with_null); |
| 47 str->resize(length_with_null - 1); |
| 48 return &((*str)[0]); |
| 49 } |
20 | 50 |
21 } | 51 } |
22 | 52 |
23 #endif // BASE_STRING_UTIL_H_ | 53 #endif // BASE_STRING_UTIL_H_ |
OLD | NEW |