• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef MOJO_PUBLIC_CPP_BINDINGS_TYPE_CONVERTER_H_
6 #define MOJO_PUBLIC_CPP_BINDINGS_TYPE_CONVERTER_H_
7 
8 namespace mojo {
9 
10 // Specialize the following class:
11 //   template <typename T, typename U> class TypeConverter;
12 // to perform type conversion for Mojom-defined structs and arrays. Here, T is
13 // the Mojom-defined struct or array, and U is some other non-Mojom
14 // struct or array type.
15 //
16 // Specializations should implement the following interface:
17 //   namespace mojo {
18 //   template <>
19 //   class TypeConverter<T, U> {
20 //    public:
21 //     static T ConvertFrom(const U& input);
22 //     static U ConvertTo(const T& input);
23 //   };
24 //   }
25 //
26 // EXAMPLE:
27 //
28 // Suppose you have the following Mojom-defined struct:
29 //
30 //   module geometry {
31 //   struct Point {
32 //     int32 x;
33 //     int32 y;
34 //   };
35 //   }
36 //
37 // Now, imagine you wanted to write a TypeConverter specialization for
38 // gfx::Point. It might look like this:
39 //
40 //   namespace mojo {
41 //   template <>
42 //   class TypeConverter<geometry::PointPtr, gfx::Point> {
43 //    public:
44 //     static geometry::PointPtr ConvertFrom(const gfx::Point& input) {
45 //       geometry::PointPtr result;
46 //       result->x = input.x();
47 //       result->y = input.y();
48 //       return result.Pass();
49 //     }
50 //     static gfx::Point ConvertTo(const geometry::PointPtr& input) {
51 //       return input ? gfx::Point(input->x, input->y) : gfx::Point();
52 //     }
53 //   };
54 //   }
55 //
56 // With the above TypeConverter defined, it is possible to write code like this:
57 //
58 //   void AcceptPoint(const geometry::PointPtr& input) {
59 //     // With an explicit cast using the .To<> method.
60 //     gfx::Point pt = input.To<gfx::Point>();
61 //
62 //     // With an explicit cast using the static From() method.
63 //     geometry::PointPtr output = geometry::Point::From(pt);
64 //   }
65 //
66 template <typename T, typename U> class TypeConverter;
67 
68 // The following specialization is useful when you are converting between
69 // Array<POD> and std::vector<POD>.
70 template <typename T> class TypeConverter<T, T> {
71  public:
ConvertFrom(const T & obj)72   static T ConvertFrom(const T& obj) {
73     return obj;
74   }
ConvertTo(const T & obj)75   static T ConvertTo(const T& obj) {
76     return obj;
77   }
78 };
79 
80 }  // namespace mojo
81 
82 #endif  // MOJO_PUBLIC_CPP_BINDINGS_TYPE_CONVERTER_H_
83