17
17
#include " llvm/ADT/StringRef.h"
18
18
#include " llvm/Support/Endian.h"
19
19
#include " llvm/Support/MemoryBufferRef.h"
20
+ #include " llvm/Support/raw_ostream.h"
20
21
#include " gmock/gmock.h"
21
22
#include " gtest/gtest.h"
22
23
@@ -37,6 +38,29 @@ module @TestDialectResources attributes {
37
38
#-}
38
39
)" ;
39
40
41
+ struct MockOstream final : public raw_ostream {
42
+ std::unique_ptr<std::byte[]> buffer;
43
+ size_t size = 0 ;
44
+
45
+ MOCK_METHOD (void , reserveExtraSpace, (uint64_t extraSpace), (override ));
46
+
47
+ MockOstream () : raw_ostream(true ) {}
48
+ uint64_t current_pos () const override { return pos; }
49
+
50
+ private:
51
+ size_t pos = 0 ;
52
+
53
+ void write_impl (const char *ptr, size_t length) override {
54
+ if (pos + length <= size) {
55
+ memcpy ((void *)(buffer.get () + pos), ptr, length);
56
+ pos += length;
57
+ } else {
58
+ report_fatal_error (
59
+ " Attempted to write past the end of the fixed size buffer." );
60
+ }
61
+ }
62
+ };
63
+
40
64
TEST (Bytecode, MultiModuleWithResource) {
41
65
MLIRContext context;
42
66
Builder builder (&context);
@@ -45,12 +69,17 @@ TEST(Bytecode, MultiModuleWithResource) {
45
69
parseSourceString<Operation *>(irWithResources, parseConfig);
46
70
ASSERT_TRUE (module );
47
71
48
- // Write the module to bytecode
49
- std::string buffer;
50
- llvm::raw_string_ostream ostream (buffer);
72
+ // Write the module to bytecode.
73
+ MockOstream ostream;
74
+ EXPECT_CALL (ostream, reserveExtraSpace).WillOnce ([&](uint64_t space) {
75
+ ostream.buffer = std::make_unique<std::byte[]>(space);
76
+ ostream.size = space;
77
+ });
51
78
ASSERT_TRUE (succeeded (writeBytecodeToFile (module .get (), ostream)));
52
79
53
80
// Create copy of buffer which is aligned to requested resource alignment.
81
+ std::string buffer ((char *)ostream.buffer .get (),
82
+ (char *)ostream.buffer .get () + ostream.size );
54
83
constexpr size_t kAlignment = 0x20 ;
55
84
size_t bufferSize = buffer.size ();
56
85
buffer.reserve (bufferSize + kAlignment - 1 );
0 commit comments