1 //===- buffer_ostream_test.cpp - buffer_ostream tests ---------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/ADT/SmallString.h"
10 #include "llvm/Support/raw_ostream.h"
11 #include "gtest/gtest.h"
12
13 using namespace llvm;
14
15 namespace {
16
17 /// Naive version of raw_svector_ostream that is buffered (by default) and
18 /// doesn't support pwrite.
19 class NaiveSmallVectorStream : public raw_ostream {
20 public:
current_pos() const21 uint64_t current_pos() const override { return Vector.size(); }
write_impl(const char * Ptr,size_t Size)22 void write_impl(const char *Ptr, size_t Size) override {
23 Vector.append(Ptr, Ptr + Size);
24 }
25
NaiveSmallVectorStream(SmallVectorImpl<char> & Vector)26 explicit NaiveSmallVectorStream(SmallVectorImpl<char> &Vector)
27 : Vector(Vector) {}
~NaiveSmallVectorStream()28 ~NaiveSmallVectorStream() override { flush(); }
29
30 SmallVectorImpl<char> &Vector;
31 };
32
TEST(buffer_ostreamTest,Reference)33 TEST(buffer_ostreamTest, Reference) {
34 SmallString<128> Dest;
35 {
36 NaiveSmallVectorStream DestOS(Dest);
37 buffer_ostream BufferOS(DestOS);
38
39 // Writing and flushing should have no effect on Dest.
40 BufferOS << "abcd";
41 static_cast<raw_ostream &>(BufferOS).flush();
42 EXPECT_EQ("", Dest);
43 DestOS.flush();
44 EXPECT_EQ("", Dest);
45 }
46
47 // Write should land when constructor is called.
48 EXPECT_EQ("abcd", Dest);
49 }
50
TEST(buffer_ostreamTest,Owned)51 TEST(buffer_ostreamTest, Owned) {
52 SmallString<128> Dest;
53 {
54 auto DestOS = std::make_unique<NaiveSmallVectorStream>(Dest);
55
56 // Confirm that NaiveSmallVectorStream is buffered by default.
57 EXPECT_NE(0u, DestOS->GetBufferSize());
58
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());
64
65 // Writing and flushing should have no effect on Dest.
66 BufferOS << "abcd";
67 static_cast<raw_ostream &>(BufferOS).flush();
68 EXPECT_EQ("", Dest);
69 DestOSRef.flush();
70 EXPECT_EQ("", Dest);
71 }
72
73 // Write should land when constructor is called.
74 EXPECT_EQ("abcd", Dest);
75 }
76
77 } // end namespace
78