bounded_utf8_length_sequence.h 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. // Copyright 2024 The Abseil Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef ABSL_DEBUGGING_INTERNAL_BOUNDED_UTF8_LENGTH_SEQUENCE_H_
  15. #define ABSL_DEBUGGING_INTERNAL_BOUNDED_UTF8_LENGTH_SEQUENCE_H_
  16. #include <cstdint>
  17. #include "absl/base/config.h"
  18. #include "absl/numeric/bits.h"
  19. namespace absl {
  20. ABSL_NAMESPACE_BEGIN
  21. namespace debugging_internal {
  22. // A sequence of up to max_elements integers between 1 and 4 inclusive, whose
  23. // insertion operation computes the sum of all the elements before the insertion
  24. // point. This is useful in decoding Punycode, where one needs to know where in
  25. // a UTF-8 byte stream the n-th code point begins.
  26. //
  27. // BoundedUtf8LengthSequence is async-signal-safe and suitable for use in
  28. // symbolizing stack traces in a signal handler, provided max_elements is not
  29. // improvidently large. For inputs of lengths accepted by the Rust demangler,
  30. // up to a couple hundred code points, InsertAndReturnSumOfPredecessors should
  31. // run in a few dozen clock cycles, on par with the other arithmetic required
  32. // for Punycode decoding.
  33. template <uint32_t max_elements>
  34. class BoundedUtf8LengthSequence {
  35. public:
  36. // Constructs an empty sequence.
  37. BoundedUtf8LengthSequence() = default;
  38. // Inserts `utf_length` at position `index`, shifting any existing elements at
  39. // or beyond `index` one position to the right. If the sequence is already
  40. // full, the rightmost element is discarded.
  41. //
  42. // Returns the sum of the elements at positions 0 to `index - 1` inclusive.
  43. // If `index` is greater than the number of elements already inserted, the
  44. // excess positions in the range count 1 apiece.
  45. //
  46. // REQUIRES: index < max_elements and 1 <= utf8_length <= 4.
  47. uint32_t InsertAndReturnSumOfPredecessors(
  48. uint32_t index, uint32_t utf8_length) {
  49. // The caller shouldn't pass out-of-bounds inputs, but if it does happen,
  50. // clamp the values and try to continue. If we're being called from a
  51. // signal handler, the last thing we want to do is crash. Emitting
  52. // malformed UTF-8 is a lesser evil.
  53. if (index >= max_elements) index = max_elements - 1;
  54. if (utf8_length == 0 || utf8_length > 4) utf8_length = 1;
  55. const uint32_t word_index = index/32;
  56. const uint32_t bit_index = 2 * (index % 32);
  57. const uint64_t ones_bit = uint64_t{1} << bit_index;
  58. // Compute the sum of predecessors.
  59. // - Each value from 1 to 4 is represented by a bit field with value from
  60. // 0 to 3, so the desired sum is index plus the sum of the
  61. // representations actually stored.
  62. // - For each bit field, a set low bit should contribute 1 to the sum, and
  63. // a set high bit should contribute 2.
  64. // - Another way to say the same thing is that each set bit contributes 1,
  65. // and each set high bit contributes an additional 1.
  66. // - So the sum we want is index + popcount(everything) + popcount(bits in
  67. // odd positions).
  68. const uint64_t odd_bits_mask = 0xaaaaaaaaaaaaaaaa;
  69. const uint64_t lower_seminibbles_mask = ones_bit - 1;
  70. const uint64_t higher_seminibbles_mask = ~lower_seminibbles_mask;
  71. const uint64_t same_word_bits_below_insertion =
  72. rep_[word_index] & lower_seminibbles_mask;
  73. int full_popcount = absl::popcount(same_word_bits_below_insertion);
  74. int odd_popcount =
  75. absl::popcount(same_word_bits_below_insertion & odd_bits_mask);
  76. for (uint32_t j = word_index; j > 0; --j) {
  77. const uint64_t word_below_insertion = rep_[j - 1];
  78. full_popcount += absl::popcount(word_below_insertion);
  79. odd_popcount += absl::popcount(word_below_insertion & odd_bits_mask);
  80. }
  81. const uint32_t sum_of_predecessors =
  82. index + static_cast<uint32_t>(full_popcount + odd_popcount);
  83. // Now insert utf8_length's representation, shifting successors up one
  84. // place.
  85. for (uint32_t j = max_elements/32 - 1; j > word_index; --j) {
  86. rep_[j] = (rep_[j] << 2) | (rep_[j - 1] >> 62);
  87. }
  88. rep_[word_index] =
  89. (rep_[word_index] & lower_seminibbles_mask) |
  90. (uint64_t{utf8_length - 1} << bit_index) |
  91. ((rep_[word_index] & higher_seminibbles_mask) << 2);
  92. return sum_of_predecessors;
  93. }
  94. private:
  95. // If the (32 * i + j)-th element of the represented sequence has the value k
  96. // (0 <= j < 32, 1 <= k <= 4), then bits 2 * j and 2 * j + 1 of rep_[i]
  97. // contain the seminibble (k - 1).
  98. //
  99. // In particular, the zero-initialization of rep_ makes positions not holding
  100. // any inserted element count as 1 in InsertAndReturnSumOfPredecessors.
  101. //
  102. // Example: rep_ = {0xb1, ... the rest zeroes ...} represents the sequence
  103. // (2, 1, 4, 3, ... the rest 1's ...). Constructing the sequence of Unicode
  104. // code points "Àa🂻中" = {U+00C0, U+0061, U+1F0BB, U+4E2D} (among many
  105. // other examples) would yield this value of rep_.
  106. static_assert(max_elements > 0 && max_elements % 32 == 0,
  107. "max_elements must be a positive multiple of 32");
  108. uint64_t rep_[max_elements/32] = {};
  109. };
  110. } // namespace debugging_internal
  111. ABSL_NAMESPACE_END
  112. } // namespace absl
  113. #endif // ABSL_DEBUGGING_INTERNAL_BOUNDED_UTF8_LENGTH_SEQUENCE_H_