1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
31//
32// The Google C++ Testing Framework (Google Test)
33//
34// This header file declares the String class and functions used internally by
35// Google Test.  They are subject to change without notice. They should not used
36// by code external to Google Test.
37//
38// This header file is #included by <gtest/internal/gtest-internal.h>.
39// It should not be #included by other files.
40
41#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
42#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
43
44#include <string.h>
45#include <gtest/internal/gtest-port.h>
46
47#if GTEST_HAS_GLOBAL_STRING || GTEST_HAS_STD_STRING
48#include <string>
49#endif  // GTEST_HAS_GLOBAL_STRING || GTEST_HAS_STD_STRING
50
51namespace testing {
52namespace internal {
53
54// String - a UTF-8 string class.
55//
56// We cannot use std::string as Microsoft's STL implementation in
57// Visual C++ 7.1 has problems when exception is disabled.  There is a
58// hack to work around this, but we've seen cases where the hack fails
59// to work.
60//
61// Also, String is different from std::string in that it can represent
62// both NULL and the empty string, while std::string cannot represent
63// NULL.
64//
65// NULL and the empty string are considered different.  NULL is less
66// than anything (including the empty string) except itself.
67//
68// This class only provides minimum functionality necessary for
69// implementing Google Test.  We do not intend to implement a full-fledged
70// string class here.
71//
72// Since the purpose of this class is to provide a substitute for
73// std::string on platforms where it cannot be used, we define a copy
74// constructor and assignment operators such that we don't need
75// conditional compilation in a lot of places.
76//
77// In order to make the representation efficient, the d'tor of String
78// is not virtual.  Therefore DO NOT INHERIT FROM String.
79class String {
80 public:
81  // Static utility methods
82
83  // Returns the input enclosed in double quotes if it's not NULL;
84  // otherwise returns "(null)".  For example, "\"Hello\"" is returned
85  // for input "Hello".
86  //
87  // This is useful for printing a C string in the syntax of a literal.
88  //
89  // Known issue: escape sequences are not handled yet.
90  static String ShowCStringQuoted(const char* c_str);
91
92  // Clones a 0-terminated C string, allocating memory using new.  The
93  // caller is responsible for deleting the return value using
94  // delete[].  Returns the cloned string, or NULL if the input is
95  // NULL.
96  //
97  // This is different from strdup() in string.h, which allocates
98  // memory using malloc().
99  static const char* CloneCString(const char* c_str);
100
101#if GTEST_OS_WINDOWS_MOBILE
102  // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
103  // able to pass strings to Win32 APIs on CE we need to convert them
104  // to 'Unicode', UTF-16.
105
106  // Creates a UTF-16 wide string from the given ANSI string, allocating
107  // memory using new. The caller is responsible for deleting the return
108  // value using delete[]. Returns the wide string, or NULL if the
109  // input is NULL.
110  //
111  // The wide string is created using the ANSI codepage (CP_ACP) to
112  // match the behaviour of the ANSI versions of Win32 calls and the
113  // C runtime.
114  static LPCWSTR AnsiToUtf16(const char* c_str);
115
116  // Creates an ANSI string from the given wide string, allocating
117  // memory using new. The caller is responsible for deleting the return
118  // value using delete[]. Returns the ANSI string, or NULL if the
119  // input is NULL.
120  //
121  // The returned string is created using the ANSI codepage (CP_ACP) to
122  // match the behaviour of the ANSI versions of Win32 calls and the
123  // C runtime.
124  static const char* Utf16ToAnsi(LPCWSTR utf16_str);
125#endif
126
127  // Compares two C strings.  Returns true iff they have the same content.
128  //
129  // Unlike strcmp(), this function can handle NULL argument(s).  A
130  // NULL C string is considered different to any non-NULL C string,
131  // including the empty string.
132  static bool CStringEquals(const char* lhs, const char* rhs);
133
134  // Converts a wide C string to a String using the UTF-8 encoding.
135  // NULL will be converted to "(null)".  If an error occurred during
136  // the conversion, "(failed to convert from wide string)" is
137  // returned.
138  static String ShowWideCString(const wchar_t* wide_c_str);
139
140  // Similar to ShowWideCString(), except that this function encloses
141  // the converted string in double quotes.
142  static String ShowWideCStringQuoted(const wchar_t* wide_c_str);
143
144  // Compares two wide C strings.  Returns true iff they have the same
145  // content.
146  //
147  // Unlike wcscmp(), this function can handle NULL argument(s).  A
148  // NULL C string is considered different to any non-NULL C string,
149  // including the empty string.
150  static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
151
152  // Compares two C strings, ignoring case.  Returns true iff they
153  // have the same content.
154  //
155  // Unlike strcasecmp(), this function can handle NULL argument(s).
156  // A NULL C string is considered different to any non-NULL C string,
157  // including the empty string.
158  static bool CaseInsensitiveCStringEquals(const char* lhs,
159                                           const char* rhs);
160
161  // Compares two wide C strings, ignoring case.  Returns true iff they
162  // have the same content.
163  //
164  // Unlike wcscasecmp(), this function can handle NULL argument(s).
165  // A NULL C string is considered different to any non-NULL wide C string,
166  // including the empty string.
167  // NB: The implementations on different platforms slightly differ.
168  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
169  // environment variable. On GNU platform this method uses wcscasecmp
170  // which compares according to LC_CTYPE category of the current locale.
171  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
172  // current locale.
173  static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
174                                               const wchar_t* rhs);
175
176  // Formats a list of arguments to a String, using the same format
177  // spec string as for printf.
178  //
179  // We do not use the StringPrintf class as it is not universally
180  // available.
181  //
182  // The result is limited to 4096 characters (including the tailing
183  // 0).  If 4096 characters are not enough to format the input,
184  // "<buffer exceeded>" is returned.
185  static String Format(const char* format, ...);
186
187  // C'tors
188
189  // The default c'tor constructs a NULL string.
190  String() : c_str_(NULL), length_(0) {}
191
192  // Constructs a String by cloning a 0-terminated C string.
193  String(const char* c_str) {  // NOLINT
194    if (c_str == NULL) {
195      c_str_ = NULL;
196      length_ = 0;
197    } else {
198      ConstructNonNull(c_str, strlen(c_str));
199    }
200  }
201
202  // Constructs a String by copying a given number of chars from a
203  // buffer.  E.g. String("hello", 3) creates the string "hel",
204  // String("a\0bcd", 4) creates "a\0bc", String(NULL, 0) creates "",
205  // and String(NULL, 1) results in access violation.
206  String(const char* buffer, size_t length) {
207    ConstructNonNull(buffer, length);
208  }
209
210  // The copy c'tor creates a new copy of the string.  The two
211  // String objects do not share content.
212  String(const String& str) : c_str_(NULL), length_(0) { *this = str; }
213
214  // D'tor.  String is intended to be a final class, so the d'tor
215  // doesn't need to be virtual.
216  ~String() { delete[] c_str_; }
217
218  // Allows a String to be implicitly converted to an ::std::string or
219  // ::string, and vice versa.  Converting a String containing a NULL
220  // pointer to ::std::string or ::string is undefined behavior.
221  // Converting a ::std::string or ::string containing an embedded NUL
222  // character to a String will result in the prefix up to the first
223  // NUL character.
224#if GTEST_HAS_STD_STRING
225  String(const ::std::string& str) {
226    ConstructNonNull(str.c_str(), str.length());
227  }
228
229  operator ::std::string() const { return ::std::string(c_str(), length()); }
230#endif  // GTEST_HAS_STD_STRING
231
232#if GTEST_HAS_GLOBAL_STRING
233  String(const ::string& str) {
234    ConstructNonNull(str.c_str(), str.length());
235  }
236
237  operator ::string() const { return ::string(c_str(), length()); }
238#endif  // GTEST_HAS_GLOBAL_STRING
239
240  // Returns true iff this is an empty string (i.e. "").
241  bool empty() const { return (c_str() != NULL) && (length() == 0); }
242
243  // Compares this with another String.
244  // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
245  // if this is greater than rhs.
246  int Compare(const String& rhs) const;
247
248  // Returns true iff this String equals the given C string.  A NULL
249  // string and a non-NULL string are considered not equal.
250  bool operator==(const char* c_str) const { return Compare(c_str) == 0; }
251
252  // Returns true iff this String is less than the given String.  A
253  // NULL string is considered less than "".
254  bool operator<(const String& rhs) const { return Compare(rhs) < 0; }
255
256  // Returns true iff this String doesn't equal the given C string.  A NULL
257  // string and a non-NULL string are considered not equal.
258  bool operator!=(const char* c_str) const { return !(*this == c_str); }
259
260  // Returns true iff this String ends with the given suffix.  *Any*
261  // String is considered to end with a NULL or empty suffix.
262  bool EndsWith(const char* suffix) const;
263
264  // Returns true iff this String ends with the given suffix, not considering
265  // case. Any String is considered to end with a NULL or empty suffix.
266  bool EndsWithCaseInsensitive(const char* suffix) const;
267
268  // Returns the length of the encapsulated string, or 0 if the
269  // string is NULL.
270  size_t length() const { return length_; }
271
272  // Gets the 0-terminated C string this String object represents.
273  // The String object still owns the string.  Therefore the caller
274  // should NOT delete the return value.
275  const char* c_str() const { return c_str_; }
276
277  // Assigns a C string to this object.  Self-assignment works.
278  const String& operator=(const char* c_str) { return *this = String(c_str); }
279
280  // Assigns a String object to this object.  Self-assignment works.
281  const String& operator=(const String& rhs) {
282    if (this != &rhs) {
283      delete[] c_str_;
284      if (rhs.c_str() == NULL) {
285        c_str_ = NULL;
286        length_ = 0;
287      } else {
288        ConstructNonNull(rhs.c_str(), rhs.length());
289      }
290    }
291
292    return *this;
293  }
294
295 private:
296  // Constructs a non-NULL String from the given content.  This
297  // function can only be called when data_ has not been allocated.
298  // ConstructNonNull(NULL, 0) results in an empty string ("").
299  // ConstructNonNull(NULL, non_zero) is undefined behavior.
300  void ConstructNonNull(const char* buffer, size_t length) {
301    char* const str = new char[length + 1];
302    memcpy(str, buffer, length);
303    str[length] = '\0';
304    c_str_ = str;
305    length_ = length;
306  }
307
308  const char* c_str_;
309  size_t length_;
310};  // class String
311
312// Streams a String to an ostream.  Each '\0' character in the String
313// is replaced with "\\0".
314inline ::std::ostream& operator<<(::std::ostream& os, const String& str) {
315  if (str.c_str() == NULL) {
316    os << "(null)";
317  } else {
318    const char* const c_str = str.c_str();
319    for (size_t i = 0; i != str.length(); i++) {
320      if (c_str[i] == '\0') {
321        os << "\\0";
322      } else {
323        os << c_str[i];
324      }
325    }
326  }
327  return os;
328}
329
330// Gets the content of the StrStream's buffer as a String.  Each '\0'
331// character in the buffer is replaced with "\\0".
332String StrStreamToString(StrStream* stream);
333
334// Converts a streamable value to a String.  A NULL pointer is
335// converted to "(null)".  When the input value is a ::string,
336// ::std::string, ::wstring, or ::std::wstring object, each NUL
337// character in it is replaced with "\\0".
338
339// Declared here but defined in gtest.h, so that it has access
340// to the definition of the Message class, required by the ARM
341// compiler.
342template <typename T>
343String StreamableToString(const T& streamable);
344
345}  // namespace internal
346}  // namespace testing
347
348#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
349