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_LIB_STRING_SERIALIZATION_H_ 6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_ 7 8 #include <stddef.h> 9 #include <string.h> 10 11 #include "mojo/public/cpp/bindings/lib/array_internal.h" 12 #include "mojo/public/cpp/bindings/lib/serialization_forward.h" 13 #include "mojo/public/cpp/bindings/lib/serialization_util.h" 14 #include "mojo/public/cpp/bindings/string.h" 15 #include "mojo/public/cpp/bindings/string_traits.h" 16 17 namespace mojo { 18 namespace internal { 19 20 template <typename MaybeConstUserType> 21 struct Serializer<String, MaybeConstUserType> { 22 using UserType = typename std::remove_const<MaybeConstUserType>::type; 23 using Traits = StringTraits<UserType>; 24 25 static size_t PrepareToSerialize(MaybeConstUserType& input, 26 SerializationContext* context) { 27 if (CallIsNullIfExists<Traits>(input)) 28 return 0; 29 30 void* custom_context = CustomContextHelper<Traits>::SetUp(input, context); 31 return Align(sizeof(String_Data) + 32 CallWithContext(Traits::GetSize, input, custom_context)); 33 } 34 35 static void Serialize(MaybeConstUserType& input, 36 Buffer* buffer, 37 String_Data** output, 38 SerializationContext* context) { 39 if (CallIsNullIfExists<Traits>(input)) { 40 *output = nullptr; 41 return; 42 } 43 44 void* custom_context = CustomContextHelper<Traits>::GetNext(context); 45 46 String_Data* result = String_Data::New( 47 CallWithContext(Traits::GetSize, input, custom_context), buffer); 48 if (result) { 49 memcpy(result->storage(), 50 CallWithContext(Traits::GetData, input, custom_context), 51 CallWithContext(Traits::GetSize, input, custom_context)); 52 } 53 *output = result; 54 55 CustomContextHelper<Traits>::TearDown(input, custom_context); 56 } 57 58 static bool Deserialize(String_Data* input, 59 UserType* output, 60 SerializationContext* context) { 61 if (!input) 62 return CallSetToNullIfExists<Traits>(output); 63 return Traits::Read(StringDataView(input), output); 64 } 65 }; 66 67 } // namespace internal 68 } // namespace mojo 69 70 #endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_ 71