xref: /llvm-project/mlir/include/mlir/CAPI/Utils.h (revision e8d073951b4c732b48a87ca4f3a87e5f35a0ffa4)
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 <utility>
18 
19 #include "mlir-c/Support.h"
20 #include "llvm/Support/raw_ostream.h"
21 
22 //===----------------------------------------------------------------------===//
23 // Printing helper.
24 //===----------------------------------------------------------------------===//
25 
26 namespace mlir {
27 namespace detail {
28 /// A simple raw ostream subclass that forwards write_impl calls to the
29 /// user-supplied callback together with opaque user-supplied data.
30 class CallbackOstream : public llvm::raw_ostream {
31 public:
CallbackOstream(std::function<void (MlirStringRef,void *)> callback,void * opaqueData)32   CallbackOstream(std::function<void(MlirStringRef, void *)> callback,
33                   void *opaqueData)
34       : raw_ostream(/*unbuffered=*/true), callback(std::move(callback)),
35         opaqueData(opaqueData), pos(0u) {}
36 
write_impl(const char * ptr,size_t size)37   void write_impl(const char *ptr, size_t size) override {
38     MlirStringRef string = mlirStringRefCreate(ptr, size);
39     callback(string, opaqueData);
40     pos += size;
41   }
42 
current_pos()43   uint64_t current_pos() const override { return pos; }
44 
45 private:
46   std::function<void(MlirStringRef, void *)> callback;
47   void *opaqueData;
48   uint64_t pos;
49 };
50 } // namespace detail
51 } // namespace mlir
52 
53 #endif // MLIR_CAPI_UTILS_H
54