strfunc.h 2.1 KB

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