string_util_icu.cc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2016 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "device/bluetooth/string_util_icu.h"
  5. #include <memory>
  6. #include "base/memory/singleton.h"
  7. #include "base/strings/string_util.h"
  8. #include "third_party/icu/source/common/unicode/uniset.h"
  9. namespace device {
  10. namespace {
  11. class GraphicCharacters {
  12. public:
  13. static GraphicCharacters* GetInstance() {
  14. return base::Singleton<GraphicCharacters, base::LeakySingletonTraits<
  15. GraphicCharacters>>::get();
  16. }
  17. GraphicCharacters(const GraphicCharacters&) = delete;
  18. GraphicCharacters& operator=(const GraphicCharacters&) = delete;
  19. bool HasGraphicCharacter(base::StringPiece s) {
  20. int32_t length = graphic_->spanUTF8(
  21. s.data(), s.size(), USetSpanCondition::USET_SPAN_NOT_CONTAINED);
  22. return static_cast<size_t>(length) != s.size();
  23. }
  24. private:
  25. friend struct base::DefaultSingletonTraits<GraphicCharacters>;
  26. GraphicCharacters();
  27. // set of graphic characters.
  28. std::unique_ptr<icu::UnicodeSet> graphic_;
  29. };
  30. GraphicCharacters::GraphicCharacters() {
  31. UErrorCode graphic_status = U_ZERO_ERROR;
  32. // The set of Unicode Graphic Characters as defined by
  33. // http://www.unicode.org/reports/tr18/#graph
  34. // This set is composed of the characters not included in the following
  35. // sets:
  36. // - Whitespace (WSpace)
  37. // - gc=Control (Cc)
  38. // - gc=Surrogate (Cs)
  39. // - gc=Unassigned (Cn)
  40. graphic_ = std::make_unique<icu::UnicodeSet>(
  41. UNICODE_STRING_SIMPLE("[:graph:]"), graphic_status);
  42. DCHECK(U_SUCCESS(graphic_status));
  43. graphic_->freeze();
  44. }
  45. } // namespace
  46. bool HasGraphicCharacter(base::StringPiece s) {
  47. DCHECK(base::IsStringUTF8(s));
  48. return GraphicCharacters::GetInstance()->HasGraphicCharacter(s);
  49. }
  50. } // namespace device