Fix fibers gdb utils script
[folly.git] / folly / Format.h
index dae9ae4b51d47b96fe2ead03d36d9d8a792c732d..c34f333978d3bd4f7a06f6c8483f14d881c5e3c5 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2013 Facebook, Inc.
+ * Copyright 2016 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * limitations under the License.
  */
 
-#ifndef FOLLY_FORMAT_H_
+#pragma once
 #define FOLLY_FORMAT_H_
 
-#include <array>
 #include <cstdio>
 #include <tuple>
 #include <type_traits>
-#include <vector>
-#include <deque>
-#include <map>
-#include <unordered_map>
-
-#include <double-conversion.h>
-
-#include "folly/FBVector.h"
-#include "folly/Conv.h"
-#include "folly/Range.h"
-#include "folly/Traits.h"
-#include "folly/Likely.h"
-#include "folly/String.h"
-#include "folly/small_vector.h"
-#include "folly/FormatArg.h"
+
+#include <folly/Conv.h>
+#include <folly/Range.h>
+#include <folly/Traits.h>
+#include <folly/String.h>
+#include <folly/FormatArg.h>
 
 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
 #pragma GCC diagnostic push
@@ -51,6 +41,11 @@ template <class C>
 Formatter<true, C> vformat(StringPiece fmt, C&& container);
 template <class T, class Enable=void> class FormatValue;
 
+// meta-attribute to identify formatters in this sea of template weirdness
+namespace detail {
+class FormatterTag {};
+};
+
 /**
  * Formatter class.
  *
@@ -59,12 +54,12 @@ template <class T, class Enable=void> class FormatValue;
  * this directly, you have to use format(...) below.
  */
 
-template <bool containerMode, class... Args>
-class Formatter {
-  template <class... A>
-  friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
-  template <class C>
-  friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
+/* BaseFormatter class. Currently, the only behavior that can be
+ * overridden is the actual formatting of positional parameters in
+ * `doFormatArg`. The Formatter class provides the default implementation.
+ */
+template <class Derived, bool containerMode, class... Args>
+class BaseFormatter {
  public:
   /**
    * Append to output.  out(StringPiece sp) may be called (more than once)
@@ -76,7 +71,7 @@ class Formatter {
    * Append to a string.
    */
   template <class Str>
-  typename std::enable_if<detail::IsSomeString<Str>::value>::type
+  typename std::enable_if<IsSomeString<Str>::value>::type
   appendTo(Str& str) const {
     auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
     (*this)(appender);
@@ -100,36 +95,28 @@ class Formatter {
     return s;
   }
 
- private:
-  explicit Formatter(StringPiece str, Args&&... args);
-
-  // Not copyable
-  Formatter(const Formatter&) = delete;
-  Formatter& operator=(const Formatter&) = delete;
-
-  // Movable, but the move constructor and assignment operator are private,
-  // for the exclusive use of format() (below).  This way, you can't create
-  // a Formatter object, but can handle references to it (for streaming,
-  // conversion to string, etc) -- which is good, as Formatter objects are
-  // dangerous (they hold references, possibly to temporaries)
-  Formatter(Formatter&&) = default;
-  Formatter& operator=(Formatter&&) = default;
+  /**
+   * metadata to identify generated children of BaseFormatter
+   */
+  typedef detail::FormatterTag IsFormatter;
+  typedef BaseFormatter BaseType;
 
+ private:
   typedef std::tuple<FormatValue<
       typename std::decay<Args>::type>...> ValueTuple;
   static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
 
   template <size_t K, class Callback>
   typename std::enable_if<K == valueCount>::type
-  doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
-    LOG(FATAL) << arg.errorStr("argument index out of range, max=", i);
+  doFormatFrom(size_t i, FormatArg& arg, Callback& /*cb*/) const {
+    arg.error("argument index out of range, max=", i);
   }
 
   template <size_t K, class Callback>
   typename std::enable_if<(K < valueCount)>::type
   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
     if (i == K) {
-      std::get<K>(values_).format(arg, cb);
+      static_cast<const Derived*>(this)->template doFormatArg<K>(arg, cb);
     } else {
       doFormatFrom<K+1>(i, arg, cb);
     }
@@ -140,10 +127,84 @@ class Formatter {
     return doFormatFrom<0>(i, arg, cb);
   }
 
+  template <size_t K>
+  typename std::enable_if<K == valueCount, int>::type
+  getSizeArgFrom(size_t i, const FormatArg& arg) const {
+    arg.error("argument index out of range, max=", i);
+  }
+
+  template <class T>
+  typename std::enable_if<std::is_integral<T>::value &&
+                          !std::is_same<T, bool>::value, int>::type
+  getValue(const FormatValue<T>& format, const FormatArg&) const {
+    return static_cast<int>(format.getValue());
+  }
+
+  template <class T>
+  typename std::enable_if<!std::is_integral<T>::value ||
+                          std::is_same<T, bool>::value, int>::type
+  getValue(const FormatValue<T>&, const FormatArg& arg) const {
+    arg.error("dynamic field width argument must be integral");
+  }
+
+  template <size_t K>
+  typename std::enable_if<K < valueCount, int>::type
+  getSizeArgFrom(size_t i, const FormatArg& arg) const {
+    if (i == K) {
+      return getValue(std::get<K>(values_), arg);
+    }
+    return getSizeArgFrom<K+1>(i, arg);
+  }
+
+  int getSizeArg(size_t i, const FormatArg& arg) const {
+    return getSizeArgFrom<0>(i, arg);
+  }
+
   StringPiece str_;
+
+ protected:
+  explicit BaseFormatter(StringPiece str, Args&&... args);
+
+  // Not copyable
+  BaseFormatter(const BaseFormatter&) = delete;
+  BaseFormatter& operator=(const BaseFormatter&) = delete;
+
+  // Movable, but the move constructor and assignment operator are private,
+  // for the exclusive use of format() (below).  This way, you can't create
+  // a Formatter object, but can handle references to it (for streaming,
+  // conversion to string, etc) -- which is good, as Formatter objects are
+  // dangerous (they hold references, possibly to temporaries)
+  BaseFormatter(BaseFormatter&&) = default;
+  BaseFormatter& operator=(BaseFormatter&&) = default;
+
   ValueTuple values_;
 };
 
+template <bool containerMode, class... Args>
+class Formatter : public BaseFormatter<Formatter<containerMode, Args...>,
+                                       containerMode,
+                                       Args...> {
+ private:
+  explicit Formatter(StringPiece& str, Args&&... args)
+      : BaseFormatter<Formatter<containerMode, Args...>,
+                      containerMode,
+                      Args...>(str, std::forward<Args>(args)...) {}
+
+  template <size_t K, class Callback>
+  void doFormatArg(FormatArg& arg, Callback& cb) const {
+    std::get<K>(this->values_).format(arg, cb);
+  }
+
+  friend class BaseFormatter<Formatter<containerMode, Args...>,
+                             containerMode,
+                             Args...>;
+
+  template <class... A>
+  friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
+  template <class C>
+  friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
+};
+
 /**
  * Formatter objects can be written to streams.
  */
@@ -158,8 +219,9 @@ std::ostream& operator<<(std::ostream& out,
 /**
  * Formatter objects can be written to stdio FILEs.
  */
-template<bool containerMode, class... Args>
-void writeTo(FILE* fp, const Formatter<containerMode, Args...>& formatter);
+template <class Derived, bool containerMode, class... Args>
+void writeTo(FILE* fp,
+             const BaseFormatter<Derived, containerMode, Args...>& formatter);
 
 /**
  * Create a formatter object.
@@ -174,6 +236,15 @@ Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
       fmt, std::forward<Args>(args)...);
 }
 
+/**
+ * Like format(), but immediately returns the formatted string instead of an
+ * intermediate format object.
+ */
+template <class... Args>
+inline std::string sformat(StringPiece fmt, Args&&... args) {
+  return format(fmt, std::forward<Args>(args)...).str();
+}
+
 /**
  * Create a formatter object that takes one argument (of container type)
  * and uses that container to get argument values from.
@@ -193,6 +264,40 @@ Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
       fmt, std::forward<Container>(container));
 }
 
+/**
+ * Like vformat(), but immediately returns the formatted string instead of an
+ * intermediate format object.
+ */
+template <class Container>
+inline std::string svformat(StringPiece fmt, Container&& container) {
+  return vformat(fmt, std::forward<Container>(container)).str();
+}
+
+/**
+ * Wrap a sequence or associative container so that out-of-range lookups
+ * return a default value rather than throwing an exception.
+ *
+ * Usage:
+ * format("[no_such_key"], defaulted(map, 42))  -> 42
+ */
+namespace detail {
+template <class Container, class Value> struct DefaultValueWrapper {
+  DefaultValueWrapper(const Container& container, const Value& defaultValue)
+    : container(container),
+      defaultValue(defaultValue) {
+  }
+
+  const Container& container;
+  const Value& defaultValue;
+};
+}  // namespace
+
+template <class Container, class Value>
+detail::DefaultValueWrapper<Container, Value>
+defaulted(const Container& c, const Value& v) {
+  return detail::DefaultValueWrapper<Container, Value>(c, v);
+}
+
 /**
  * Append formatted output to a string.
  *
@@ -202,7 +307,7 @@ Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
  * Shortcut for toAppend(format(...), &foo);
  */
 template <class Str, class... Args>
-typename std::enable_if<detail::IsSomeString<Str>::value>::type
+typename std::enable_if<IsSomeString<Str>::value>::type
 format(Str* out, StringPiece fmt, Args&&... args) {
   format(fmt, std::forward<Args>(args)...).appendTo(*out);
 }
@@ -211,7 +316,7 @@ format(Str* out, StringPiece fmt, Args&&... args) {
  * Append vformatted output to a string.
  */
 template <class Str, class Container>
-typename std::enable_if<detail::IsSomeString<Str>::value>::type
+typename std::enable_if<IsSomeString<Str>::value>::type
 vformat(Str* out, StringPiece fmt, Container&& container) {
   vformat(fmt, std::forward<Container>(container)).appendTo(*out);
 }
@@ -247,10 +352,14 @@ void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
  * formatString(fmt.str(), arg, cb); but avoids creating a temporary
  * string if possible.
  */
-template <class FormatCallback, bool containerMode, class... Args>
-void formatFormatter(const Formatter<containerMode, Args...>& formatter,
-                     FormatArg& arg,
-                     FormatCallback& cb);
+template <class FormatCallback,
+          class Derived,
+          bool containerMode,
+          class... Args>
+void formatFormatter(
+    const BaseFormatter<Derived, containerMode, Args...>& formatter,
+    FormatArg& arg,
+    FormatCallback& cb);
 
 }  // namespace format_value
 
@@ -276,10 +385,51 @@ void formatFormatter(const Formatter<containerMode, Args...>& formatter,
  * empty string)
  */
 
+namespace detail {
+
+template <class T, class Enable = void>
+struct IsFormatter : public std::false_type {};
+
+template <class T>
+struct IsFormatter<
+    T,
+    typename std::enable_if<
+        std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
+        type> : public std::true_type {};
+} // folly::detail
+
+// Deprecated API. formatChecked() et. al. now behave identically to their
+// non-Checked counterparts.
+template <class... Args>
+Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
+  return format(fmt, std::forward<Args>(args)...);
+}
+template <class... Args>
+inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
+  return formatChecked(fmt, std::forward<Args>(args)...).str();
+}
+template <class Container>
+Formatter<true, Container> vformatChecked(StringPiece fmt,
+                                          Container&& container) {
+  return vformat(fmt, std::forward<Container>(container));
+}
+template <class Container>
+inline std::string svformatChecked(StringPiece fmt, Container&& container) {
+  return vformatChecked(fmt, std::forward<Container>(container)).str();
+}
+template <class Str, class... Args>
+typename std::enable_if<IsSomeString<Str>::value>::type
+formatChecked(Str* out, StringPiece fmt, Args&&... args) {
+  formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
+}
+template <class Str, class Container>
+typename std::enable_if<IsSomeString<Str>::value>::type
+vformatChecked(Str* out, StringPiece fmt, Container&& container) {
+  vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
+}
+
 }  // namespace folly
 
-#include "folly/Format-inl.h"
+#include <folly/Format-inl.h>
 
 #pragma GCC diagnostic pop
-
-#endif /* FOLLY_FORMAT_H_ */