fork(1) download
  1. #include <string>
  2. #include <cstring>
  3. #include <iostream>
  4.  
  5. bool validateUTF8(std::string const& _input, size_t& _invalidPosition)
  6. {
  7. const size_t length = _input.length();
  8. bool valid = true;
  9. size_t i = 0;
  10.  
  11. for (; i < length; i++)
  12. {
  13. if ((unsigned char)_input[i] < 0x80)
  14. continue;
  15.  
  16. size_t count = 0;
  17. switch(_input[i] & 0xe0) {
  18. case 0xc0: count = 1; break;
  19. case 0xe0: count = 2; break;
  20. case 0xf0: count = 3; break;
  21. default: break;
  22. }
  23.  
  24. if (count == 0)
  25. {
  26. valid = false;
  27. break;
  28. }
  29.  
  30. if ((i + count) >= length)
  31. {
  32. valid = false;
  33. break;
  34. }
  35.  
  36. for (size_t j = 0; j < count; j++)
  37. {
  38. i++;
  39. if ((_input[i] & 0xc0) != 0x80)
  40. {
  41. valid = false;
  42. break;
  43. }
  44. }
  45. }
  46.  
  47. if (valid)
  48. return true;
  49.  
  50. _invalidPosition = i;
  51. return false;
  52. }
  53.  
  54. int main() {
  55. const std::string input = "\xF0\x9F\xA6\x84";
  56. size_t position = 0;
  57.  
  58. bool ret = validateUTF8(input, position);
  59. std::cout << "Final Position:" << position << std::endl;
  60. std::cout << "OK:" << ret << std::endl;
  61.  
  62. return 0;
  63. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
Final Position:3
OK:0