1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
4 * Ceph - scalable distributed file system
6 * Copyright (C) 2015 Red Hat Inc
8 * Author: John Spray <john.spray@redhat.com>
10 * This is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License version 2.1, as published by the Free Software
13 * Foundation. See file COPYING.
18 #include "PyFormatter.h"
20 #define LARGE_SIZE 1024
23 void PyFormatter::open_array_section(const char *name)
25 PyObject *list = PyList_New(0);
26 dump_pyobject(name, list);
31 void PyFormatter::open_object_section(const char *name)
33 PyObject *dict = PyDict_New();
34 dump_pyobject(name, dict);
39 void PyFormatter::dump_unsigned(const char *name, uint64_t u)
41 PyObject *p = PyLong_FromLongLong(u);
43 dump_pyobject(name, p);
46 void PyFormatter::dump_int(const char *name, int64_t u)
48 PyObject *p = PyLong_FromLongLong(u);
50 dump_pyobject(name, p);
53 void PyFormatter::dump_float(const char *name, double d)
55 dump_pyobject(name, PyFloat_FromDouble(d));
58 void PyFormatter::dump_string(const char *name, const std::string& s)
60 dump_pyobject(name, PyString_FromString(s.c_str()));
63 void PyFormatter::dump_bool(const char *name, bool b)
67 dump_pyobject(name, Py_True);
70 dump_pyobject(name, Py_False);
74 std::ostream& PyFormatter::dump_stream(const char *name)
76 // Give the caller an ostream, construct a PyString,
77 // and remember the association between the two. On flush,
78 // we'll read from the ostream into the PyString
79 auto ps = std::make_shared<PendingStream>();
83 pending_streams.push_back(ps);
88 void PyFormatter::dump_format_va(const char *name, const char *ns, bool quoted, const char *fmt, va_list ap)
91 vsnprintf(buf, LARGE_SIZE, fmt, ap);
93 dump_pyobject(name, PyString_FromString(buf));
97 * Steals reference to `p`
99 void PyFormatter::dump_pyobject(const char *name, PyObject *p)
101 if (PyList_Check(cursor)) {
102 PyList_Append(cursor, p);
104 } else if (PyDict_Check(cursor)) {
105 PyObject *key = PyString_FromString(name);
106 PyDict_SetItem(cursor, key, p);
114 void PyFormatter::finish_pending_streams()
116 for (const auto &i : pending_streams) {
117 PyObject *tmp_cur = cursor;
121 PyString_FromString(i->stream.str().c_str()));
125 pending_streams.clear();