MCPcopy Create free account
hub / github.com/pybind/pybind11 / utf8_remainder

Method utf8_remainder

include/pybind11/iostream.h:58–91  ·  view source on GitHub ↗

Computes how many bytes at the end of the buffer are part of an incomplete sequence of UTF-8 bytes. Precondition: pbase() < pptr()

Source from the content-addressed store, hash-verified

56 // incomplete sequence of UTF-8 bytes.
57 // Precondition: pbase() < pptr()
58 size_t utf8_remainder() const {
59 const auto rbase = std::reverse_iterator<char *>(pbase());
60 const auto rpptr = std::reverse_iterator<char *>(pptr());
61 auto is_ascii = [](char c) { return (static_cast<unsigned char>(c) & 0x80) == 0x00; };
62 auto is_leading = [](char c) { return (static_cast<unsigned char>(c) & 0xC0) == 0xC0; };
63 auto is_leading_2b = [](char c) { return static_cast<unsigned char>(c) <= 0xDF; };
64 auto is_leading_3b = [](char c) { return static_cast<unsigned char>(c) <= 0xEF; };
65 // If the last character is ASCII, there are no incomplete code points
66 if (is_ascii(*rpptr)) {
67 return 0;
68 }
69 // Otherwise, work back from the end of the buffer and find the first
70 // UTF-8 leading byte
71 const auto rpend = rbase - rpptr >= 3 ? rpptr + 3 : rbase;
72 const auto leading = std::find_if(rpptr, rpend, is_leading);
73 if (leading == rbase) {
74 return 0;
75 }
76 const auto dist = static_cast<size_t>(leading - rpptr);
77 size_t remainder = 0;
78
79 if (dist == 0) {
80 remainder = 1; // 1-byte code point is impossible
81 } else if (dist == 1) {
82 remainder = is_leading_2b(*leading) ? 0 : dist + 1;
83 } else if (dist == 2) {
84 remainder = is_leading_3b(*leading) ? 0 : dist + 1;
85 }
86 // else if (dist >= 3), at least 4 bytes before encountering an UTF-8
87 // leading byte, either no remainder or invalid UTF-8.
88 // Invalid UTF-8 will cause an exception later when converting
89 // to a Python string, so that's not handled here.
90 return remainder;
91 }
92
93 // This function must be non-virtual to be called in a destructor.
94 int _sync() {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected