scratch_buffer.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include "common/make_unique_for_overwrite.h"
  5. namespace Common {
  6. /**
  7. * ScratchBuffer class
  8. * This class creates a default initialized heap allocated buffer for cases such as intermediate
  9. * buffers being copied into entirely, where value initializing members during allocation or resize
  10. * is redundant.
  11. */
  12. template <typename T>
  13. class ScratchBuffer {
  14. public:
  15. ScratchBuffer() = default;
  16. explicit ScratchBuffer(size_t initial_capacity)
  17. : last_requested_size{initial_capacity}, buffer_capacity{initial_capacity},
  18. buffer{Common::make_unique_for_overwrite<T[]>(initial_capacity)} {}
  19. ~ScratchBuffer() = default;
  20. /// This will only grow the buffer's capacity if size is greater than the current capacity.
  21. /// The previously held data will remain intact.
  22. void resize(size_t size) {
  23. if (size > buffer_capacity) {
  24. auto new_buffer = Common::make_unique_for_overwrite<T[]>(size);
  25. std::move(buffer.get(), buffer.get() + buffer_capacity, new_buffer.get());
  26. buffer = std::move(new_buffer);
  27. buffer_capacity = size;
  28. }
  29. last_requested_size = size;
  30. }
  31. /// This will only grow the buffer's capacity if size is greater than the current capacity.
  32. /// The previously held data will be destroyed if a reallocation occurs.
  33. void resize_destructive(size_t size) {
  34. if (size > buffer_capacity) {
  35. buffer_capacity = size;
  36. buffer = Common::make_unique_for_overwrite<T[]>(buffer_capacity);
  37. }
  38. last_requested_size = size;
  39. }
  40. [[nodiscard]] T* data() noexcept {
  41. return buffer.get();
  42. }
  43. [[nodiscard]] const T* data() const noexcept {
  44. return buffer.get();
  45. }
  46. [[nodiscard]] T* begin() noexcept {
  47. return data();
  48. }
  49. [[nodiscard]] const T* begin() const noexcept {
  50. return data();
  51. }
  52. [[nodiscard]] T* end() noexcept {
  53. return data() + last_requested_size;
  54. }
  55. [[nodiscard]] const T* end() const noexcept {
  56. return data() + last_requested_size;
  57. }
  58. [[nodiscard]] T& operator[](size_t i) {
  59. return buffer[i];
  60. }
  61. [[nodiscard]] const T& operator[](size_t i) const {
  62. return buffer[i];
  63. }
  64. [[nodiscard]] size_t size() const noexcept {
  65. return last_requested_size;
  66. }
  67. [[nodiscard]] size_t capacity() const noexcept {
  68. return buffer_capacity;
  69. }
  70. private:
  71. size_t last_requested_size{};
  72. size_t buffer_capacity{};
  73. std::unique_ptr<T[]> buffer{};
  74. };
  75. } // namespace Common