summaryrefslogtreecommitdiffstats
path: root/chrome/browser/sync/notifier/base/string.h
blob: 725cc66ad6eda1cd15a3fe750de19920f29631f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_SYNC_NOTIFIER_BASE_STRING_H_
#define CHROME_BROWSER_SYNC_NOTIFIER_BASE_STRING_H_

#ifdef COMPILER_MSVC
#include <xhash>
#elif defined(__GNUC__)
#include <ext/hash_map>
#endif

#include <ctype.h>
#include <string>

#include "chrome/browser/sync/notifier/base/fastalloc.h"
#include "talk/base/basictypes.h"

namespace notifier {

// Does html encoding of strings.
std::string HtmlEncode(const std::string& src);

// Does html decoding of strings.
std::string HtmlDecode(const std::string& src);

// Does utl encoding of strings.
std::string UrlEncode(const std::string& src);

// Does url decoding of strings.
std::string UrlDecode(const std::string& src);

// Convert a character to a digit
// if the character is not a digit return -1 (same as CRT)
inline int CharToDigit(char c) {
  return ((c) >= '0' && (c) <= '9' ? (c) - '0' : -1);
}

int CharToHexValue(char hex);

// ----------------------------------------------------------------------
// ParseStringToInt()
// ParseStringToUint()
// ParseStringToInt64()
// ParseStringToDouble()
//    Convert a string to an int/int64/double
//    If strict is true, check for the validity and overflow
// ----------------------------------------------------------------------

bool ParseStringToInt(const char* str, int* value, bool strict);

bool ParseStringToUint(const char* str, uint32* value, bool strict);

bool ParseStringToInt64(const char* str, int64* value, bool strict);

bool ParseStringToDouble(const char* str, double* value, bool strict);

// ----------------------------------------------------------------------
// StringToInt()
// StringToUint()
// StringToInt64()
// StringToDouble()
//    Convert a string to an int/int64/double
//    Note that these functions do not check for the validity or overflow
// ----------------------------------------------------------------------

int StringToInt(const char* str);

uint32 StringToUint(const char* str);

int64 StringToInt64(const char* str);

double StringToDouble(const char* str);

// ----------------------------------------------------------------------
// FloatToString()
// DoubleToString()
// IntToString()
// UIntToString()
// Int64ToString()
// UInt64ToString()
//    Convert various types to their string representation.  These
//    all do the obvious, trivial thing.
// ----------------------------------------------------------------------

std::string FloatToString(float f);
std::string DoubleToString(double d);

std::string IntToString(int i);
std::string UIntToString(uint32 i);

std::string Int64ToString(int64 i64);
std::string UInt64ToString(uint64 i64);

std::string Int64ToHexString(int64 i64);

// ----------------------------------------------------------------------
// StringStartsWith()
// StringEndsWith()
//    Check if a string starts or ends with a pattern
// ----------------------------------------------------------------------

inline bool StringStartsWith(const std::string& s, const char* p) {
  return s.find(p) == 0;
}

inline bool StringEndsWith(const std::string& s, const char* p) {
  return s.rfind(p) == (s.length() - strlen(p));
}

// ----------------------------------------------------------------------
// MakeStringEndWith()
//   If the string does not end with a pattern, make it end with it
// ----------------------------------------------------------------------

inline std::string MakeStringEndWith(const std::string& s, const char* p) {
  if (StringEndsWith(s, p)) {
    return s;
  } else {
    std::string ns(s);
    ns += p;
    return ns;
  }
}

// Convert a lower_case_string to LowerCaseString
std::string LowerWithUnderToPascalCase(const char* lower_with_under);

// Convert a PascalCaseString to pascal_case_string
std::string PascalCaseToLowerWithUnder(const char* pascal_case);

// ----------------------------------------------------------------------
// LowerString()
// LowerStringToBuf()
//    Convert the characters in "s" to lowercase.
//    Changes contents of "s".  LowerStringToBuf copies at most
//    "n" characters (including the terminating '\0')  from "s"
//    to another buffer.
// ----------------------------------------------------------------------

inline void LowerString(char* s) {
  for (; *s; ++s) {
    *s = tolower(*s);
  }
}

inline void LowerString(std::string* s) {
  std::string::iterator end = s->end();
  for (std::string::iterator i = s->begin(); i != end; ++i) {
    *i = tolower(*i);
  }
}

inline void LowerStringToBuf(const char* s, char* buf, int n) {
  for (int i = 0; i < n - 1; ++i) {
    char c = s[i];
    buf[i] = tolower(c);
    if (c == '\0') {
      return;
    }
  }
  buf[n - 1] = '\0';
}

// ----------------------------------------------------------------------
// UpperString()
// UpperStringToBuf()
//    Convert the characters in "s" to uppercase.
//    UpperString changes "s". UpperStringToBuf copies at most
//    "n" characters (including the terminating '\0')  from "s"
//    to another buffer.
// ----------------------------------------------------------------------

inline void UpperString(char* s) {
  for (; *s; ++s) {
    *s = toupper(*s);
  }
}

inline void UpperString(std::string* s) {
  for (std::string::iterator iter = s->begin(); iter != s->end(); ++iter) {
    *iter = toupper(*iter);
  }
}

inline void UpperStringToBuf(const char* s, char* buf, int n) {
  for (int i = 0; i < n - 1; ++i) {
    char c = s[i];
    buf[i] = toupper(c);
    if (c == '\0') {
      return;
    }
  }
  buf[n - 1] = '\0';
}

// ----------------------------------------------------------------------
// TrimStringLeft
//    Removes any occurrences of the characters in 'remove' from the start
//    of the string.  Returns the number of chars trimmed.
// ----------------------------------------------------------------------
inline int TrimStringLeft(std::string* s, const char* remove) {
  int i = 0;
  for (; i < static_cast<int>(s->size()) && strchr(remove, (*s)[i]); ++i);
  if (i > 0) s->erase(0, i);
  return i;
}

// ----------------------------------------------------------------------
// TrimStringRight
//    Removes any occurrences of the characters in 'remove' from the end
//    of the string.  Returns the number of chars trimmed.
// ----------------------------------------------------------------------
inline int TrimStringRight(std::string* s, const char* remove) {
  int size = static_cast<int>(s->size());
  int i = size;
  for (; i > 0 && strchr(remove, (*s)[i - 1]); --i);
  if (i < size) {
    s->erase(i);
  }
  return size - i;
}

// ----------------------------------------------------------------------
// TrimString
//    Removes any occurrences of the characters in 'remove' from either
//    end of the string.
// ----------------------------------------------------------------------
inline int TrimString(std::string* s, const char* remove) {
  return TrimStringRight(s, remove) + TrimStringLeft(s, remove);
}

// ----------------------------------------------------------------------
// StringReplace()
//    Replace the "old" pattern with the "new" pattern in a string.  If
//    replace_all is false, it only replaces the first instance of "old."
// ----------------------------------------------------------------------

void StringReplace(std::string* s,
                   const char* old_sub,
                   const char* new_sub,
                   bool replace_all);

inline size_t HashString(const std::string &value) {
#ifdef COMPILER_MSVC
  return stdext::hash_value(value);
#elif defined(__GNUC__)
  __gnu_cxx::hash<const char*> h;
  return h(value.c_str());
#else
  // Compile time error because we don't return a value
#endif
}

// ----------------------------------------------------------------------
// SplitOneStringToken()
//   Parse a single "delim" delimited string from "*source"
//   Modify *source to point after the delimiter.
//   If no delimiter is present after the string, set *source to NULL.
//
//   If the start of *source is a delimiter, return an empty string.
//   If *source is NULL, return an empty string.
// ----------------------------------------------------------------------
std::string SplitOneStringToken(const char** source, const char* delim);

//----------------------------------------------------------------------
// CharTraits provides wrappers with common function names for char/wchar_t
// specific CRT functions
//----------------------------------------------------------------------

template <class CharT> struct CharTraits {
};

template <>
struct CharTraits<char> {
  static inline size_t length(const char* s) {
    return strlen(s);
  }
  static inline bool copy(char* dst, size_t dst_size, const char* s) {
    if (s == NULL || dst == NULL)
      return false;
    else
      return copy_num(dst, dst_size, s, strlen(s));
  }
  static inline bool copy_num(char* dst, size_t dst_size, const char* s,
                              size_t s_len) {
    if (dst_size < (s_len + 1))
      return false;
    memcpy(dst, s, s_len);
    dst[s_len] = '\0';
    return true;
  }
};

template <>
struct CharTraits<wchar_t> {
  static inline size_t length(const wchar_t* s) {
    return wcslen(s);
  }
  static inline bool copy(wchar_t* dst, size_t dst_size, const wchar_t* s) {
    if (s == NULL || dst == NULL)
      return false;
    else
      return copy_num(dst, dst_size, s, wcslen(s));
  }
  static inline bool copy_num(wchar_t* dst, size_t dst_size, const wchar_t* s,
                              size_t s_len) {
    if (dst_size < (s_len + 1)) {
      return false;
    }
    memcpy(dst, s, s_len * sizeof(wchar_t));
    dst[s_len] = '\0';
    return true;
  }
};

//----------------------------------------------------------------------
// This class manages a fixed-size, null-terminated string buffer.  It is
// meant to be allocated on the stack, and it makes no use of the heap
// internally. In most cases you'll just want to use a std::(w)string, but
// when you need to avoid the heap, you can use this class instead.
//
// Methods are provided to read the null-terminated buffer and to append
// data to the buffer, and once the buffer fills-up, it simply discards any
// extra append calls.
//----------------------------------------------------------------------

template <class CharT, int MaxSize>
class FixedString {
 public:
  typedef CharTraits<CharT> char_traits;

  FixedString() : index_(0), truncated_(false) {
    buf_[0] = CharT(0);
  }

  ~FixedString() {
    memset(buf_, 0xCC, sizeof(buf_));
  }

  // Returns true if the Append ever failed.
  bool was_truncated() const { return truncated_; }

  // Returns the number of characters in the string, excluding the null
  // terminator.
  size_t size() const { return index_; }

  // Returns the null-terminated string.
  const CharT* get() const { return buf_; }
  CharT* get() { return buf_; }

  // Append an array of characters.  The operation is bounds checked, and if
  // there is insufficient room, then the was_truncated() flag is set to true.
  void Append(const CharT* s, size_t n) {
    if (char_traits::copy_num(buf_ + index_, arraysize(buf_) - index_, s, n)) {
      index_ += n;
    } else {
      truncated_ = true;
    }
  }

  // Append a null-terminated string.
  void Append(const CharT* s) {
    Append(s, char_traits::length(s));
  }

  // Append a single character.
  void Append(CharT c) {
    Append(&c, 1);
  }

 private:
  CharT buf_[MaxSize];
  size_t index_;
  bool truncated_;
};

}  // namespace notifier

#endif  // CHROME_BROWSER_SYNC_NOTIFIER_BASE_STRING_H_