You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mesos.apache.org by mp...@apache.org on 2016/01/15 18:59:51 UTC
[1/4] mesos git commit: Added `jsonify` function to stout.
Repository: mesos
Updated Branches:
refs/heads/master 331939ff7 -> e8af5cca9
Added `jsonify` function to stout.
Review: https://reviews.apache.org/r/41593/
Project: http://git-wip-us.apache.org/repos/asf/mesos/repo
Commit: http://git-wip-us.apache.org/repos/asf/mesos/commit/42cf29ec
Tree: http://git-wip-us.apache.org/repos/asf/mesos/tree/42cf29ec
Diff: http://git-wip-us.apache.org/repos/asf/mesos/diff/42cf29ec
Branch: refs/heads/master
Commit: 42cf29ec9e16771cb2ff397b80889b7bd219be6d
Parents: 331939f
Author: Michael Park <mp...@apache.org>
Authored: Tue Dec 8 09:25:32 2015 -0500
Committer: Michael Park <mp...@apache.org>
Committed: Fri Jan 15 09:37:35 2016 -0800
----------------------------------------------------------------------
3rdparty/libprocess/3rdparty/stout/Makefile.am | 1 +
3rdparty/libprocess/3rdparty/stout/README.md | 66 ++
.../3rdparty/stout/include/Makefile.am | 1 +
.../3rdparty/stout/include/stout/jsonify.hpp | 604 +++++++++++++++++++
.../3rdparty/stout/include/stout/protobuf.hpp | 130 ++++
.../3rdparty/stout/tests/CMakeLists.txt | 1 +
.../3rdparty/stout/tests/jsonify_tests.cpp | 164 +++++
.../3rdparty/stout/tests/protobuf_tests.cpp | 180 ++++++
8 files changed, 1147 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/mesos/blob/42cf29ec/3rdparty/libprocess/3rdparty/stout/Makefile.am
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/Makefile.am b/3rdparty/libprocess/3rdparty/stout/Makefile.am
index 5ab7bc4..206489c 100644
--- a/3rdparty/libprocess/3rdparty/stout/Makefile.am
+++ b/3rdparty/libprocess/3rdparty/stout/Makefile.am
@@ -35,6 +35,7 @@ EXTRA_DIST = \
tests/interval_tests.cpp \
tests/ip_tests.cpp \
tests/json_tests.cpp \
+ tests/jsonify_tests.cpp \
tests/linkedhashmap_tests.cpp \
tests/mac_tests.cpp \
tests/main.cpp \
http://git-wip-us.apache.org/repos/asf/mesos/blob/42cf29ec/3rdparty/libprocess/3rdparty/stout/README.md
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/README.md b/3rdparty/libprocess/3rdparty/stout/README.md
index a2a3dc6..c534835 100644
--- a/3rdparty/libprocess/3rdparty/stout/README.md
+++ b/3rdparty/libprocess/3rdparty/stout/README.md
@@ -21,6 +21,7 @@ Note that the library is designed to completely avoid exceptions. See [exception
* <a href="#fs">fs::</a>
* <a href="#gzip">gzip::</a>
* <a href="#json">JSON::</a>
+* <a href="#jsonify">`jsonify`</a>
* <a href="#lambda">lambda::</a>
* <a href="#net">net::</a>
* <a href="#os">os::</a>
@@ -218,6 +219,71 @@ Of course, nesting of a `JSON::Value` is also permitted as per the JSON specific
You can "render" a JSON value using `std::ostream operator<<` (or by using `stringify` (see [here](#stringify)).
+<a href="jsonify"></a>
+
+## `jsonify`
+
+`jsonify` takes an instance of a C++ object and returns a representation of `JSON` string captured in a light-weight proxy object. The proxy object can either be implicitly converted to a `std::string`, or directly inserted into an output stream.
+
+`jsonify(const T&)` is implemented by calling the function `json`. We perform unqualified function call so that it can detect overloads via argument dependent lookup. That is, we will search for, and use a free function named `json` in the same namespace as `T`.
+
+> NOTE: This relationship is similar to `boost::hash` and `hash_value`.
+
+`json` takes two parameters: a pointer to a writer type, and the type of the object. The following are the available writers and their member functions:
+
+* `BooleanWriter` -- `set(value)`
+* `NumberWriter` -- `set(value)`
+* `StringWriter` -- `append(value)`
+* `ArrayWriter` -- `element(value)`
+* `ObjectWriter` -- `field(key, value)`
+
+~~~{.cpp}
+namespace store {
+
+struct Customer
+{
+ std::string first_name;
+ std::string last_name;
+ int age;
+};
+
+void json(JSON::ObjectWriter* writer, const Customer& customer)
+{
+ writer->field("first name", customer.first_name);
+ writer->field("last name", customer.last_name);
+ writer->field("age", customer.age);
+}
+
+} // namespace store {
+
+store::Customer customer{"michael", "park", 25};
+std::cout << jsonify(customer);
+// prints: {"first name":"michael","last name":"park","age":25}
+~~~
+
+`jsonify(const F&)` overload takes a function object `F` that takes a pointer to writer. This is useful in cases where we don't want to define a public `json` function out-ouf-line.
+
+~~~{.cpp}
+namespace store {
+
+struct Customer
+{
+ std::string first_name;
+ std::string last_name;
+ int age;
+};
+
+} // namespace store {
+
+store::Customer customer{"michael", "park", 25};
+std::cout << jsonify([&customer](JSON::ObjectWriter* writer) {
+ writer->field("first name", customer.first_name);
+ writer->field("last name", customer.last_name);
+ writer->field("age", customer.age);
+});
+// prints: {"first name":"michael","last name":"park","age":25}
+~~~
+
<a href="lambda"></a>
## `lambda::`
http://git-wip-us.apache.org/repos/asf/mesos/blob/42cf29ec/3rdparty/libprocess/3rdparty/stout/include/Makefile.am
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/include/Makefile.am b/3rdparty/libprocess/3rdparty/stout/include/Makefile.am
index f32493f..41c5435 100644
--- a/3rdparty/libprocess/3rdparty/stout/include/Makefile.am
+++ b/3rdparty/libprocess/3rdparty/stout/include/Makefile.am
@@ -42,6 +42,7 @@ nobase_include_HEADERS = \
stout/interval.hpp \
stout/ip.hpp \
stout/json.hpp \
+ stout/jsonify.hpp \
stout/lambda.hpp \
stout/linkedhashmap.hpp \
stout/mac.hpp \
http://git-wip-us.apache.org/repos/asf/mesos/blob/42cf29ec/3rdparty/libprocess/3rdparty/stout/include/stout/jsonify.hpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/include/stout/jsonify.hpp b/3rdparty/libprocess/3rdparty/stout/include/stout/jsonify.hpp
new file mode 100644
index 0000000..cabb20d
--- /dev/null
+++ b/3rdparty/libprocess/3rdparty/stout/include/stout/jsonify.hpp
@@ -0,0 +1,604 @@
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef __STOUT_JSONIFY__
+#define __STOUT_JSONIFY__
+
+#include <cstddef>
+#include <functional>
+#include <ostream>
+#include <sstream>
+#include <string>
+#include <type_traits>
+#include <utility>
+
+#include <stout/strings.hpp>
+
+// `jsonify` takes an instance of a C++ object and returns a light-weight proxy
+// object that can either be implicitly converted to a `std::string`, or
+// directly inserted into an output stream.
+//
+// `jsonify(const T&)` is implemented by calling the function `json`.
+// We perform unqualified function call so that it can detect overloads via
+// argument dependent lookup. That is, we will search for, and use a free
+// function named `json` in the same namespace as `T`.
+//
+// IMPORTANT: The output stream must not be exception-enabled. This is because
+// the writer definitions below insert into the output stream in their
+// destructors.
+//
+// NOTE: This relationship is similar to `boost::hash` and `hash_value`.
+
+
+// Forward declaration of `JSON::Proxy`.
+namespace JSON { class Proxy; }
+
+// Forward declaration of `jsonify`.
+template <typename T>
+JSON::Proxy jsonify(const T&);
+
+namespace JSON {
+
+// The result of `jsonify`. This is a light-weight proxy object that can either
+// be implicitly converted to a `std::string`, or directly inserted into an
+// output stream.
+//
+// In order to make this object light-weight, variables are captured by
+// reference. This gives rise to similar semantics as `std::forward_as_tuple`.
+// If the arguments are temporaries, `JSON::Proxy` does not extend their
+// lifetime; they have to be used before the end of the full expression.
+class Proxy
+{
+public:
+ operator std::string() &&
+ {
+ std::ostringstream stream;
+ stream << std::move(*this);
+ return stream.str();
+ }
+
+private:
+ Proxy(std::function<void(std::ostream*)> write) : write_(std::move(write)) {}
+
+ // We declare copy/move constructors `private` to prevent statements that try
+ // to "save" an instance of `Proxy` such as:
+ //
+ // ```
+ // std::string F();
+ // Proxy proxy = jsonify(F());
+ // ```
+ //
+ // Since `proxy` in the above example would be holding onto a reference to a
+ // temporary string returned by `F()`.
+ Proxy(const Proxy&) = default;
+ Proxy(Proxy&&) = default;
+
+ std::function<void(std::ostream*)> write_;
+
+ template <typename T>
+ friend Proxy (::jsonify)(const T&);
+
+ friend std::ostream& operator<<(std::ostream& stream, Proxy&& that);
+};
+
+
+inline std::ostream& operator<<(std::ostream& stream, Proxy&& that)
+{
+ that.write_(&stream);
+ return stream;
+}
+
+
+// The boolean writer. If `set` is not called at all, `false` is printed.
+// If `set` is called more than once, only the last value is printed out.
+class BooleanWriter
+{
+public:
+ BooleanWriter(std::ostream* stream) : stream_(stream), value_(false) {}
+
+ BooleanWriter(const BooleanWriter&) = delete;
+ BooleanWriter(BooleanWriter&&) = delete;
+
+ ~BooleanWriter() { *stream_ << (value_ ? "true" : "false"); }
+
+ BooleanWriter& operator=(const BooleanWriter&) = delete;
+ BooleanWriter& operator=(BooleanWriter&&) = delete;
+
+ void set(bool value) { value_ = value; }
+
+private:
+ std::ostream* stream_;
+ bool value_;
+};
+
+
+// The number writer. If `set` is not called at all, `0` is printed.
+// If `set` is called more than once, only the last value is printed.
+class NumberWriter
+{
+public:
+ NumberWriter(std::ostream* stream)
+ : stream_(stream), type_(INT64), int64_(0) {}
+
+ NumberWriter(const NumberWriter&) = delete;
+ NumberWriter(NumberWriter&&) = delete;
+
+ ~NumberWriter()
+ {
+ switch (type_) {
+ case INT64: {
+ *stream_ << int64_;
+ break;
+ }
+ case UINT64: {
+ *stream_ << uint64_;
+ break;
+ }
+ case DOUBLE: {
+ // Prints a floating point value, with the specified precision, see:
+ // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2005.pdf
+ // Additionally ensures that a decimal point is in the output.
+ char buffer[50] = {}; // More than enough for the specified precision.
+ snprintf(
+ buffer,
+ sizeof(buffer),
+ "%#.*g",
+ std::numeric_limits<double>::digits10,
+ double_);
+
+ // Get rid of excess trailing zeroes before outputting.
+ // Otherwise, printing 1.0 would result in "1.00000000000000".
+ std::string trimmed = strings::trim(buffer, strings::SUFFIX, "0");
+
+ // NOTE: valid JSON numbers cannot end with a '.'.
+ *stream_ << trimmed << (trimmed.back() == '.' ? "0" : "");
+ break;
+ }
+ }
+ }
+
+ NumberWriter& operator=(const NumberWriter&) = delete;
+ NumberWriter& operator=(NumberWriter&&) = delete;
+
+ void set(int32_t value) { set(static_cast<int64_t>(value)); }
+
+ void set(int64_t value)
+ {
+ type_ = INT64;
+ int64_ = value;
+ }
+
+ void set(uint32_t value) { set(static_cast<uint64_t>(value)); }
+
+ void set(uint64_t value)
+ {
+ type_ = UINT64;
+ uint64_ = value;
+ }
+
+ void set(float value) { set(static_cast<double>(value)); }
+
+ void set(double value)
+ {
+ type_ = DOUBLE;
+ double_ = value;
+ }
+
+private:
+ std::ostream* stream_;
+
+ enum { INT64, UINT64, DOUBLE } type_;
+
+ union
+ {
+ int64_t int64_;
+ uint64_t uint64_;
+ double double_;
+ };
+};
+
+
+// The string writer. `append` is used to append a character or a string.
+// If `append` is not called at all, `""` is printed.
+class StringWriter
+{
+public:
+ StringWriter(std::ostream* stream) : stream_(stream) { *stream_ << '"'; }
+
+ StringWriter(const StringWriter&) = delete;
+ StringWriter(StringWriter&&) = delete;
+
+ ~StringWriter() { *stream_ << '"'; }
+
+ StringWriter& operator=(const StringWriter&) = delete;
+ StringWriter& operator=(StringWriter&&) = delete;
+
+ void append(char c)
+ {
+ switch (c) {
+ case '"' : *stream_ << "\\\""; break;
+ case '\\': *stream_ << "\\\\"; break;
+ case '/' : *stream_ << "\\/"; break;
+ case '\b': *stream_ << "\\b"; break;
+ case '\f': *stream_ << "\\f"; break;
+ case '\n': *stream_ << "\\n"; break;
+ case '\r': *stream_ << "\\r"; break;
+ case '\t': *stream_ << "\\t"; break;
+ default: {
+ if (static_cast<unsigned char>(c) < 0x20 || c == 0x7f) {
+ char buffer[7];
+ snprintf(buffer, sizeof(buffer), "\\u%04x", c & 0xff);
+ stream_->write(buffer, sizeof(buffer) - 1);
+ } else {
+ *stream_ << c;
+ }
+ break;
+ }
+ }
+ }
+
+ template <std::size_t N>
+ void append(const char (&value)[N]) { append(value, N - 1); }
+ void append(const std::string& value) { append(value.data(), value.size()); }
+
+private:
+ void append(const char* value, std::size_t size)
+ {
+ for (std::size_t i = 0; i < size; ++i) {
+ append(value[i]);
+ }
+ }
+
+ std::ostream* stream_;
+};
+
+
+// The array writer. `element(value)` is used to write a new element.
+// If `element` is not called at all, `[]` is printed.
+class ArrayWriter
+{
+public:
+ ArrayWriter(std::ostream* stream) : stream_(stream), count_(0)
+ {
+ *stream_ << '[';
+ }
+
+ ArrayWriter(const ArrayWriter&) = delete;
+ ArrayWriter(ArrayWriter&&) = delete;
+
+ ~ArrayWriter() { *stream_ << ']'; }
+
+ ArrayWriter& operator=(const ArrayWriter&) = delete;
+ ArrayWriter& operator=(ArrayWriter&&) = delete;
+
+ template <typename T>
+ void element(const T& value)
+ {
+ if (count_ > 0) {
+ *stream_ << ',';
+ }
+ *stream_ << jsonify(value);
+ ++count_;
+ }
+
+private:
+ std::ostream* stream_;
+ std::size_t count_;
+};
+
+
+// The object writer. `field(key, value)` is used to write a new field.
+// If `field` is not called at all, `{}` is printed.
+class ObjectWriter
+{
+public:
+ ObjectWriter(std::ostream* stream) : stream_(stream), count_(0)
+ {
+ *stream_ << '{';
+ }
+
+ ObjectWriter(const ObjectWriter&) = delete;
+ ObjectWriter(ObjectWriter&&) = delete;
+
+ ~ObjectWriter() { *stream_ << '}'; }
+
+ ObjectWriter& operator=(const ObjectWriter&) = delete;
+ ObjectWriter& operator=(ObjectWriter&&) = delete;
+
+ template <typename T>
+ void field(const std::string& key, const T& value)
+ {
+ if (count_ > 0) {
+ *stream_ << ',';
+ }
+ *stream_ << jsonify(key) << ':' << jsonify(value);
+ ++count_;
+ }
+
+private:
+ std::ostream* stream_;
+ std::size_t count_;
+};
+
+
+// `json` function for boolean.
+inline void json(BooleanWriter* writer, bool value) { writer->set(value); }
+
+
+// `json` functions for numbers.
+inline void json(NumberWriter* writer, int32_t value) { writer->set(value); }
+inline void json(NumberWriter* writer, int64_t value) { writer->set(value); }
+inline void json(NumberWriter* writer, uint32_t value) { writer->set(value); }
+inline void json(NumberWriter* writer, uint64_t value) { writer->set(value); }
+inline void json(NumberWriter* writer, float value) { writer->set(value); }
+inline void json(NumberWriter* writer, double value) { writer->set(value); }
+
+
+// `json` functions for strings.
+
+template <std::size_t N>
+void json(StringWriter* writer, const char (&value)[N])
+{
+ writer->append(value);
+}
+
+
+inline void json(StringWriter* writer, const std::string& value)
+{
+ writer->append(value);
+}
+
+namespace internal {
+
+// TODO(mpark): Pull this out to something like <stout/meta.hpp>.
+// This pattern already exists in `<process/future.hpp>`.
+struct LessPrefer {};
+struct Prefer : LessPrefer {};
+
+// The member `value` is `true` if `T` is a sequence, and `false` otherwise.
+template <typename T>
+struct IsSequence
+{
+private:
+ // This overload only participates in overload resolution if the following
+ // expressions are valid.
+ // (1) begin(t) != end(t)
+ // (2) auto iter = begin(t); ++iter
+ // (3) *begin(t)
+ //
+ // The expressions are only used for SFINAE purposes, and comma operators are
+ // used to ignore the results of the expressions. That is, the return type of
+ // this function is `decltype(expr0, expr1, expr2, std::true_type{})` which is
+ // `std::true_type`.
+ template <typename U>
+ static auto test(Prefer)
+ -> decltype(std::begin(std::declval<U&>()) != std::end(std::declval<U&>()),
+ ++std::declval<decltype(std::begin(std::declval<U&>()))&>(),
+ *std::begin(std::declval<U&>()),
+ std::true_type{});
+
+ // This overload is chosen if the preferred version is SFINAE'd out.
+ template <typename U>
+ static std::false_type test(LessPrefer);
+
+public:
+ static constexpr bool value = decltype(test<T>(Prefer()))::value;
+};
+
+
+// The member `value` is `true` if `T` has a member typedef `mapped_type`, and
+// `false` otherwise. We take the existence of `mapped_type` as the indication
+// of an associative container (e.g., std::map).
+template <typename T>
+struct HasMappedType
+{
+private:
+ template <typename U, typename = typename U::mapped_type>
+ static std::true_type test(Prefer);
+
+ template <typename U>
+ static std::false_type test(LessPrefer);
+
+public:
+ static constexpr bool value = decltype(test<T>(Prefer()))::value;
+};
+
+} // namespace internal {
+
+// `json` function for iterables (e.g., std::vector).
+// This function is only enabled if `Iterable` is iterable, is not a
+// `const char (&)[N]` (in order to avoid ambiguity with the string literal
+// overload), and does not have a member typedef `mapped_type` (we take the
+// existence of `mapped_type` as the indication of an associative container).
+template <
+ typename Iterable,
+ typename std::enable_if<
+ internal::IsSequence<Iterable>::value &&
+ !(std::is_array<Iterable>::value &&
+ std::rank<Iterable>::value == 1 &&
+ std::is_same<
+ char, typename std::remove_extent<Iterable>::type>::value) &&
+ !internal::HasMappedType<Iterable>::value, int>::type = 0>
+void json(ArrayWriter* writer, const Iterable& iterable)
+{
+ foreach (const auto& value, iterable) {
+ writer->element(value);
+ }
+}
+
+
+// `json` function for dictionaries (e.g., std::map).
+// This function is only enabled if `Dictionary` is iterable, and has a member
+// typedef `mapped_type` (we take the existence of `mapped_type` as the
+// indication of an associative container).
+template <
+ typename Dictionary,
+ typename std::enable_if<
+ internal::IsSequence<Dictionary>::value &&
+ internal::HasMappedType<Dictionary>::value, int>::type = 0>
+void json(ObjectWriter* writer, const Dictionary& dictionary)
+{
+ foreachpair (const auto& key, const auto& value, dictionary) {
+ // TODO(mpark): Consider passing `stringify(key)`.
+ writer->field(key, value);
+ }
+}
+
+
+// An object that can be converted to a pointer to any of the JSON writers.
+// This is used to resolve the following scenario:
+//
+// ```
+// void json(JSON::ObjectWriter*, const Resources&);
+//
+// void json(
+// JSON::ArrayWriter*,
+// const google::protobuf::RepeatedPtrField<Resource>&);
+//
+// Resources resources;
+// std::cout << jsonify(resources); // We want to use the first overload!
+// ```
+//
+// The goal is to perform overload resolution based on the second parameter.
+// Since `WriterProxy` is convertible to any of the writers equivalently, we
+// force overload resolution of `json(WriterProxy(stream), value)` to depend
+// only on the second parameter.
+class WriterProxy
+{
+public:
+ WriterProxy(std::ostream* stream) : stream_(stream) {}
+
+ ~WriterProxy()
+ {
+ switch (type_) {
+ case BOOLEAN_WRITER: {
+ writer_.boolean_writer.~BooleanWriter();
+ break;
+ }
+ case NUMBER_WRITER: {
+ writer_.number_writer.~NumberWriter();
+ break;
+ }
+ case STRING_WRITER: {
+ writer_.string_writer.~StringWriter();
+ break;
+ }
+ case ARRAY_WRITER: {
+ writer_.array_writer.~ArrayWriter();
+ break;
+ }
+ case OBJECT_WRITER: {
+ writer_.object_writer.~ObjectWriter();
+ break;
+ }
+ }
+ }
+
+ operator BooleanWriter*() &&
+ {
+ new (&writer_.boolean_writer) BooleanWriter(stream_);
+ type_ = BOOLEAN_WRITER;
+ return &writer_.boolean_writer;
+ }
+
+ operator NumberWriter*() &&
+ {
+ new (&writer_.number_writer) NumberWriter(stream_);
+ type_ = NUMBER_WRITER;
+ return &writer_.number_writer;
+ }
+
+ operator StringWriter*() &&
+ {
+ new (&writer_.string_writer) StringWriter(stream_);
+ type_ = STRING_WRITER;
+ return &writer_.string_writer;
+ }
+
+ operator ArrayWriter*() &&
+ {
+ new (&writer_.array_writer) ArrayWriter(stream_);
+ type_ = ARRAY_WRITER;
+ return &writer_.array_writer;
+ }
+
+ operator ObjectWriter*() &&
+ {
+ new (&writer_.object_writer) ObjectWriter(stream_);
+ type_ = OBJECT_WRITER;
+ return &writer_.object_writer;
+ }
+
+private:
+ enum Type
+ {
+ BOOLEAN_WRITER,
+ NUMBER_WRITER,
+ STRING_WRITER,
+ ARRAY_WRITER,
+ OBJECT_WRITER
+ };
+
+ union Writer
+ {
+ Writer() {}
+ ~Writer() {}
+ BooleanWriter boolean_writer;
+ NumberWriter number_writer;
+ StringWriter string_writer;
+ ArrayWriter array_writer;
+ ObjectWriter object_writer;
+ };
+
+ std::ostream* stream_;
+ Type type_;
+ Writer writer_;
+};
+
+namespace internal {
+
+// NOTE: The following overloads of `internal::jsonify` return a `std::function`
+// rather than a `JSON::Proxy` since `JSON::Proxy`'s copy/move constructors are
+// declared `private`. We could also declare `internal::jsonify` as friend of
+// `JSON::Proxy` but chose to minimize friendship and construct a
+// `std::function` instead.
+
+// Given an `F` which is a "write" function, we simply use it directly.
+template <typename F, typename = typename std::result_of<F(WriterProxy)>::type>
+std::function<void(std::ostream*)> jsonify(const F& write, Prefer)
+{
+ return [&write](std::ostream* stream) { write(WriterProxy(stream)); };
+}
+
+// Given a `T` which is not a "write" function itself, the default "write"
+// function is to perform an unqualified function call to `json`, which enables
+// argument-dependent lookup. This considers the `json` overloads in the `JSON`
+// namespace as well, since `WriterProxy` is intentionally defined in the
+// `JSON` namespace.
+template <typename T>
+std::function<void(std::ostream*)> jsonify(const T& value, LessPrefer)
+{
+ return [&value](std::ostream* stream) {
+ json(WriterProxy(stream), value);
+ };
+}
+
+} // namespace internal {
+} // namespace JSON {
+
+template <typename T>
+JSON::Proxy jsonify(const T& t)
+{
+ return JSON::internal::jsonify(t, JSON::internal::Prefer());
+}
+
+#endif // __STOUT_JSONIFY__
http://git-wip-us.apache.org/repos/asf/mesos/blob/42cf29ec/3rdparty/libprocess/3rdparty/stout/include/stout/protobuf.hpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/include/stout/protobuf.hpp b/3rdparty/libprocess/3rdparty/stout/include/stout/protobuf.hpp
index 017cef4..6d7d033 100644
--- a/3rdparty/libprocess/3rdparty/stout/include/stout/protobuf.hpp
+++ b/3rdparty/libprocess/3rdparty/stout/include/stout/protobuf.hpp
@@ -36,6 +36,7 @@
#include <stout/base64.hpp>
#include <stout/error.hpp>
#include <stout/json.hpp>
+#include <stout/jsonify.hpp>
#include <stout/none.hpp>
#include <stout/nothing.hpp>
#include <stout/result.hpp>
@@ -619,6 +620,135 @@ Try<T> parse(const JSON::Value& value)
namespace JSON {
+// `json` function for protobuf messages. Refer to `jsonify.hpp` for details.
+// TODO(mpark): This currently uses the default value for optional fields with
+// a default that are not set, but we may want to revisit this decision.
+inline void json(ObjectWriter* writer, const google::protobuf::Message& message)
+{
+ using google::protobuf::FieldDescriptor;
+
+ const google::protobuf::Descriptor* descriptor = message.GetDescriptor();
+ const google::protobuf::Reflection* reflection = message.GetReflection();
+
+ // We first look through all the possible fields to determine both the set
+ // fields __and__ the optional fields with a default that are not set.
+ // `Reflection::ListFields()` alone will only include set fields and
+ // is therefore insufficient.
+ int fieldCount = descriptor->field_count();
+ std::vector<const FieldDescriptor*> fields;
+ fields.reserve(fieldCount);
+ for (int i = 0; i < fieldCount; ++i) {
+ const FieldDescriptor* field = descriptor->field(i);
+ if (field->is_repeated()) {
+ if (reflection->FieldSize(message, field) > 0) {
+ // Has repeated field with members, output as JSON.
+ fields.push_back(field);
+ }
+ } else if (reflection->HasField(message, field) ||
+ field->has_default_value()) {
+ // Field is set or has default, output as JSON.
+ fields.push_back(field);
+ }
+ }
+
+ foreach (const FieldDescriptor* field, fields) {
+ if (field->is_repeated()) {
+ writer->field(
+ field->name(),
+ [&field, &reflection, &message](JSON::ArrayWriter* writer) {
+ int fieldSize = reflection->FieldSize(message, field);
+ for (int i = 0; i < fieldSize; ++i) {
+ switch (field->cpp_type()) {
+ case FieldDescriptor::CPPTYPE_BOOL:
+ writer->element(
+ reflection->GetRepeatedBool(message, field, i));
+ break;
+ case FieldDescriptor::CPPTYPE_INT32:
+ writer->element(
+ reflection->GetRepeatedInt32(message, field, i));
+ break;
+ case FieldDescriptor::CPPTYPE_INT64:
+ writer->element(
+ reflection->GetRepeatedInt64(message, field, i));
+ break;
+ case FieldDescriptor::CPPTYPE_UINT32:
+ writer->element(
+ reflection->GetRepeatedUInt32(message, field, i));
+ break;
+ case FieldDescriptor::CPPTYPE_UINT64:
+ writer->element(
+ reflection->GetRepeatedUInt64(message, field, i));
+ break;
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ writer->element(
+ reflection->GetRepeatedFloat(message, field, i));
+ break;
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ writer->element(
+ reflection->GetRepeatedDouble(message, field, i));
+ break;
+ case FieldDescriptor::CPPTYPE_MESSAGE:
+ writer->element(
+ reflection->GetRepeatedMessage(message, field, i));
+ break;
+ case FieldDescriptor::CPPTYPE_ENUM:
+ writer->element(
+ reflection->GetRepeatedEnum(message, field, i)->name());
+ break;
+ case FieldDescriptor::CPPTYPE_STRING:
+ std::string s =
+ reflection->GetRepeatedString(message, field, i);
+ if (field->type() == FieldDescriptor::TYPE_BYTES) {
+ s = base64::encode(s);
+ }
+ writer->element(s);
+ break;
+ }
+ }
+ });
+ } else {
+ switch (field->cpp_type()) {
+ case FieldDescriptor::CPPTYPE_BOOL:
+ writer->field(field->name(), reflection->GetBool(message, field));
+ break;
+ case FieldDescriptor::CPPTYPE_INT32:
+ writer->field(field->name(), reflection->GetInt32(message, field));
+ break;
+ case FieldDescriptor::CPPTYPE_INT64:
+ writer->field(field->name(), reflection->GetInt64(message, field));
+ break;
+ case FieldDescriptor::CPPTYPE_UINT32:
+ writer->field(field->name(), reflection->GetUInt32(message, field));
+ break;
+ case FieldDescriptor::CPPTYPE_UINT64:
+ writer->field(field->name(), reflection->GetUInt64(message, field));
+ break;
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ writer->field(field->name(), reflection->GetFloat(message, field));
+ break;
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ writer->field(field->name(), reflection->GetDouble(message, field));
+ break;
+ case FieldDescriptor::CPPTYPE_MESSAGE:
+ writer->field(field->name(), reflection->GetMessage(message, field));
+ break;
+ case FieldDescriptor::CPPTYPE_ENUM:
+ writer->field(
+ field->name(), reflection->GetEnum(message, field)->name());
+ break;
+ case FieldDescriptor::CPPTYPE_STRING:
+ std::string str = reflection->GetString(message, field);
+ if (field->type() == FieldDescriptor::TYPE_BYTES) {
+ str = base64::encode(str);
+ }
+ writer->field(field->name(), str);
+ break;
+ }
+ }
+ }
+}
+
+
// TODO(bmahler): This currently uses the default value for optional
// fields but we may want to revisit this decision.
inline Object protobuf(const google::protobuf::Message& message)
http://git-wip-us.apache.org/repos/asf/mesos/blob/42cf29ec/3rdparty/libprocess/3rdparty/stout/tests/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/tests/CMakeLists.txt b/3rdparty/libprocess/3rdparty/stout/tests/CMakeLists.txt
index 62ad461..ebf9795 100644
--- a/3rdparty/libprocess/3rdparty/stout/tests/CMakeLists.txt
+++ b/3rdparty/libprocess/3rdparty/stout/tests/CMakeLists.txt
@@ -29,6 +29,7 @@ set(STOUT_TESTS_SRC
interval_tests.cpp
ip_tests.cpp
json_tests.cpp
+ jsonify_tests.cpp
linkedhashmap_tests.cpp
main.cpp
multimap_tests.cpp
http://git-wip-us.apache.org/repos/asf/mesos/blob/42cf29ec/3rdparty/libprocess/3rdparty/stout/tests/jsonify_tests.cpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/tests/jsonify_tests.cpp b/3rdparty/libprocess/3rdparty/stout/tests/jsonify_tests.cpp
new file mode 100644
index 0000000..d06eba3
--- /dev/null
+++ b/3rdparty/libprocess/3rdparty/stout/tests/jsonify_tests.cpp
@@ -0,0 +1,164 @@
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <stout/jsonify.hpp>
+
+using std::map;
+using std::multimap;
+using std::set;
+using std::string;
+using std::vector;
+
+// Tests that booleans are jsonified correctly.
+TEST(JsonifyTest, Boolean)
+{
+ EXPECT_EQ("true", string(jsonify(true)));
+ EXPECT_EQ("false", string(jsonify(false)));
+}
+
+
+// Tests that numbers are jsonified correctly.
+TEST(JsonifyTest, Number)
+{
+ // Test whole numbers (as doubles).
+ EXPECT_EQ("0.0", string(jsonify(0.0)));
+ EXPECT_EQ("1.0", string(jsonify(1.0)));
+
+ // Negative.
+ EXPECT_EQ("-1.0", string(jsonify(-1.0)));
+
+ // Test integers.
+ EXPECT_EQ("0", string(jsonify(0)));
+ EXPECT_EQ("2", string(jsonify(2)));
+ EXPECT_EQ("-2", string(jsonify(-2)));
+
+ // Expect at least 15 digits of precision.
+ EXPECT_EQ("1234567890.12345", string(jsonify(1234567890.12345)));
+}
+
+
+// Tests that strings are jsonified correctly, including escaping.
+TEST(JsonifyTest, String)
+{
+ EXPECT_EQ("\"hello world!\"", string(jsonify("hello world!")));
+ EXPECT_EQ(
+ "\"\\\"\\\\\\/\\b\\f\\n\\r\\t\\u0000\\u0019 !#[]\\u007f\xFF\"",
+ string(jsonify(string("\"\\/\b\f\n\r\t\x00\x19 !#[]\x7F\xFF", 17))));
+}
+
+
+namespace store {
+
+// A simple object consisting of primitive types.
+struct Name
+{
+ string first;
+ string last;
+};
+
+
+// A simple object consisting of primitive types as well as a sub-object.
+struct Customer
+{
+ Name name;
+ int age;
+};
+
+
+// `json` overload for `Name`.
+void json(JSON::ObjectWriter* writer, const Name& name)
+{
+ writer->field("first_name", name.first);
+ writer->field("last_name", name.last);
+}
+
+
+// `json` overload for `Customer`.
+void json(JSON::ObjectWriter* writer, const Customer& customer)
+{
+ json(writer, customer.name); // Composition of `json` functions!
+ writer->field("age", customer.age);
+}
+
+} // namespace store {
+
+
+// Tests that objects are jsonified correctly.
+TEST(JsonifyTest, Object)
+{
+ store::Name name{"michael", "park"};
+ EXPECT_EQ(
+ "{\"first_name\":\"michael\",\"last_name\":\"park\"}",
+ string(jsonify(name)));
+
+ store::Customer customer{name, 25};
+ EXPECT_EQ(
+ "{\"first_name\":\"michael\",\"last_name\":\"park\",\"age\":25}",
+ string(jsonify(customer)));
+}
+
+
+// Tests that iterable types are jsonified as array correctly.
+TEST(JsonifyTest, Array)
+{
+ bool booleans[] = {true, true, false};
+ EXPECT_EQ("[true,true,false]", string(jsonify(booleans)));
+
+ vector<int> numbers = {1, 2, 3};
+ EXPECT_EQ("[1,2,3]", string(jsonify(numbers)));
+
+ set<string> strings = {"there", "hello"};
+ EXPECT_EQ("[\"hello\",\"there\"]", string(jsonify(strings)));
+
+ vector<set<int>> numbers_list = {{1, 2, 3}, {1, 1, 1}};
+ EXPECT_EQ("[[1,2,3],[1]]", string(jsonify(numbers_list)));
+
+ vector<store::Customer> names = {{{"michael", "park"}, 25}};
+ EXPECT_EQ(
+ "[{\"first_name\":\"michael\",\"last_name\":\"park\",\"age\":25}]",
+ string(jsonify(names)));
+}
+
+
+// Tests that dictionary types of primitive a member typedef `mapped_type` are
+// considered dictionaries and therefore are jsonified as objects correctly.
+TEST(JsonifyTest, Dictionary)
+{
+ map<string, bool> booleans = {{"x", true}, {"y", false}};
+ EXPECT_EQ("{\"x\":true,\"y\":false}", string(jsonify(booleans)));
+
+ map<string, map<string, int>> nested_numbers = {{"foo", {{"x", 1}}}};
+ EXPECT_EQ("{\"foo\":{\"x\":1}}", string(jsonify(nested_numbers)));
+
+ multimap<string, store::Name> names = {
+ {"kobe", {"kobe", "bryant"}},
+ {"michael", {"michael", "jordan"}},
+ {"michael", {"michael", "park"}}
+ };
+
+ string expected = strings::remove(
+ "{"
+ " \"kobe\":{\"first_name\":\"kobe\",\"last_name\":\"bryant\"},"
+ " \"michael\":{\"first_name\":\"michael\",\"last_name\":\"jordan\"},"
+ " \"michael\":{\"first_name\":\"michael\",\"last_name\":\"park\"}"
+ "}",
+ " ");
+
+ EXPECT_EQ(expected, string(jsonify(names)));
+}
http://git-wip-us.apache.org/repos/asf/mesos/blob/42cf29ec/3rdparty/libprocess/3rdparty/stout/tests/protobuf_tests.cpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/tests/protobuf_tests.cpp b/3rdparty/libprocess/3rdparty/stout/tests/protobuf_tests.cpp
index 34bb252..8dd9cfd 100644
--- a/3rdparty/libprocess/3rdparty/stout/tests/protobuf_tests.cpp
+++ b/3rdparty/libprocess/3rdparty/stout/tests/protobuf_tests.cpp
@@ -19,6 +19,7 @@
#include <stout/gtest.hpp>
#include <stout/json.hpp>
+#include <stout/jsonify.hpp>
#include <stout/protobuf.hpp>
#include <stout/stringify.hpp>
#include <stout/strings.hpp>
@@ -414,3 +415,182 @@ TEST(ProtobufTest, ParseJSONNestedError)
EXPECT_TRUE(strings::contains(
parse.error(), "Not expecting a JSON number for field"));
}
+
+
+TEST(ProtobufTest, Jsonify)
+{
+ tests::Message message;
+ message.set_b(true);
+ message.set_str("string");
+ message.set_bytes("bytes");
+ message.set_int32(-1);
+ message.set_int64(-1);
+ message.set_uint32(1);
+ message.set_uint64(1);
+ message.set_sint32(-1);
+ message.set_sint64(-1);
+ message.set_f(1.0);
+ message.set_d(1.0);
+ message.set_e(tests::ONE);
+ message.mutable_nested()->set_str("nested");
+ message.add_repeated_bool(true);
+ message.add_repeated_string("repeated_string");
+ message.add_repeated_bytes("repeated_bytes");
+ message.add_repeated_int32(-2);
+ message.add_repeated_int64(-2);
+ message.add_repeated_uint32(2);
+ message.add_repeated_uint64(2);
+ message.add_repeated_sint32(-2);
+ message.add_repeated_sint64(-2);
+ message.add_repeated_float(1.0);
+ message.add_repeated_double(1.0);
+ message.add_repeated_double(2.0);
+ message.add_repeated_enum(tests::TWO);
+ message.add_repeated_nested()->set_str("repeated_nested");
+
+ // TODO(bmahler): To dynamically generate a protobuf message,
+ // see the commented-out code below.
+// DescriptorProto proto;
+//
+// proto.set_name("Message");
+//
+// FieldDescriptorProto* field = proto.add_field();
+// field->set_name("str");
+// field->set_type(FieldDescriptorProto::TYPE_STRING);
+//
+// const Descriptor* descriptor = proto.descriptor();
+//
+// DynamicMessageFactory factory;
+// Message* message = factory.GetPrototype(descriptor);
+//
+// Reflection* message.getReflection();
+
+ // The keys are in alphabetical order.
+ string expected = strings::remove(
+ "{"
+ " \"b\": true,"
+ " \"str\": \"string\","
+ " \"bytes\": \"Ynl0ZXM=\","
+ " \"int32\": -1,"
+ " \"int64\": -1,"
+ " \"uint32\": 1,"
+ " \"uint64\": 1,"
+ " \"sint32\": -1,"
+ " \"sint64\": -1,"
+ " \"f\": 1.0,"
+ " \"d\": 1.0,"
+ " \"e\": \"ONE\","
+ " \"nested\": { \"str\": \"nested\"},"
+ " \"repeated_bool\": [true],"
+ " \"repeated_string\": [\"repeated_string\"],"
+ " \"repeated_bytes\": [\"cmVwZWF0ZWRfYnl0ZXM=\"],"
+ " \"repeated_int32\": [-2],"
+ " \"repeated_int64\": [-2],"
+ " \"repeated_uint32\": [2],"
+ " \"repeated_uint64\": [2],"
+ " \"repeated_sint32\": [-2],"
+ " \"repeated_sint64\": [-2],"
+ " \"repeated_float\": [1.0],"
+ " \"repeated_double\": [1.0, 2.0],"
+ " \"repeated_enum\": [\"TWO\"],"
+ " \"repeated_nested\": [ { \"str\": \"repeated_nested\" } ],"
+ " \"optional_default\": 42.0"
+ "}",
+ " ");
+
+ EXPECT_EQ(expected, string(jsonify(message)));
+}
+
+
+TEST(ProtobufTest, JsonifyArray)
+{
+ tests::SimpleMessage message1;
+ message1.set_id("message1");
+ message1.add_numbers(1);
+ message1.add_numbers(2);
+
+ // Messages with different IDs are not equal.
+ tests::SimpleMessage message2;
+ message2.set_id("message2");
+ message2.add_numbers(1);
+ message2.add_numbers(2);
+
+ // The keys are in alphabetical order.
+ string expected = strings::remove(
+ "["
+ " {"
+ " \"id\": \"message1\","
+ " \"numbers\": [1, 2]"
+ " },"
+ " {"
+ " \"id\": \"message2\","
+ " \"numbers\": [1, 2]"
+ " }"
+ "]",
+ " ");
+
+ tests::ArrayMessage arrayMessage;
+ arrayMessage.add_values()->CopyFrom(message1);
+ arrayMessage.add_values()->CopyFrom(message2);
+
+ EXPECT_EQ(expected, string(jsonify(arrayMessage.values())));
+}
+
+
+// Tests that integer precision is maintained between
+// JSON <-> Protobuf conversions.
+TEST(ProtobufTest, JsonifyLargeIntegers)
+{
+ // These numbers are equal or close to the integer limits.
+ tests::Message message;
+ message.set_int32(-2147483647);
+ message.set_int64(-9223372036854775807);
+ message.set_uint32(4294967295U);
+ message.set_uint64(9223372036854775807);
+ message.set_sint32(-1234567890);
+ message.set_sint64(-1234567890123456789);
+ message.add_repeated_int32(-2000000000);
+ message.add_repeated_int64(-9000000000000000000);
+ message.add_repeated_uint32(3000000000U);
+ message.add_repeated_uint64(7000000000000000000);
+ message.add_repeated_sint32(-1000000000);
+ message.add_repeated_sint64(-8000000000000000000);
+
+ // Parts of the protobuf that are required. Copied from the above test.
+ message.set_b(true);
+ message.set_str("string");
+ message.set_bytes("bytes");
+ message.set_f(1.0);
+ message.set_d(1.0);
+ message.set_e(tests::ONE);
+ message.mutable_nested()->set_str("nested");
+
+ // The keys are in alphabetical order.
+ string expected = strings::remove(
+ "{"
+ " \"b\": true,"
+ " \"str\": \"string\","
+ " \"bytes\": \"Ynl0ZXM=\","
+ " \"int32\": -2147483647,"
+ " \"int64\": -9223372036854775807,"
+ " \"uint32\": 4294967295,"
+ " \"uint64\": 9223372036854775807,"
+ " \"sint32\": -1234567890,"
+ " \"sint64\": -1234567890123456789,"
+ " \"f\": 1.0,"
+ " \"d\": 1.0,"
+ " \"e\": \"ONE\","
+ " \"nested\": {\"str\": \"nested\"},"
+ " \"repeated_int32\": [-2000000000],"
+ " \"repeated_int64\": [-9000000000000000000],"
+ " \"repeated_uint32\": [3000000000],"
+ " \"repeated_uint64\": [7000000000000000000],"
+ " \"repeated_sint32\": [-1000000000],"
+ " \"repeated_sint64\": [-8000000000000000000],"
+ " \"optional_default\": 42.0"
+ "}",
+ " ");
+
+ // Check JSON -> String.
+ EXPECT_EQ(expected, string(jsonify(message)));
+}
[2/4] mesos git commit: Added support for `jsonify` result to `OK`
response in libprocess.
Posted by mp...@apache.org.
Added support for `jsonify` result to `OK` response in libprocess.
Review: https://reviews.apache.org/r/41594/
Project: http://git-wip-us.apache.org/repos/asf/mesos/repo
Commit: http://git-wip-us.apache.org/repos/asf/mesos/commit/fb599902
Tree: http://git-wip-us.apache.org/repos/asf/mesos/tree/fb599902
Diff: http://git-wip-us.apache.org/repos/asf/mesos/diff/fb599902
Branch: refs/heads/master
Commit: fb59990227f5218bf1070c49145f2c0797ee5ac4
Parents: 42cf29e
Author: Michael Park <mp...@apache.org>
Authored: Tue Dec 8 09:25:39 2015 -0500
Committer: Michael Park <mp...@apache.org>
Committed: Fri Jan 15 09:37:41 2016 -0800
----------------------------------------------------------------------
3rdparty/libprocess/3rdparty/Makefile.am | 1 +
3rdparty/libprocess/include/process/http.hpp | 3 +++
3rdparty/libprocess/src/http.cpp | 25 +++++++++++++++++++++++
3 files changed, 29 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/mesos/blob/fb599902/3rdparty/libprocess/3rdparty/Makefile.am
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/Makefile.am b/3rdparty/libprocess/3rdparty/Makefile.am
index 084475a..596905a 100644
--- a/3rdparty/libprocess/3rdparty/Makefile.am
+++ b/3rdparty/libprocess/3rdparty/Makefile.am
@@ -172,6 +172,7 @@ stout_tests_SOURCES = \
$(STOUT)/tests/interval_tests.cpp \
$(STOUT)/tests/ip_tests.cpp \
$(STOUT)/tests/json_tests.cpp \
+ $(STOUT)/tests/jsonify_tests.cpp \
$(STOUT)/tests/linkedhashmap_tests.cpp \
$(STOUT)/tests/mac_tests.cpp \
$(STOUT)/tests/main.cpp \
http://git-wip-us.apache.org/repos/asf/mesos/blob/fb599902/3rdparty/libprocess/include/process/http.hpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/include/process/http.hpp b/3rdparty/libprocess/include/process/http.hpp
index d0f820e..1fe549e 100644
--- a/3rdparty/libprocess/include/process/http.hpp
+++ b/3rdparty/libprocess/include/process/http.hpp
@@ -35,6 +35,7 @@
#include <stout/hashmap.hpp>
#include <stout/ip.hpp>
#include <stout/json.hpp>
+#include <stout/jsonify.hpp>
#include <stout/none.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
@@ -491,6 +492,8 @@ struct OK : Response
explicit OK(const std::string& body) : Response(body, Status::OK) {}
OK(const JSON::Value& value, const Option<std::string>& jsonp = None());
+
+ OK(JSON::Proxy&& value, const Option<std::string>& jsonp = None());
};
http://git-wip-us.apache.org/repos/asf/mesos/blob/fb599902/3rdparty/libprocess/src/http.cpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/src/http.cpp b/3rdparty/libprocess/src/http.cpp
index aabfd5d..40fd87c 100644
--- a/3rdparty/libprocess/src/http.cpp
+++ b/3rdparty/libprocess/src/http.cpp
@@ -566,6 +566,31 @@ OK::OK(const JSON::Value& value, const Option<string>& jsonp)
body = out.str().data();
}
+
+OK::OK(JSON::Proxy&& value, const Option<std::string>& jsonp)
+ : Response(Status::OK)
+{
+ type = BODY;
+
+ std::ostringstream out;
+
+ if (jsonp.isSome()) {
+ out << jsonp.get() << "(";
+ }
+
+ out << std::move(value);
+
+ if (jsonp.isSome()) {
+ out << ");";
+ headers["Content-Type"] = "text/javascript";
+ } else {
+ headers["Content-Type"] = "application/json";
+ }
+
+ body = out.str();
+ headers["Content-Length"] = stringify(body.size());
+}
+
namespace path {
Try<hashmap<string, string>> parse(const string& pattern, const string& path)
[4/4] mesos git commit: Updated `Master::Http::state` to use
`jsonify` in mesos.
Posted by mp...@apache.org.
Updated `Master::Http::state` to use `jsonify` in mesos.
Review: https://reviews.apache.org/r/41595/
Project: http://git-wip-us.apache.org/repos/asf/mesos/repo
Commit: http://git-wip-us.apache.org/repos/asf/mesos/commit/e8af5cca
Tree: http://git-wip-us.apache.org/repos/asf/mesos/tree/e8af5cca
Diff: http://git-wip-us.apache.org/repos/asf/mesos/diff/e8af5cca
Branch: refs/heads/master
Commit: e8af5cca9bbc7e0ab96749e42b584c09554b2347
Parents: 69188c5
Author: Michael Park <mp...@apache.org>
Authored: Tue Dec 8 09:25:43 2015 -0500
Committer: Michael Park <mp...@apache.org>
Committed: Fri Jan 15 09:37:47 2016 -0800
----------------------------------------------------------------------
src/common/http.cpp | 184 +++++++++++++++++++++++
src/common/http.hpp | 10 ++
src/master/http.cpp | 381 +++++++++++++++++++++++++++++++++--------------
3 files changed, 467 insertions(+), 108 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/mesos/blob/e8af5cca/src/common/http.cpp
----------------------------------------------------------------------
diff --git a/src/common/http.cpp b/src/common/http.cpp
index 7165551..6d88091 100644
--- a/src/common/http.cpp
+++ b/src/common/http.cpp
@@ -396,5 +396,189 @@ JSON::Object model(
return object;
}
+
+void json(JSON::ObjectWriter* writer, const Task& task)
+{
+ writer->field("id", task.task_id().value());
+ writer->field("name", task.name());
+ writer->field("framework_id", task.framework_id().value());
+ writer->field("executor_id", task.executor_id().value());
+ writer->field("slave_id", task.slave_id().value());
+ writer->field("state", TaskState_Name(task.state()));
+ writer->field("resources", Resources(task.resources()));
+ writer->field("statuses", task.statuses());
+
+ if (task.has_labels()) {
+ writer->field("labels", task.labels());
+ }
+
+ if (task.has_discovery()) {
+ writer->field("discovery", task.discovery());
+ }
+
+ if (task.has_container()) {
+ writer->field("container", task.container());
+ }
+}
+
} // namespace internal {
+
+void json(JSON::ObjectWriter* writer, const Attributes& attributes)
+{
+ foreach (const Attribute& attribute, attributes) {
+ switch (attribute.type()) {
+ case Value::SCALAR:
+ writer->field(attribute.name(), attribute.scalar());
+ break;
+ case Value::RANGES:
+ writer->field(attribute.name(), attribute.ranges());
+ break;
+ case Value::SET:
+ writer->field(attribute.name(), attribute.set());
+ break;
+ case Value::TEXT:
+ writer->field(attribute.name(), attribute.text());
+ break;
+ default:
+ LOG(FATAL) << "Unexpected Value type: " << attribute.type();
+ }
+ }
+}
+
+
+void json(JSON::ObjectWriter* writer, const CommandInfo& command)
+{
+ if (command.has_shell()) {
+ writer->field("shell", command.shell());
+ }
+
+ if (command.has_value()) {
+ writer->field("value", command.value());
+ }
+
+ writer->field("argv", command.arguments());
+
+ if (command.has_environment()) {
+ writer->field("environment", command.environment());
+ }
+
+ writer->field("uris", [&command](JSON::ArrayWriter* writer) {
+ foreach (const CommandInfo::URI& uri, command.uris()) {
+ writer->element([&uri](JSON::ObjectWriter* writer) {
+ writer->field("value", uri.value());
+ writer->field("executable", uri.executable());
+ });
+ }
+ });
+}
+
+
+void json(JSON::ObjectWriter* writer, const ExecutorInfo& executorInfo)
+{
+ writer->field("executor_id", executorInfo.executor_id().value());
+ writer->field("name", executorInfo.name());
+ writer->field("framework_id", executorInfo.framework_id().value());
+ writer->field("command", executorInfo.command());
+ writer->field("resources", Resources(executorInfo.resources()));
+}
+
+
+void json(JSON::ArrayWriter* writer, const Labels& labels)
+{
+ json(writer, labels.labels());
+}
+
+
+void json(JSON::ObjectWriter* writer, const NetworkInfo& info)
+{
+ if (info.has_ip_address()) {
+ writer->field("ip_address", info.ip_address());
+ }
+
+ if (info.groups().size() > 0) {
+ writer->field("groups", info.groups());
+ }
+
+ if (info.has_labels()) {
+ writer->field("labels", info.labels());
+ }
+
+ if (info.ip_addresses().size() > 0) {
+ writer->field("ip_addresses", info.ip_addresses());
+ }
+}
+
+
+void json(JSON::ObjectWriter* writer, const Resources& resources)
+{
+ hashmap<std::string, double> scalars = {{"cpus", 0}, {"mem", 0}, {"disk", 0}};
+ hashmap<std::string, Value::Ranges> ranges;
+ hashmap<std::string, Value::Set> sets;
+
+ foreach (const Resource& resource, resources) {
+ std::string name =
+ resource.name() + (Resources::isRevocable(resource) ? "_revocable" : "");
+ switch (resource.type()) {
+ case Value::SCALAR:
+ scalars[name] += resource.scalar().value();
+ break;
+ case Value::RANGES:
+ ranges[name] += resource.ranges();
+ break;
+ case Value::SET:
+ sets[name] += resource.set();
+ break;
+ default:
+ LOG(FATAL) << "Unexpected Value type: " << resource.type();
+ }
+ }
+
+ json(writer, scalars);
+ json(writer, ranges);
+ json(writer, sets);
+}
+
+
+void json(JSON::ObjectWriter* writer, const TaskStatus& status)
+{
+ writer->field("state", TaskState_Name(status.state()));
+ writer->field("timestamp", status.timestamp());
+
+ if (status.has_labels()) {
+ writer->field("labels", status.labels());
+ }
+
+ if (status.has_container_status()) {
+ writer->field("container_status", status.container_status());
+ }
+
+ if (status.has_healthy()) {
+ writer->field("healthy", status.healthy());
+ }
+}
+
+
+void json(JSON::NumberWriter* writer, const Value::Scalar& scalar)
+{
+ writer->set(scalar.value());
+}
+
+
+void json(JSON::StringWriter* writer, const Value::Ranges& ranges)
+{
+ writer->append(stringify(ranges));
+}
+
+
+void json(JSON::StringWriter* writer, const Value::Set& set)
+{
+ writer->append(stringify(set));
+}
+
+
+void json(JSON::StringWriter* writer, const Value::Text& text)
+{
+ writer->append(text.value());
+}
+
} // namespace mesos {
http://git-wip-us.apache.org/repos/asf/mesos/blob/e8af5cca/src/common/http.hpp
----------------------------------------------------------------------
diff --git a/src/common/http.hpp b/src/common/http.hpp
index 4f4cbf6..f88590f 100644
--- a/src/common/http.hpp
+++ b/src/common/http.hpp
@@ -24,6 +24,7 @@
#include <stout/hashmap.hpp>
#include <stout/json.hpp>
+#include <stout/jsonify.hpp>
#include <stout/protobuf.hpp>
namespace mesos {
@@ -88,7 +89,16 @@ JSON::Object model(
const TaskState& state,
const std::vector<TaskStatus>& statuses);
+
+void json(JSON::ObjectWriter* writer, const Task& task);
+
} // namespace internal {
+
+void json(JSON::ObjectWriter* writer, const Attributes& attributes);
+void json(JSON::ArrayWriter* writer, const Labels& labels);
+void json(JSON::ObjectWriter* writer, const Resources& resources);
+void json(JSON::ObjectWriter* writer, const TaskStatus& status);
+
} // namespace mesos {
#endif // __COMMON_HTTP_HPP__
http://git-wip-us.apache.org/repos/asf/mesos/blob/e8af5cca/src/master/http.cpp
----------------------------------------------------------------------
diff --git a/src/master/http.cpp b/src/master/http.cpp
index bcafc7a..e6ba311 100644
--- a/src/master/http.cpp
+++ b/src/master/http.cpp
@@ -42,12 +42,14 @@
#include <stout/hashmap.hpp>
#include <stout/hashset.hpp>
#include <stout/json.hpp>
+#include <stout/jsonify.hpp>
#include <stout/lambda.hpp>
#include <stout/net.hpp>
#include <stout/nothing.hpp>
#include <stout/numify.hpp>
#include <stout/os.hpp>
#include <stout/protobuf.hpp>
+#include <stout/representation.hpp>
#include <stout/result.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>
@@ -103,6 +105,22 @@ using std::vector;
namespace mesos {
+
+void json(
+ JSON::StringWriter* writer, const FrameworkInfo::Capability& capability)
+{
+ writer->append(FrameworkInfo::Capability::Type_Name(capability.type()));
+}
+
+
+void json(JSON::ObjectWriter* writer, const Offer& offer)
+{
+ writer->field("id", offer.id().value());
+ writer->field("framework_id", offer.framework_id().value());
+ writer->field("slave_id", offer.slave_id().value());
+ writer->field("resources", Resources(offer.resources()));
+}
+
namespace internal {
namespace master {
@@ -115,6 +133,177 @@ using process::http::Request;
using process::Owned;
+// The summary representation of `T` to support the `/state-summary` endpoint.
+// e.g., `Summary<Slave>`.
+template <typename T>
+struct Summary : Representation<T>
+{
+ using Representation<T>::Representation;
+};
+
+
+// The full representation of `T` to support the `/state` endpoint.
+// e.g., `Full<Slave>`.
+template <typename T>
+struct Full : Representation<T>
+{
+ using Representation<T>::Representation;
+};
+
+
+void json(JSON::ObjectWriter* writer, const Summary<Slave>& summary)
+{
+ const Slave& slave = summary;
+
+ writer->field("id", slave.id.value());
+ writer->field("pid", string(slave.pid));
+ writer->field("hostname", slave.info.hostname());
+ writer->field("registered_time", slave.registeredTime.secs());
+
+ if (slave.reregisteredTime.isSome()) {
+ writer->field("reregistered_time", slave.reregisteredTime.get().secs());
+ }
+
+ const Resources& totalResources = slave.totalResources;
+ writer->field("resources", totalResources);
+ writer->field("used_resources", Resources::sum(slave.usedResources));
+ writer->field("offered_resources", slave.offeredResources);
+ writer->field("reserved_resources", totalResources.reserved());
+ writer->field("unreserved_resources", totalResources.unreserved());
+
+ writer->field("attributes", Attributes(slave.info.attributes()));
+ writer->field("active", slave.active);
+ writer->field("version", slave.version);
+}
+
+
+void json(JSON::ObjectWriter* writer, const Full<Slave>& full)
+{
+ const Slave& slave = full;
+
+ json(writer, Summary<Slave>(slave));
+}
+
+
+void json(JSON::ObjectWriter* writer, const Summary<Framework>& summary)
+{
+ const Framework& framework = summary;
+
+ writer->field("id", framework.id().value());
+ writer->field("name", framework.info.name());
+
+ // Omit pid for http frameworks.
+ if (framework.pid.isSome()) {
+ writer->field("pid", string(framework.pid.get()));
+ }
+
+ // TODO(bmahler): Use these in the webui.
+ writer->field("used_resources", framework.totalUsedResources);
+ writer->field("offered_resources", framework.totalOfferedResources);
+ writer->field("capabilities", framework.info.capabilities());
+ writer->field("hostname", framework.info.hostname());
+ writer->field("webui_url", framework.info.webui_url());
+ writer->field("active", framework.active);
+}
+
+
+void json(JSON::ObjectWriter* writer, const Full<Framework>& full)
+{
+ const Framework& framework = full;
+
+ json(writer, Summary<Framework>(framework));
+
+ // Add additional fields to those generated by 'summarize'.
+ writer->field("user", framework.info.user());
+ writer->field("failover_timeout", framework.info.failover_timeout());
+ writer->field("checkpoint", framework.info.checkpoint());
+ writer->field("role", framework.info.role());
+ writer->field("registered_time", framework.registeredTime.secs());
+ writer->field("unregistered_time", framework.unregisteredTime.secs());
+ writer->field("active", framework.active);
+
+ if (framework.info.has_principal()) {
+ writer->field("principal", framework.info.principal());
+ }
+
+ // TODO(bmahler): Consider deprecating this in favor of the split
+ // used and offered resources added in 'summarize'.
+ writer->field(
+ "resources",
+ framework.totalUsedResources + framework.totalOfferedResources);
+
+ // TODO(benh): Consider making reregisteredTime an Option.
+ if (framework.registeredTime != framework.reregisteredTime) {
+ writer->field("reregistered_time", framework.reregisteredTime.secs());
+ }
+
+ // Model all of the tasks associated with a framework.
+ writer->field("tasks", [&framework](JSON::ArrayWriter* writer) {
+ foreachvalue (const TaskInfo& taskInfo, framework.pendingTasks) {
+ writer->element([&framework, &taskInfo](JSON::ObjectWriter* writer) {
+ writer->field("id", taskInfo.task_id().value());
+ writer->field("name", taskInfo.name());
+ writer->field("framework_id", framework.id().value());
+
+ writer->field("executor_id", taskInfo.executor().executor_id().value());
+
+ writer->field("slave_id", taskInfo.slave_id().value());
+ writer->field("state", TaskState_Name(TASK_STAGING));
+ writer->field("resources", Resources(taskInfo.resources()));
+ writer->field("statuses", std::initializer_list<TaskStatus>{});
+
+ if (taskInfo.has_labels()) {
+ writer->field("labels", taskInfo.labels());
+ }
+
+ if (taskInfo.has_discovery()) {
+ writer->field("discovery", taskInfo.discovery());
+ }
+
+ if (taskInfo.has_container()) {
+ writer->field("container", taskInfo.container());
+ }
+ });
+ }
+
+ foreachvalue (Task* task, framework.tasks) {
+ writer->element(*task);
+ }
+ });
+
+ writer->field("completed_tasks", [&framework](JSON::ArrayWriter* writer) {
+ foreach (const std::shared_ptr<Task>& task, framework.completedTasks) {
+ writer->element(*task);
+ }
+ });
+
+ // Model all of the offers associated with a framework.
+ writer->field("offers", [&framework](JSON::ArrayWriter* writer) {
+ foreach (Offer* offer, framework.offers) {
+ writer->element(*offer);
+ }
+ });
+
+ // Model all of the executors of a framework.
+ writer->field("executors", [&framework](JSON::ArrayWriter* writer) {
+ foreachpair (
+ const SlaveID& slaveId, const auto& executorsMap, framework.executors) {
+ foreachvalue (const ExecutorInfo& executor, executorsMap) {
+ writer->element([&executor, &slaveId](JSON::ObjectWriter* writer) {
+ json(writer, executor);
+ writer->field("slave_id", slaveId.value());
+ });
+ }
+ }
+ });
+
+ // Model all of the labels associated with a framework.
+ if (framework.info.has_labels()) {
+ writer->field("labels", framework.info.labels());
+ }
+}
+
+
// TODO(bmahler): Kill these in favor of automatic Proto->JSON Conversion (when
// it becomes available).
@@ -1107,139 +1296,115 @@ string Master::Http::STATE_HELP()
Future<Response> Master::Http::state(const Request& request) const
{
- JSON::Object object;
- object.values["version"] = MESOS_VERSION;
+ auto state = [this](JSON::ObjectWriter* writer) {
+ writer->field("version", MESOS_VERSION);
- if (build::GIT_SHA.isSome()) {
- object.values["git_sha"] = build::GIT_SHA.get();
- }
-
- if (build::GIT_BRANCH.isSome()) {
- object.values["git_branch"] = build::GIT_BRANCH.get();
- }
-
- if (build::GIT_TAG.isSome()) {
- object.values["git_tag"] = build::GIT_TAG.get();
- }
-
- object.values["build_date"] = build::DATE;
- object.values["build_time"] = build::TIME;
- object.values["build_user"] = build::USER;
- object.values["start_time"] = master->startTime.secs();
-
- if (master->electedTime.isSome()) {
- object.values["elected_time"] = master->electedTime.get().secs();
- }
-
- object.values["id"] = master->info().id();
- object.values["pid"] = string(master->self());
- object.values["hostname"] = master->info().hostname();
- object.values["activated_slaves"] = master->_slaves_active();
- object.values["deactivated_slaves"] = master->_slaves_inactive();
-
- if (master->flags.cluster.isSome()) {
- object.values["cluster"] = master->flags.cluster.get();
- }
+ if (build::GIT_SHA.isSome()) {
+ writer->field("git_sha", build::GIT_SHA.get());
+ }
- if (master->leader.isSome()) {
- object.values["leader"] = master->leader.get().pid();
- }
+ if (build::GIT_BRANCH.isSome()) {
+ writer->field("git_branch", build::GIT_BRANCH.get());
+ }
- if (master->flags.log_dir.isSome()) {
- object.values["log_dir"] = master->flags.log_dir.get();
- }
+ if (build::GIT_TAG.isSome()) {
+ writer->field("git_tag", build::GIT_TAG.get());
+ }
- if (master->flags.external_log_file.isSome()) {
- object.values["external_log_file"] = master->flags.external_log_file.get();
- }
+ writer->field("build_date", build::DATE);
+ writer->field("build_time", build::TIME);
+ writer->field("build_user", build::USER);
+ writer->field("start_time", master->startTime.secs());
- {
- JSON::Object flags;
- foreachpair (const string& name, const flags::Flag& flag, master->flags) {
- Option<string> value = flag.stringify(master->flags);
- if (value.isSome()) {
- flags.values[name] = value.get();
- }
+ if (master->electedTime.isSome()) {
+ writer->field("elected_time", master->electedTime.get().secs());
}
- object.values["flags"] = std::move(flags);
- }
- // Model all of the slaves.
- {
- JSON::Array array;
- array.values.reserve(master->slaves.registered.size()); // MESOS-2353.
+ writer->field("id", master->info().id());
+ writer->field("pid", string(master->self()));
+ writer->field("hostname", master->info().hostname());
+ writer->field("activated_slaves", master->_slaves_active());
+ writer->field("deactivated_slaves", master->_slaves_inactive());
- foreachvalue (Slave* slave, master->slaves.registered) {
- array.values.push_back(model(*slave));
+ if (master->flags.cluster.isSome()) {
+ writer->field("cluster", master->flags.cluster.get());
}
- object.values["slaves"] = std::move(array);
- }
-
- // Model all of the frameworks.
- {
- JSON::Array array;
- array.values.reserve(master->frameworks.registered.size()); // MESOS-2353.
+ if (master->leader.isSome()) {
+ writer->field("leader", master->leader.get().pid());
+ }
- foreachvalue (Framework* framework, master->frameworks.registered) {
- array.values.push_back(model(*framework));
+ if (master->flags.log_dir.isSome()) {
+ writer->field("log_dir", master->flags.log_dir.get());
}
- object.values["frameworks"] = std::move(array);
- }
+ if (master->flags.external_log_file.isSome()) {
+ writer->field("external_log_file", master->flags.external_log_file.get());
+ }
- // Model all of the completed frameworks.
- {
- JSON::Array array;
- array.values.reserve(master->frameworks.completed.size()); // MESOS-2353.
+ writer->field("flags", [this](JSON::ObjectWriter* writer) {
+ foreachpair (const string& name, const flags::Flag& flag, master->flags) {
+ Option<string> value = flag.stringify(master->flags);
+ if (value.isSome()) {
+ writer->field(name, value.get());
+ }
+ }
+ });
- foreach (const std::shared_ptr<Framework>& framework,
- master->frameworks.completed) {
- array.values.push_back(model(*framework));
- }
+ // Model all of the slaves.
+ writer->field("slaves", [this](JSON::ArrayWriter* writer) {
+ foreachvalue (Slave* slave, master->slaves.registered) {
+ writer->element(Full<Slave>(*slave));
+ }
+ });
- object.values["completed_frameworks"] = std::move(array);
- }
+ // Model all of the frameworks.
+ writer->field("frameworks", [this](JSON::ArrayWriter* writer) {
+ foreachvalue (Framework* framework, master->frameworks.registered) {
+ writer->element(Full<Framework>(*framework));
+ }
+ });
- // Model all of the orphan tasks.
- {
- JSON::Array array;
+ // Model all of the completed frameworks.
+ writer->field("completed_frameworks", [this](JSON::ArrayWriter* writer) {
+ foreach (const std::shared_ptr<Framework>& framework,
+ master->frameworks.completed) {
+ writer->element(Full<Framework>(*framework));
+ }
+ });
- // Find those orphan tasks.
- foreachvalue (const Slave* slave, master->slaves.registered) {
- typedef hashmap<TaskID, Task*> TaskMap;
- foreachvalue (const TaskMap& tasks, slave->tasks) {
- foreachvalue (const Task* task, tasks) {
- CHECK_NOTNULL(task);
- if (!master->frameworks.registered.contains(task->framework_id())) {
- array.values.push_back(model(*task));
+ // Model all of the orphan tasks.
+ writer->field("orphan_tasks", [this](JSON::ArrayWriter* writer) {
+ // Find those orphan tasks.
+ foreachvalue (const Slave* slave, master->slaves.registered) {
+ typedef hashmap<TaskID, Task*> TaskMap;
+ foreachvalue (const TaskMap& tasks, slave->tasks) {
+ foreachvalue (const Task* task, tasks) {
+ CHECK_NOTNULL(task);
+ if (!master->frameworks.registered.contains(task->framework_id())) {
+ writer->element(*task);
+ }
}
}
}
- }
-
- object.values["orphan_tasks"] = std::move(array);
- }
-
- // Model all currently unregistered frameworks.
- // This could happen when the framework has yet to re-register
- // after master failover.
- {
- JSON::Array array;
+ });
- // Find unregistered frameworks.
- foreachvalue (const Slave* slave, master->slaves.registered) {
- foreachkey (const FrameworkID& frameworkId, slave->tasks) {
- if (!master->frameworks.registered.contains(frameworkId)) {
- array.values.push_back(frameworkId.value());
+ // Model all currently unregistered frameworks.
+ // This could happen when the framework has yet to re-register
+ // after master failover.
+ writer->field("unregistered_frameworks", [this](JSON::ArrayWriter* writer) {
+ // Find unregistered frameworks.
+ foreachvalue (const Slave* slave, master->slaves.registered) {
+ foreachkey (const FrameworkID& frameworkId, slave->tasks) {
+ if (!master->frameworks.registered.contains(frameworkId)) {
+ writer->element(frameworkId.value());
+ }
}
}
- }
-
- object.values["unregistered_frameworks"] = std::move(array);
- }
+ });
+ };
- return OK(object, request.url.query.get("jsonp"));
+ return OK(jsonify(state), request.url.query.get("jsonp"));
}
[3/4] mesos git commit: Added a `Representation` abstraction to stout.
Posted by mp...@apache.org.
Added a `Representation` abstraction to stout.
Review: https://reviews.apache.org/r/41946/
Project: http://git-wip-us.apache.org/repos/asf/mesos/repo
Commit: http://git-wip-us.apache.org/repos/asf/mesos/commit/69188c53
Tree: http://git-wip-us.apache.org/repos/asf/mesos/tree/69188c53
Diff: http://git-wip-us.apache.org/repos/asf/mesos/diff/69188c53
Branch: refs/heads/master
Commit: 69188c53d22df888c101970287cad03d60ec2ac4
Parents: fb59990
Author: Michael Park <mp...@apache.org>
Authored: Tue Jan 5 14:34:05 2016 -0800
Committer: Michael Park <mp...@apache.org>
Committed: Fri Jan 15 09:37:44 2016 -0800
----------------------------------------------------------------------
.../3rdparty/stout/include/Makefile.am | 1 +
.../stout/include/stout/representation.hpp | 83 ++++++++++++++++++++
2 files changed, 84 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/mesos/blob/69188c53/3rdparty/libprocess/3rdparty/stout/include/Makefile.am
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/include/Makefile.am b/3rdparty/libprocess/3rdparty/stout/include/Makefile.am
index 41c5435..e6d5b42 100644
--- a/3rdparty/libprocess/3rdparty/stout/include/Makefile.am
+++ b/3rdparty/libprocess/3rdparty/stout/include/Makefile.am
@@ -125,6 +125,7 @@ nobase_include_HEADERS = \
stout/posix/gzip.hpp \
stout/posix/os.hpp \
stout/recordio.hpp \
+ stout/representation.hpp \
stout/result.hpp \
stout/set.hpp \
stout/some.hpp \
http://git-wip-us.apache.org/repos/asf/mesos/blob/69188c53/3rdparty/libprocess/3rdparty/stout/include/stout/representation.hpp
----------------------------------------------------------------------
diff --git a/3rdparty/libprocess/3rdparty/stout/include/stout/representation.hpp b/3rdparty/libprocess/3rdparty/stout/include/stout/representation.hpp
new file mode 100644
index 0000000..22f70f7
--- /dev/null
+++ b/3rdparty/libprocess/3rdparty/stout/include/stout/representation.hpp
@@ -0,0 +1,83 @@
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef __STOUT_REPRESENTATION_HPP__
+#define __STOUT_REPRESENTATION_HPP__
+
+#include <functional>
+
+// The class template `Representation` is a generic base class to support types
+// that have multiple human-readable representations of itself.
+//
+// `Time` is a good example of such a type. Even though the __underlying__
+// representation may be a `std::chrono::time_point` or even a `time_t`, there
+// are multiple formats in which we can print them out.
+//
+// NOTE: These classes are light-weight objects that simply holds a reference to
+// a type `T`, and therefore cannot be used with a temporary.
+//
+// NOTE: The pattern is to inherit from `Representation`, and pull in
+// `Representation`'s constructors with using declarations. The explicit `using`
+// declarations are necessary since inheritance does not inherit the base class'
+// constructors. Also note that a type alias is not sufficient, since we need to
+// give rise to distinct types.
+//
+// Example:
+//
+// ```
+// // Two different representations of `Time`.
+//
+// struct RFC1123 : Representation<Time>
+// {
+// using Representation<Time>::Representation;
+// };
+//
+// struct RFC3339 : Representation<Time>
+// {
+// using Representation<Time>::Representation;
+// };
+//
+// // `operator<<` for the two different representations of `Time`.
+//
+// std::ostream& operator<<(std::ostream& stream, const RFC1123& rfc1123)
+// {
+// const Time& t = rfc1123;
+// // Print in `RFC1123` format.
+// }
+//
+// std::ostream& operator<<(std::ostream& stream, const RFC3339& rfc3339)
+// {
+// const Time& t = rfc1123;
+// // Print in `RFC3339` format.
+// }
+//
+// int main()
+// {
+// Time t = ...;
+// std::cout << RFC1123(t); // Print in `RFC1123` format.
+// std::cout << RFC3339(t); // Print in `RFC1123` format.
+// }
+// ```
+
+template <typename T>
+struct Representation : std::reference_wrapper<const T>
+{
+ // We pull in `std::reference_wrapper`'s constructors since inheritance does
+ // not inherit the base class' constructors.
+ using std::reference_wrapper<const T>::reference_wrapper;
+
+ // Disallow rebinding.
+ Representation& operator=(const Representation&) = delete;
+ Representation& operator=(Representation&&) = delete;
+};
+
+#endif // __STOUT_REPRESENTATION_HPP__