1 //===- Utils.h - C API General Utilities ------------------------*- C++ -*-===//
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 // This file defines general utilities for C API. This file should not be
10 // included from C++ code other than C API implementation nor from C code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef MLIR_CAPI_UTILS_H
15 #define MLIR_CAPI_UTILS_H
16 
17 #include "mlir-c/Support.h"
18 #include "llvm/Support/raw_ostream.h"
19 
20 //===----------------------------------------------------------------------===//
21 // Printing helper.
22 //===----------------------------------------------------------------------===//
23 
24 namespace mlir {
25 namespace detail {
26 /// A simple raw ostream subclass that forwards write_impl calls to the
27 /// user-supplied callback together with opaque user-supplied data.
28 class CallbackOstream : public llvm::raw_ostream {
29 public:
CallbackOstream(std::function<void (MlirStringRef,void *)> callback,void * opaqueData)30   CallbackOstream(std::function<void(MlirStringRef, void *)> callback,
31                   void *opaqueData)
32       : raw_ostream(/*unbuffered=*/true), callback(callback),
33         opaqueData(opaqueData), pos(0u) {}
34 
write_impl(const char * ptr,size_t size)35   void write_impl(const char *ptr, size_t size) override {
36     MlirStringRef string = mlirStringRefCreate(ptr, size);
37     callback(string, opaqueData);
38     pos += size;
39   }
40 
current_pos()41   uint64_t current_pos() const override { return pos; }
42 
43 private:
44   std::function<void(MlirStringRef, void *)> callback;
45   void *opaqueData;
46   uint64_t pos;
47 };
48 } // end namespace detail
49 } // end namespace mlir
50 
51 #endif // MLIR_CAPI_UTILS_H
52