From 41eeca5ce3802324d653221bddc0483b2fbe5194 Mon Sep 17 00:00:00 2001 From: Yehuda Sadeh Date: Wed, 8 Nov 2017 13:19:31 -0800 Subject: [PATCH] common/formattable: initial work initial work on a dict-like api Signed-off-by: Yehuda Sadeh --- src/rgw/rgw_admin.cc | 71 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/src/rgw/rgw_admin.cc b/src/rgw/rgw_admin.cc index 7b97e77a18a01..37546ddfef719 100644 --- a/src/rgw/rgw_admin.cc +++ b/src/rgw/rgw_admin.cc @@ -2448,6 +2448,77 @@ static int scan_totp(CephContext *cct, ceph::real_time& now, rados::cls::otp::ot return -ENOENT; } +struct Formattable { + enum Type { + FMT_NONE, + FMT_STRING, + FMT_ARRAY, + FMT_OBJ, + } type{FMT_NONE}; + string str; + vector arr; + map obj; + + void decode_json(JSONObj *jo) { + if (jo->is_array()) { + type = Formattable::FMT_ARRAY; + decode_json_obj(arr, jo); + } else if (jo->is_object()) { + type = Formattable::FMT_OBJ; + auto iter = jo->find_first(); + while (!iter.end()) { + JSONObj *field; + decode_json_obj(obj[field->get_name()], field); + } + } else { + type = Formattable::FMT_STRING; + decode_json_obj(str, jo); + } + } + + const string& val() const { + return str; + } + + const vector& array() const { + return arr; + } + + const Formattable& operator[](const string& name) const; +}; + +static Formattable default_formattable; + +const Formattable& Formattable::operator[](const string& name) const { + auto i = obj.find(name); + if (i == obj.end()) { + return default_formattable; + } + return i->second; +} + +void encode_json(const char *name, const Formattable& v, Formatter *f) +{ + switch (v.type) { + case Formattable::FMT_STRING: + encode_json(name, v.str, f); + break; + case Formattable::FMT_ARRAY: + encode_json(name, v.arr, f); + break; + case Formattable::FMT_OBJ: + f->open_object_section(name); + for (auto iter : v.obj) { + encode_json(iter.first.c_str(), iter.second, f); + } + f->close_section(); + break; + case Formattable::FMT_NONE: + break; + } +} + + #ifdef BUILDING_FOR_EMBEDDED extern "C" int cephd_rgw_admin(int argc, const char **argv) #else -- 2.39.5