[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / llvm / unittests / Support / buffer_ostream_test.cpp
blobf29c1bb61afa0512136be14f64bbff4d68c552ef
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 //===----------------------------------------------------------------------===//
9 #include "llvm/ADT/SmallString.h"
10 #include "llvm/Support/raw_ostream.h"
11 #include "gtest/gtest.h"
13 using namespace llvm;
15 namespace {
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:
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)
27 : Vector(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.
40 BufferOS << "abcd";
41 static_cast<raw_ostream &>(BufferOS).flush();
42 EXPECT_EQ("", Dest);
43 DestOS.flush();
44 EXPECT_EQ("", Dest);
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.
66 BufferOS << "abcd";
67 static_cast<raw_ostream &>(BufferOS).flush();
68 EXPECT_EQ("", Dest);
69 DestOSRef.flush();
70 EXPECT_EQ("", Dest);
73 // Write should land when constructor is called.
74 EXPECT_EQ("abcd", Dest);
77 } // end namespace