aboutsummaryrefslogtreecommitdiff
path: root/mojo/public/cpp/bindings/clone_traits.h
blob: 203ab34189a5e138a76b1f36eb17ae112cd816c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef MOJO_PUBLIC_CPP_BINDINGS_CLONE_TRAITS_H_
#define MOJO_PUBLIC_CPP_BINDINGS_CLONE_TRAITS_H_

#include <type_traits>
#include <unordered_map>
#include <vector>

#include "base/optional.h"
#include "mojo/public/cpp/bindings/lib/template_util.h"

namespace mojo {

template <typename T>
struct HasCloneMethod {
  template <typename U>
  static char Test(decltype(&U::Clone));
  template <typename U>
  static int Test(...);
  static const bool value = sizeof(Test<T>(0)) == sizeof(char);

 private:
  internal::EnsureTypeIsComplete<T> check_t_;
};

template <typename T, bool has_clone_method = HasCloneMethod<T>::value>
struct CloneTraits;

template <typename T>
T Clone(const T& input);

template <typename T>
struct CloneTraits<T, true> {
  static T Clone(const T& input) { return input.Clone(); }
};

template <typename T>
struct CloneTraits<T, false> {
  static T Clone(const T& input) { return input; }
};

template <typename T>
struct CloneTraits<base::Optional<T>, false> {
  static base::Optional<T> Clone(const base::Optional<T>& input) {
    if (!input)
      return base::nullopt;

    return base::Optional<T>(mojo::Clone(*input));
  }
};

template <typename T>
struct CloneTraits<std::vector<T>, false> {
  static std::vector<T> Clone(const std::vector<T>& input) {
    std::vector<T> result;
    result.reserve(input.size());
    for (const auto& element : input)
      result.push_back(mojo::Clone(element));

    return result;
  }
};

template <typename K, typename V>
struct CloneTraits<std::unordered_map<K, V>, false> {
  static std::unordered_map<K, V> Clone(const std::unordered_map<K, V>& input) {
    std::unordered_map<K, V> result;
    for (const auto& element : input) {
      result.insert(std::make_pair(mojo::Clone(element.first),
                                   mojo::Clone(element.second)));
    }
    return result;
  }
};

template <typename T>
T Clone(const T& input) {
  return CloneTraits<T>::Clone(input);
};

}  // namespace mojo

#endif  // MOJO_PUBLIC_CPP_BINDINGS_CLONE_TRAITS_H_