utf8_checker.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #ifndef BOOST_BEAST_WEBSOCKET_DETAIL_UTF8_CHECKER_HPP
  10. #define BOOST_BEAST_WEBSOCKET_DETAIL_UTF8_CHECKER_HPP
  11. #include <boost/beast/core/buffers_range.hpp>
  12. #include <boost/asio/buffer.hpp>
  13. #include <cstdint>
  14. namespace boost {
  15. namespace beast {
  16. namespace websocket {
  17. namespace detail {
  18. /** A UTF8 validator.
  19. This validator can be used to check if a buffer containing UTF8 text is
  20. valid. The write function may be called incrementally with segmented UTF8
  21. sequences. The finish function determines if all processed text is valid.
  22. */
  23. class utf8_checker
  24. {
  25. std::size_t need_ = 0; // chars we need to finish the code point
  26. std::uint8_t* p_ = cp_; // current position in temp buffer
  27. std::uint8_t cp_[4]; // a temp buffer for the code point
  28. public:
  29. /** Prepare to process text as valid utf8
  30. */
  31. BOOST_BEAST_DECL
  32. void
  33. reset();
  34. /** Check that all processed text is valid utf8
  35. */
  36. BOOST_BEAST_DECL
  37. bool
  38. finish();
  39. /** Check if text is valid UTF8
  40. @return `true` if the text is valid utf8 or false otherwise.
  41. */
  42. BOOST_BEAST_DECL
  43. bool
  44. write(std::uint8_t const* in, std::size_t size);
  45. /** Check if text is valid UTF8
  46. @return `true` if the text is valid utf8 or false otherwise.
  47. */
  48. template<class ConstBufferSequence>
  49. bool
  50. write(ConstBufferSequence const& bs);
  51. };
  52. template<class ConstBufferSequence>
  53. bool
  54. utf8_checker::
  55. write(ConstBufferSequence const& buffers)
  56. {
  57. static_assert(
  58. net::is_const_buffer_sequence<ConstBufferSequence>::value,
  59. "ConstBufferSequence type requirements not met");
  60. for(auto b : beast::buffers_range_ref(buffers))
  61. if(! write(static_cast<
  62. std::uint8_t const*>(b.data()),
  63. b.size()))
  64. return false;
  65. return true;
  66. }
  67. BOOST_BEAST_DECL
  68. bool
  69. check_utf8(char const* p, std::size_t n);
  70. } // detail
  71. } // websocket
  72. } // beast
  73. } // boost
  74. #if BOOST_BEAST_HEADER_ONLY
  75. #include <boost/beast/websocket/detail/utf8_checker.ipp>
  76. #endif
  77. #endif