1
0

stringBuilder.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "main.h"
  2. #include "./stringBuilder.h"
  3. #include <strsafe.h>
  4. StringBuilder::StringBuilder()
  5. : buffer(NULL), cursor(NULL), allocated(0), remaining(0)
  6. {
  7. }
  8. StringBuilder::~StringBuilder()
  9. {
  10. Plugin_FreeString(buffer);
  11. }
  12. HRESULT StringBuilder::Allocate(size_t newSize)
  13. {
  14. if (newSize <= allocated)
  15. return S_FALSE;
  16. LPWSTR t = Plugin_ReAllocString(buffer, newSize);
  17. if (NULL == t) return E_OUTOFMEMORY;
  18. cursor = t + (cursor - buffer);
  19. buffer = t;
  20. remaining += newSize - allocated;
  21. allocated = newSize;
  22. return S_OK;
  23. }
  24. void StringBuilder::Clear(void)
  25. {
  26. if (NULL != buffer)
  27. {
  28. buffer[0] = L'\0';
  29. }
  30. cursor = buffer;
  31. remaining = allocated;
  32. }
  33. LPCWSTR StringBuilder::Get(void)
  34. {
  35. return buffer;
  36. }
  37. HRESULT StringBuilder::Set(size_t index, WCHAR value)
  38. {
  39. if (NULL == buffer)
  40. return E_POINTER;
  41. if (index >= allocated)
  42. return E_INVALIDARG;
  43. buffer[index] = value;
  44. return S_OK;
  45. }
  46. HRESULT StringBuilder::Append(LPCWSTR pszString)
  47. {
  48. HRESULT hr;
  49. if (NULL == buffer)
  50. {
  51. hr = Allocate(1024);
  52. if (FAILED(hr)) return hr;
  53. }
  54. size_t cchCursor = remaining;
  55. hr = StringCchCopyEx(cursor, cchCursor, pszString, &cursor, &remaining, STRSAFE_IGNORE_NULLS);
  56. if (STRSAFE_E_INSUFFICIENT_BUFFER == hr)
  57. {
  58. size_t offset = cchCursor - remaining;
  59. size_t requested = lstrlen(pszString) + (allocated - remaining) + 1;
  60. size_t newsize = allocated * 2;
  61. while (newsize < requested) newsize = newsize * 2;
  62. hr = Allocate(newsize);
  63. if (FAILED(hr)) return hr;
  64. hr = StringCchCopyEx(cursor, remaining, pszString + offset, &cursor, &remaining, STRSAFE_IGNORE_NULLS);
  65. }
  66. return hr;
  67. }