Skip to content

Commit ad6c23a

Browse files
authored
[Support] Allow llvm::interleaved with custom ostream types (llvm#136318)
This makes `llvm::interleaved` useable with ostream types that define custom stream operators that print in a different format from `raw_ostream`. For example, MLIR's OpAsmPrinter prints values as operands: https://github.com/llvm/llvm-project/blob/6c5f50f18694a4d91d7ce53a14188c54ee7c6f3b/mlir/include/mlir/IR/OpImplementation.h#L534-L552
1 parent bc48b3f commit ad6c23a

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

llvm/include/llvm/Support/InterleavedRange.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ template <typename Range> class InterleavedRange {
4242
StringRef Suffix)
4343
: TheRange(R), Separator(Separator), Prefix(Prefix), Suffix(Suffix) {}
4444

45-
friend raw_ostream &operator<<(raw_ostream &OS,
46-
const InterleavedRange &Interleaved) {
45+
template <typename OStream>
46+
friend OStream &operator<<(OStream &OS, const InterleavedRange &Interleaved) {
4747
if (!Interleaved.Prefix.empty())
4848
OS << Interleaved.Prefix;
4949
llvm::interleave(Interleaved.TheRange, OS, Interleaved.Separator);

llvm/unittests/Support/InterleavedRangeTest.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,26 @@ TEST(InterleavedRangeTest, CustomPrint) {
6767
EXPECT_EQ("[$$3##, $$4##, $$5##]", interleaved_array(V).str());
6868
}
6969

70+
struct CustomDoublingOStream : raw_string_ostream {
71+
unsigned NumCalled = 0;
72+
using raw_string_ostream::raw_string_ostream;
73+
74+
friend CustomDoublingOStream &operator<<(CustomDoublingOStream &OS, int V) {
75+
++OS.NumCalled;
76+
static_cast<raw_string_ostream &>(OS) << (2 * V);
77+
return OS;
78+
}
79+
};
80+
81+
TEST(InterleavedRangeTest, CustomOStream) {
82+
// Make sure that interleaved calls the stream operator on the derived class,
83+
// and that it returns a reference to the same stream type.
84+
int V[] = {3, 4, 5};
85+
std::string Buf;
86+
CustomDoublingOStream OS(Buf);
87+
OS << interleaved(V) << 22;
88+
EXPECT_EQ("6, 8, 1044", Buf);
89+
EXPECT_EQ(OS.NumCalled, 4u);
90+
}
91+
7092
} // namespace

0 commit comments

Comments
 (0)