Skip to content
Repos

DevPlaceApp

C++ 601 B24 lines Opens in site

Directory Raw Download

#include "core/TextCount.hpp"

namespace dp {

int TextCount::utf16(const std::string& s) {
  int n = 0;
  for (std::size_t i = 0; i < s.size();) {
    const unsigned char c = static_cast<unsigned char>(s[i]);
    if (c < 0x80) { n += 1; i += 1; }
    else if ((c >> 5) == 0x6) { n += 1; i += 2; }
    else if ((c >> 4) == 0xE) { n += 1; i += 3; }
    else if ((c >> 3) == 0x1E) { n += 2; i += 4; }
    else { n += 1; i += 1; }
  }
  return n;
}

int TextCount::codepoints(const std::string& s) {
  int n = 0;
  for (unsigned char c : s) if ((c & 0xC0) != 0x80) ++n;
  return n;
}

}  // namespace dp
15.7ms