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 #include <stdint.h> 9 10 namespace mojo { 11 12 // Specialize the following class: 13 // template <typename T, typename U> struct TypeConverter; 14 // to perform type conversion for Mojom-defined structs and arrays. Here, T is 15 // the target type; U is the input type. 16 // 17 // Specializations should implement the following interfaces: 18 // namespace mojo { 19 // template <> 20 // struct TypeConverter<X, Y> { 21 // static X Convert(const Y& input); 22 // }; 23 // template <> 24 // struct TypeConverter<Y, X> { 25 // static Y Convert(const X& input); 26 // }; 27 // } 28 // 29 // EXAMPLE: 30 // 31 // Suppose you have the following Mojom-defined struct: 32 // 33 // module geometry { 34 // struct Point { 35 // int32_t x; 36 // int32_t y; 37 // }; 38 // } 39 // 40 // Now, imagine you wanted to write a TypeConverter specialization for 41 // gfx::Point. It might look like this: 42 // 43 // namespace mojo { 44 // template <> 45 // struct TypeConverter<geometry::PointPtr, gfx::Point> { 46 // static geometry::PointPtr Convert(const gfx::Point& input) { 47 // geometry::PointPtr result; 48 // result->x = input.x(); 49 // result->y = input.y(); 50 // return result; 51 // } 52 // }; 53 // template <> 54 // struct TypeConverter<gfx::Point, geometry::PointPtr> { 55 // static gfx::Point Convert(const geometry::PointPtr& input) { 56 // return input ? gfx::Point(input->x, input->y) : gfx::Point(); 57 // } 58 // }; 59 // } 60 // 61 // With the above TypeConverter defined, it is possible to write code like this: 62 // 63 // void AcceptPoint(const geometry::PointPtr& input) { 64 // // With an explicit cast using the .To<> method. 65 // gfx::Point pt = input.To<gfx::Point>(); 66 // 67 // // With an explicit cast using the static From() method. 68 // geometry::PointPtr output = geometry::Point::From(pt); 69 // 70 // // Inferring the input type using the ConvertTo helper function. 71 // gfx::Point pt2 = ConvertTo<gfx::Point>(input); 72 // } 73 // 74 template <typename T, typename U> 75 struct TypeConverter; 76 77 // The following specialization is useful when you are converting between 78 // Array<POD> and std::vector<POD>. 79 template <typename T> 80 struct TypeConverter<T, T> { 81 static T Convert(const T& obj) { return obj; } 82 }; 83 84 // The following helper function is useful for shorthand. The compiler can infer 85 // the input type, so you can write: 86 // OutputType out = ConvertTo<OutputType>(input); 87 template <typename T, typename U> 88 inline T ConvertTo(const U& obj) { 89 return TypeConverter<T, U>::Convert(obj); 90 }; 91 92 } // namespace mojo 93 94 #endif // MOJO_PUBLIC_CPP_BINDINGS_TYPE_CONVERTER_H_ 95