Move rtc::FunctionView to the public API

Bug: webrtc:10138
Change-Id: Icc25a2a277a9608701aaddd546882366739991ca
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/127898
Reviewed-by: Karl Wiberg <kwiberg@webrtc.org>
Reviewed-by: Mirko Bonadei <mbonadei@webrtc.org>
Commit-Queue: Artem Titov <titovartem@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#27227}
diff --git a/api/BUILD.gn b/api/BUILD.gn
index ec03df3..6b78a6c 100644
--- a/api/BUILD.gn
+++ b/api/BUILD.gn
@@ -399,6 +399,16 @@
   ]
 }
 
+rtc_source_set("function_view") {
+  visibility = [ "*" ]
+  sources = [
+    "function_view.h",
+  ]
+  deps = [
+    "../rtc_base:checks",
+  ]
+}
+
 if (rtc_include_tests) {
   if (rtc_enable_protobuf) {
     rtc_source_set("audioproc_f_api") {
@@ -684,6 +694,7 @@
 
     sources = [
       "array_view_unittest.cc",
+      "function_view_unittest.cc",
       "rtc_error_unittest.cc",
       "rtp_parameters_unittest.cc",
       "test/loopback_media_transport_unittest.cc",
@@ -691,6 +702,7 @@
 
     deps = [
       ":array_view",
+      ":function_view",
       ":libjingle_peerconnection_api",
       ":loopback_media_transport",
       "../rtc_base:checks",
diff --git a/api/function_view.h b/api/function_view.h
new file mode 100644
index 0000000..5ae1bd6
--- /dev/null
+++ b/api/function_view.h
@@ -0,0 +1,130 @@
+/*
+ *  Copyright 2016 The WebRTC Project Authors. All rights reserved.
+ *
+ *  Use of this source code is governed by a BSD-style license
+ *  that can be found in the LICENSE file in the root of the source
+ *  tree. An additional intellectual property rights grant can be found
+ *  in the file PATENTS.  All contributing project authors may
+ *  be found in the AUTHORS file in the root of the source tree.
+ */
+
+#ifndef API_FUNCTION_VIEW_H_
+#define API_FUNCTION_VIEW_H_
+
+#include <type_traits>
+#include <utility>
+
+#include "rtc_base/checks.h"
+
+// Just like std::function, FunctionView will wrap any callable and hide its
+// actual type, exposing only its signature. But unlike std::function,
+// FunctionView doesn't own its callable---it just points to it. Thus, it's a
+// good choice mainly as a function argument when the callable argument will
+// not be called again once the function has returned.
+//
+// Its constructors are implicit, so that callers won't have to convert lambdas
+// and other callables to FunctionView<Blah(Blah, Blah)> explicitly. This is
+// safe because FunctionView is only a reference to the real callable.
+//
+// Example use:
+//
+//   void SomeFunction(rtc::FunctionView<int(int)> index_transform);
+//   ...
+//   SomeFunction([](int i) { return 2 * i + 1; });
+//
+// Note: FunctionView is tiny (essentially just two pointers) and trivially
+// copyable, so it's probably cheaper to pass it by value than by const
+// reference.
+
+namespace rtc {
+
+template <typename T>
+class FunctionView;  // Undefined.
+
+template <typename RetT, typename... ArgT>
+class FunctionView<RetT(ArgT...)> final {
+ public:
+  // Constructor for lambdas and other callables; it accepts every type of
+  // argument except those noted in its enable_if call.
+  template <
+      typename F,
+      typename std::enable_if<
+          // Not for function pointers; we have another constructor for that
+          // below.
+          !std::is_function<typename std::remove_pointer<
+              typename std::remove_reference<F>::type>::type>::value &&
+
+          // Not for nullptr; we have another constructor for that below.
+          !std::is_same<std::nullptr_t,
+                        typename std::remove_cv<F>::type>::value &&
+
+          // Not for FunctionView objects; we have another constructor for that
+          // (the implicitly declared copy constructor).
+          !std::is_same<FunctionView,
+                        typename std::remove_cv<typename std::remove_reference<
+                            F>::type>::type>::value>::type* = nullptr>
+  FunctionView(F&& f)
+      : call_(CallVoidPtr<typename std::remove_reference<F>::type>) {
+    f_.void_ptr = &f;
+  }
+
+  // Constructor that accepts function pointers. If the argument is null, the
+  // result is an empty FunctionView.
+  template <
+      typename F,
+      typename std::enable_if<std::is_function<typename std::remove_pointer<
+          typename std::remove_reference<F>::type>::type>::value>::type* =
+          nullptr>
+  FunctionView(F&& f)
+      : call_(f ? CallFunPtr<typename std::remove_pointer<F>::type> : nullptr) {
+    f_.fun_ptr = reinterpret_cast<void (*)()>(f);
+  }
+
+  // Constructor that accepts nullptr. It creates an empty FunctionView.
+  template <typename F,
+            typename std::enable_if<std::is_same<
+                std::nullptr_t,
+                typename std::remove_cv<F>::type>::value>::type* = nullptr>
+  FunctionView(F&& f) : call_(nullptr) {}
+
+  // Default constructor. Creates an empty FunctionView.
+  FunctionView() : call_(nullptr) {}
+
+  RetT operator()(ArgT... args) const {
+    RTC_DCHECK(call_);
+    return call_(f_, std::forward<ArgT>(args)...);
+  }
+
+  // Returns true if we have a function, false if we don't (i.e., we're null).
+  explicit operator bool() const { return !!call_; }
+
+ private:
+  union VoidUnion {
+    void* void_ptr;
+    void (*fun_ptr)();
+  };
+
+  template <typename F>
+  static RetT CallVoidPtr(VoidUnion vu, ArgT... args) {
+    return (*static_cast<F*>(vu.void_ptr))(std::forward<ArgT>(args)...);
+  }
+  template <typename F>
+  static RetT CallFunPtr(VoidUnion vu, ArgT... args) {
+    return (reinterpret_cast<typename std::add_pointer<F>::type>(vu.fun_ptr))(
+        std::forward<ArgT>(args)...);
+  }
+
+  // A pointer to the callable thing, with type information erased. It's a
+  // union because we have to use separate types depending on if the callable
+  // thing is a function pointer or something else.
+  VoidUnion f_;
+
+  // Pointer to a dispatch function that knows the type of the callable thing
+  // that's stored in f_, and how to call it. A FunctionView object is empty
+  // (null) iff call_ is null.
+  RetT (*call_)(VoidUnion, ArgT...);
+};
+
+}  // namespace rtc
+
+#endif  // API_FUNCTION_VIEW_H_
diff --git a/api/function_view_unittest.cc b/api/function_view_unittest.cc
new file mode 100644
index 0000000..3abf0e3
--- /dev/null
+++ b/api/function_view_unittest.cc
@@ -0,0 +1,175 @@
+/*
+ *  Copyright 2016 The WebRTC Project Authors. All rights reserved.
+ *
+ *  Use of this source code is governed by a BSD-style license
+ *  that can be found in the LICENSE file in the root of the source
+ *  tree. An additional intellectual property rights grant can be found
+ *  in the file PATENTS.  All contributing project authors may
+ *  be found in the AUTHORS file in the root of the source tree.
+ */
+
+#include <memory>
+#include <utility>
+
+#include "api/function_view.h"
+#include "test/gtest.h"
+
+namespace rtc {
+
+namespace {
+
+int CallWith33(rtc::FunctionView<int(int)> fv) {
+  return fv ? fv(33) : -1;
+}
+
+int Add33(int x) {
+  return x + 33;
+}
+
+}  // namespace
+
+// Test the main use case of FunctionView: implicitly converting a callable
+// argument.
+TEST(FunctionViewTest, ImplicitConversion) {
+  EXPECT_EQ(38, CallWith33([](int x) { return x + 5; }));
+  EXPECT_EQ(66, CallWith33(Add33));
+  EXPECT_EQ(-1, CallWith33(nullptr));
+}
+
+TEST(FunctionViewTest, IntIntLambdaWithoutState) {
+  auto f = [](int x) { return x + 1; };
+  EXPECT_EQ(18, f(17));
+  rtc::FunctionView<int(int)> fv(f);
+  EXPECT_TRUE(fv);
+  EXPECT_EQ(18, fv(17));
+}
+
+TEST(FunctionViewTest, IntVoidLambdaWithState) {
+  int x = 13;
+  auto f = [x]() mutable { return ++x; };
+  rtc::FunctionView<int()> fv(f);
+  EXPECT_TRUE(fv);
+  EXPECT_EQ(14, f());
+  EXPECT_EQ(15, fv());
+  EXPECT_EQ(16, f());
+  EXPECT_EQ(17, fv());
+}
+
+TEST(FunctionViewTest, IntIntFunction) {
+  rtc::FunctionView<int(int)> fv(Add33);
+  EXPECT_TRUE(fv);
+  EXPECT_EQ(50, fv(17));
+}
+
+TEST(FunctionViewTest, IntIntFunctionPointer) {
+  rtc::FunctionView<int(int)> fv(&Add33);
+  EXPECT_TRUE(fv);
+  EXPECT_EQ(50, fv(17));
+}
+
+TEST(FunctionViewTest, Null) {
+  // These two call constructors that statically construct null FunctionViews.
+  EXPECT_FALSE(rtc::FunctionView<int()>());
+  EXPECT_FALSE(rtc::FunctionView<int()>(nullptr));
+
+  // This calls the constructor for function pointers.
+  EXPECT_FALSE(rtc::FunctionView<int()>(reinterpret_cast<int (*)()>(0)));
+}
+
+// Ensure that FunctionView handles move-only arguments and return values.
+TEST(FunctionViewTest, UniquePtrPassthrough) {
+  auto f = [](std::unique_ptr<int> x) { return x; };
+  rtc::FunctionView<std::unique_ptr<int>(std::unique_ptr<int>)> fv(f);
+  std::unique_ptr<int> x(new int);
+  int* x_addr = x.get();
+  auto y = fv(std::move(x));
+  EXPECT_EQ(x_addr, y.get());
+}
+
+TEST(FunctionViewTest, CopyConstructor) {
+  auto f17 = [] { return 17; };
+  rtc::FunctionView<int()> fv1(f17);
+  rtc::FunctionView<int()> fv2(fv1);
+  EXPECT_EQ(17, fv1());
+  EXPECT_EQ(17, fv2());
+}
+
+TEST(FunctionViewTest, MoveConstructorIsCopy) {
+  auto f17 = [] { return 17; };
+  rtc::FunctionView<int()> fv1(f17);
+  rtc::FunctionView<int()> fv2(std::move(fv1));  // NOLINT
+  EXPECT_EQ(17, fv1());
+  EXPECT_EQ(17, fv2());
+}
+
+TEST(FunctionViewTest, CopyAssignment) {
+  auto f17 = [] { return 17; };
+  rtc::FunctionView<int()> fv1(f17);
+  auto f23 = [] { return 23; };
+  rtc::FunctionView<int()> fv2(f23);
+  EXPECT_EQ(17, fv1());
+  EXPECT_EQ(23, fv2());
+  fv2 = fv1;
+  EXPECT_EQ(17, fv1());
+  EXPECT_EQ(17, fv2());
+}
+
+TEST(FunctionViewTest, MoveAssignmentIsCopy) {
+  auto f17 = [] { return 17; };
+  rtc::FunctionView<int()> fv1(f17);
+  auto f23 = [] { return 23; };
+  rtc::FunctionView<int()> fv2(f23);
+  EXPECT_EQ(17, fv1());
+  EXPECT_EQ(23, fv2());
+  fv2 = std::move(fv1);  // NOLINT
+  EXPECT_EQ(17, fv1());
+  EXPECT_EQ(17, fv2());
+}
+
+TEST(FunctionViewTest, Swap) {
+  auto f17 = [] { return 17; };
+  rtc::FunctionView<int()> fv1(f17);
+  auto f23 = [] { return 23; };
+  rtc::FunctionView<int()> fv2(f23);
+  EXPECT_EQ(17, fv1());
+  EXPECT_EQ(23, fv2());
+  using std::swap;
+  swap(fv1, fv2);
+  EXPECT_EQ(23, fv1());
+  EXPECT_EQ(17, fv2());
+}
+
+// Ensure that when you copy-construct a FunctionView, the new object points to
+// the same function as the old one (as opposed to the new object pointing to
+// the old one).
+TEST(FunctionViewTest, CopyConstructorChaining) {
+  auto f17 = [] { return 17; };
+  rtc::FunctionView<int()> fv1(f17);
+  rtc::FunctionView<int()> fv2(fv1);
+  EXPECT_EQ(17, fv1());
+  EXPECT_EQ(17, fv2());
+  auto f23 = [] { return 23; };
+  fv1 = f23;
+  EXPECT_EQ(23, fv1());
+  EXPECT_EQ(17, fv2());
+}
+
+// Ensure that when you assign one FunctionView to another, we actually make a
+// copy (as opposed to making the second FunctionView point to the first one).
+TEST(FunctionViewTest, CopyAssignmentChaining) {
+  auto f17 = [] { return 17; };
+  rtc::FunctionView<int()> fv1(f17);
+  rtc::FunctionView<int()> fv2;
+  EXPECT_TRUE(fv1);
+  EXPECT_EQ(17, fv1());
+  EXPECT_FALSE(fv2);
+  fv2 = fv1;
+  EXPECT_EQ(17, fv1());
+  EXPECT_EQ(17, fv2());
+  auto f23 = [] { return 23; };
+  fv1 = f23;
+  EXPECT_EQ(23, fv1());
+  EXPECT_EQ(17, fv2());
+}
+
+}  // namespace rtc