1 // Copyright 2016 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_STRING_TRAITS_H_ 6 #define MOJO_PUBLIC_CPP_BINDINGS_STRING_TRAITS_H_ 7 8 #include "base/logging.h" 9 #include "mojo/public/cpp/bindings/lib/array_internal.h" 10 11 namespace mojo { 12 13 // Access to the contents of a serialized string. 14 class StringDataView { 15 public: StringDataView(internal::String_Data * data)16 explicit StringDataView(internal::String_Data* data) : data_(data) { 17 DCHECK(data_); 18 } 19 storage()20 const char* storage() const { return data_->storage(); } 21 size()22 size_t size() const { return data_->size(); } 23 24 private: 25 internal::String_Data* data_; 26 }; 27 28 // This must be specialized for any type |T| to be serialized/deserialized as 29 // a mojom string. 30 // 31 // Imagine you want to specialize it for CustomString, usually you need to 32 // implement: 33 // 34 // template <T> 35 // struct StringTraits<CustomString> { 36 // // These two methods are optional. Please see comments in struct_traits.h 37 // static bool IsNull(const CustomString& input); 38 // static void SetToNull(CustomString* output); 39 // 40 // static size_t GetSize(const CustomString& input); 41 // static const char* GetData(const CustomString& input); 42 // 43 // static bool Read(StringDataView input, CustomString* output); 44 // }; 45 // 46 // In some cases, you may need to do conversion before you can return the size 47 // and data as 8-bit characters for serialization. (For example, CustomString is 48 // UTF-16 string). In that case, you can add two optional methods: 49 // 50 // static void* SetUpContext(const CustomString& input); 51 // static void TearDownContext(const CustomString& input, void* context); 52 // 53 // And then you append a second parameter, void* context, to GetSize() and 54 // GetData(): 55 // 56 // static size_t GetSize(const CustomString& input, void* context); 57 // static const char* GetData(const CustomString& input, void* context); 58 // 59 // If a CustomString instance is not null, the serialization code will call 60 // SetUpContext() at the beginning, and pass the resulting context pointer to 61 // GetSize()/GetData(). After serialization is done, it calls TearDownContext() 62 // so that you can do any necessary cleanup. 63 // 64 template <typename T> 65 struct StringTraits; 66 67 } // namespace mojo 68 69 #endif // MOJO_PUBLIC_CPP_BINDINGS_STRING_TRAITS_H_ 70