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
26namespace mlir {
27namespace detail {
28/// A simple raw ostream subclass that forwards write_impl calls to the
29/// user-supplied callback together with opaque user-supplied data.
30class CallbackOstream : public llvm::raw_ostream {
31public:
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
37 void write_impl(const char *ptr, size_t size) override {
38 MlirStringRef string = mlirStringRefCreate(str: ptr, length: size);
39 callback(string, opaqueData);
40 pos += size;
41 }
42
43 uint64_t current_pos() const override { return pos; }
44
45private:
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

source code of mlir/include/mlir/CAPI/Utils.h