char_traits.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_STRINGS_CHAR_TRAITS_H_
  5. #define BASE_STRINGS_CHAR_TRAITS_H_
  6. #include <stddef.h>
  7. #include "base/compiler_specific.h"
  8. namespace base {
  9. // constexpr version of http://en.cppreference.com/w/cpp/string/char_traits.
  10. // This currently just implements the bits needed to support a (mostly)
  11. // constexpr StringPiece.
  12. //
  13. // TODO(dcheng): Once we switch to C++17, most methods will become constexpr and
  14. // we can switch over to using the one in the standard library.
  15. template <typename T>
  16. struct CharTraits {
  17. // Performs a lexographical comparison of the first N characters of |s1| and
  18. // |s2|. Returns 0 if equal, -1 if |s1| is less than |s2|, and 1 if |s1| is
  19. // greater than |s2|.
  20. static constexpr int compare(const T* s1, const T* s2, size_t n) noexcept;
  21. // Returns the length of |s|, assuming null termination (and not including the
  22. // terminating null).
  23. static constexpr size_t length(const T* s) noexcept;
  24. };
  25. template <typename T>
  26. constexpr int CharTraits<T>::compare(const T* s1,
  27. const T* s2,
  28. size_t n) noexcept {
  29. for (; n; --n, ++s1, ++s2) {
  30. if (*s1 < *s2)
  31. return -1;
  32. if (*s1 > *s2)
  33. return 1;
  34. }
  35. return 0;
  36. }
  37. template <typename T>
  38. constexpr size_t CharTraits<T>::length(const T* s) noexcept {
  39. size_t i = 0;
  40. for (; *s; ++s)
  41. ++i;
  42. return i;
  43. }
  44. // char specialization of CharTraits that can use clang's constexpr instrinsics,
  45. // where available.
  46. template <>
  47. struct CharTraits<char> {
  48. static constexpr int compare(const char* s1,
  49. const char* s2,
  50. size_t n) noexcept;
  51. static constexpr size_t length(const char* s) noexcept;
  52. };
  53. constexpr int CharTraits<char>::compare(const char* s1,
  54. const char* s2,
  55. size_t n) noexcept {
  56. #if HAS_FEATURE(cxx_constexpr_string_builtins)
  57. return __builtin_memcmp(s1, s2, n);
  58. #else
  59. for (; n; --n, ++s1, ++s2) {
  60. if (*s1 < *s2)
  61. return -1;
  62. if (*s1 > *s2)
  63. return 1;
  64. }
  65. return 0;
  66. #endif
  67. }
  68. constexpr size_t CharTraits<char>::length(const char* s) noexcept {
  69. #if defined(__clang__)
  70. return __builtin_strlen(s);
  71. #else
  72. size_t i = 0;
  73. for (; *s; ++s)
  74. ++i;
  75. return i;
  76. #endif
  77. }
  78. } // namespace base
  79. #endif // BASE_STRINGS_CHAR_TRAITS_H_