Files
carbon-lang/common/raw_string_ostream.h
T
Jon Ross-PerkinsandGeoff Romer 4c4c4a4d2c Add RawStringOstream for slightly simpler streaming to strings (#4817)
This adds a RawStringOstream. Versus TestRawOstream, which is
consolidated over to RawStringOstream, it uses a string for storage
instead of a vector, mainly to support move-to-string semantics. Versus
llvm::raw_string_ostream, it owns the string and supports pwrite (which
is needed for driver and its fd_ostream compatibility requirement).

This converts most uses of llvm::raw_string_ostream, leaving behind a
few in InstNamer that explicitly cannot own the string, such as:

```
     llvm::raw_string_ostream(name)
          << "_" << tree.tokens().GetColumnNumber(token);
```

I have this as its own library so that it can use CHECK.

Yes this doesn't save much code, but it's code we repeatedly write.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-01-18 01:11:44 +00:00

65 lines
1.8 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef CARBON_COMMON_RAW_STRING_OSTREAM_H_
#define CARBON_COMMON_RAW_STRING_OSTREAM_H_
#include "common/check.h"
#include "common/ostream.h"
namespace Carbon {
// Implements streaming output with an underlying string. The string must always
// be taken prior to destruction.
//
// Versus `llvm::raw_string_ostream`:
// - Owns the underlying string.
// - Supports `pwrite` for compatibility with more stream uses in tests.
class RawStringOstream : public llvm::raw_pwrite_stream {
public:
explicit RawStringOstream() : llvm::raw_pwrite_stream(/*Unbuffered=*/true) {}
~RawStringOstream() override {
CARBON_CHECK(str_.empty(), "Expected to be emptied by TakeStr, have: {0}",
str_);
}
// Returns the streamed contents, clearing the stream back to empty.
auto TakeStr() -> std::string {
std::string result = std::move(str_);
clear();
return result;
}
// Clears the buffer, which can be helpful when destructing without
// necessarily calling `TakeStr()`.
auto clear() -> void { str_.clear(); }
auto empty() -> bool { return str_.empty(); }
auto size() -> size_t { return str_.size(); }
private:
auto current_pos() const -> uint64_t override { return str_.size(); }
auto pwrite_impl(const char* ptr, size_t size, uint64_t offset)
-> void override {
str_.replace(offset, size, ptr, size);
}
auto write_impl(const char* ptr, size_t size) -> void override {
str_.append(ptr, size);
}
void reserveExtraSpace(uint64_t extra_size) override {
str_.reserve(str_.size() + extra_size);
}
// The actual buffer.
std::string str_;
};
} // namespace Carbon
#endif // CARBON_COMMON_RAW_STRING_OSTREAM_H_