raw_string_ostream.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_COMMON_RAW_STRING_OSTREAM_H_
  5. #define CARBON_COMMON_RAW_STRING_OSTREAM_H_
  6. #include "common/check.h"
  7. #include "common/ostream.h"
  8. namespace Carbon {
  9. // Implements streaming output with an underlying string. The string must always
  10. // be taken prior to destruction.
  11. //
  12. // Versus `llvm::raw_string_ostream`:
  13. // - Owns the underlying string.
  14. // - Supports `pwrite` for compatibility with more stream uses in tests.
  15. class RawStringOstream : public llvm::raw_pwrite_stream {
  16. public:
  17. explicit RawStringOstream() : llvm::raw_pwrite_stream(/*Unbuffered=*/true) {}
  18. ~RawStringOstream() override {
  19. CARBON_CHECK(str_.empty(), "Expected to be emptied by TakeStr, have: {0}",
  20. str_);
  21. }
  22. // Returns the streamed contents, clearing the stream back to empty.
  23. auto TakeStr() -> std::string {
  24. std::string result = std::move(str_);
  25. clear();
  26. return result;
  27. }
  28. // Clears the buffer, which can be helpful when destructing without
  29. // necessarily calling `TakeStr()`.
  30. auto clear() -> void { str_.clear(); }
  31. auto empty() -> bool { return str_.empty(); }
  32. auto size() -> size_t { return str_.size(); }
  33. private:
  34. auto current_pos() const -> uint64_t override { return str_.size(); }
  35. auto pwrite_impl(const char* ptr, size_t size, uint64_t offset)
  36. -> void override {
  37. str_.replace(offset, size, ptr, size);
  38. }
  39. auto write_impl(const char* ptr, size_t size) -> void override {
  40. str_.append(ptr, size);
  41. }
  42. void reserveExtraSpace(uint64_t extra_size) override {
  43. str_.reserve(str_.size() + extra_size);
  44. }
  45. // The actual buffer.
  46. std::string str_;
  47. };
  48. } // namespace Carbon
  49. #endif // CARBON_COMMON_RAW_STRING_OSTREAM_H_