1 //===- buffer_ostream_test.cpp - buffer_ostream tests ---------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/ADT/SmallString.h"
10 #include "llvm/Support/raw_ostream.h"
11 #include "gtest/gtest.h"
17 /// Naive version of raw_svector_ostream that is buffered (by default) and
18 /// doesn't support pwrite.
19 class NaiveSmallVectorStream
: public raw_ostream
{
21 uint64_t current_pos() const override
{ return Vector
.size(); }
22 void write_impl(const char *Ptr
, size_t Size
) override
{
23 Vector
.append(Ptr
, Ptr
+ Size
);
26 explicit NaiveSmallVectorStream(SmallVectorImpl
<char> &Vector
)
28 ~NaiveSmallVectorStream() override
{ flush(); }
30 SmallVectorImpl
<char> &Vector
;
33 TEST(buffer_ostreamTest
, Reference
) {
34 SmallString
<128> Dest
;
36 NaiveSmallVectorStream
DestOS(Dest
);
37 buffer_ostream
BufferOS(DestOS
);
39 // Writing and flushing should have no effect on Dest.
41 static_cast<raw_ostream
&>(BufferOS
).flush();
47 // Write should land when constructor is called.
48 EXPECT_EQ("abcd", Dest
);
51 TEST(buffer_ostreamTest
, Owned
) {
52 SmallString
<128> Dest
;
54 auto DestOS
= std::make_unique
<NaiveSmallVectorStream
>(Dest
);
56 // Confirm that NaiveSmallVectorStream is buffered by default.
57 EXPECT_NE(0u, DestOS
->GetBufferSize());
59 // Confirm that passing ownership to buffer_unique_ostream sets it to
60 // unbuffered. Also steal a reference to DestOS.
61 NaiveSmallVectorStream
&DestOSRef
= *DestOS
;
62 buffer_unique_ostream
BufferOS(std::move(DestOS
));
63 EXPECT_EQ(0u, DestOSRef
.GetBufferSize());
65 // Writing and flushing should have no effect on Dest.
67 static_cast<raw_ostream
&>(BufferOS
).flush();
73 // Write should land when constructor is called.
74 EXPECT_EQ("abcd", Dest
);