strfunc.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Tencent is pleased to support the open source community by making RapidJSON
  2. // available.
  3. //
  4. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All
  5. // rights reserved.
  6. //
  7. // Licensed under the MIT License (the "License"); you may not use this file
  8. // except in compliance with the License. You may obtain a copy of the License
  9. // at
  10. //
  11. // http://opensource.org/licenses/MIT
  12. //
  13. // Unless required by applicable law or agreed to in writing, software
  14. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  16. // License for the specific language governing permissions and limitations under
  17. // the License.
  18. #ifndef RAPIDJSON_INTERNAL_STRFUNC_H_
  19. #define RAPIDJSON_INTERNAL_STRFUNC_H_
  20. #include <cwchar>
  21. #include "../stream.h"
  22. RAPIDJSON_NAMESPACE_BEGIN
  23. namespace internal {
  24. //! Custom strlen() which works on different character types.
  25. /*! \tparam Ch Character type (e.g. char, wchar_t, short)
  26. \param s Null-terminated input string.
  27. \return Number of characters in the string.
  28. \note This has the same semantics as strlen(), the return value is not
  29. number of Unicode codepoints.
  30. */
  31. template <typename Ch>
  32. inline SizeType StrLen(const Ch *s) {
  33. RAPIDJSON_ASSERT(s != 0);
  34. const Ch *p = s;
  35. while (*p) ++p;
  36. return SizeType(p - s);
  37. }
  38. template <>
  39. inline SizeType StrLen(const char *s) {
  40. return SizeType(std::strlen(s));
  41. }
  42. template <>
  43. inline SizeType StrLen(const wchar_t *s) {
  44. return SizeType(std::wcslen(s));
  45. }
  46. //! Returns number of code points in a encoded string.
  47. template <typename Encoding>
  48. bool CountStringCodePoint(const typename Encoding::Ch *s, SizeType length,
  49. SizeType *outCount) {
  50. RAPIDJSON_ASSERT(s != 0);
  51. RAPIDJSON_ASSERT(outCount != 0);
  52. GenericStringStream<Encoding> is(s);
  53. const typename Encoding::Ch *end = s + length;
  54. SizeType count = 0;
  55. while (is.src_ < end) {
  56. unsigned codepoint;
  57. if (!Encoding::Decode(is, &codepoint)) return false;
  58. count++;
  59. }
  60. *outCount = count;
  61. return true;
  62. }
  63. } // namespace internal
  64. RAPIDJSON_NAMESPACE_END
  65. #endif // RAPIDJSON_INTERNAL_STRFUNC_H_