stringBuilder.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. String_Free(buffer);
  11. }
  12. HRESULT StringBuilder::Allocate(size_t newSize)
  13. {
  14. if (newSize <= allocated)
  15. return S_FALSE;
  16. LPWSTR t = String_ReAlloc(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. }