unistrappender.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. ******************************************************************************
  5. * Copyright (C) 2015, International Business Machines Corporation and
  6. * others. All Rights Reserved.
  7. ******************************************************************************
  8. *
  9. * File unistrappender.h
  10. ******************************************************************************
  11. */
  12. #ifndef __UNISTRAPPENDER_H__
  13. #define __UNISTRAPPENDER_H__
  14. #include "unicode/unistr.h"
  15. #include "unicode/uobject.h"
  16. #include "unicode/utf16.h"
  17. #include "unicode/utypes.h"
  18. #include "cmemory.h"
  19. U_NAMESPACE_BEGIN
  20. /**
  21. * An optimization for the slowness of calling UnicodeString::append()
  22. * one character at a time in a loop. It stores appends in a buffer while
  23. * never actually calling append on the unicode string unless the buffer
  24. * fills up or is flushed.
  25. *
  26. * proper usage:
  27. * {
  28. * UnicodeStringAppender appender(astring);
  29. * for (int32_t i = 0; i < 100; ++i) {
  30. * appender.append((UChar) i);
  31. * }
  32. * // appender flushed automatically when it goes out of scope.
  33. * }
  34. */
  35. class UnicodeStringAppender : public UMemory {
  36. public:
  37. /**
  38. * dest is the UnicodeString being appended to. It must always
  39. * exist while this instance exists.
  40. */
  41. UnicodeStringAppender(UnicodeString &dest) : fDest(&dest), fIdx(0) { }
  42. inline void append(UChar x) {
  43. if (fIdx == UPRV_LENGTHOF(fBuffer)) {
  44. fDest->append(fBuffer, 0, fIdx);
  45. fIdx = 0;
  46. }
  47. fBuffer[fIdx++] = x;
  48. }
  49. inline void append(UChar32 x) {
  50. if (fIdx >= UPRV_LENGTHOF(fBuffer) - 1) {
  51. fDest->append(fBuffer, 0, fIdx);
  52. fIdx = 0;
  53. }
  54. U16_APPEND_UNSAFE(fBuffer, fIdx, x);
  55. }
  56. /**
  57. * Ensures that all appended characters have been written out to dest.
  58. */
  59. inline void flush() {
  60. if (fIdx) {
  61. fDest->append(fBuffer, 0, fIdx);
  62. }
  63. fIdx = 0;
  64. }
  65. /**
  66. * flush the buffer when we go out of scope.
  67. */
  68. ~UnicodeStringAppender() {
  69. flush();
  70. }
  71. private:
  72. UnicodeString *fDest;
  73. int32_t fIdx;
  74. UChar fBuffer[32];
  75. UnicodeStringAppender(const UnicodeStringAppender &other);
  76. UnicodeStringAppender &operator=(const UnicodeStringAppender &other);
  77. };
  78. U_NAMESPACE_END
  79. #endif