xref: /aosp_15_r20/external/libchrome/mojo/public/cpp/bindings/lib/string_serialization.h (revision 635a864187cb8b6c713ff48b7e790a6b21769273)
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_data_view.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<StringDataView, MaybeConstUserType> {
22   using UserType = typename std::remove_const<MaybeConstUserType>::type;
23   using Traits = StringTraits<UserType>;
24 
25   static void Serialize(MaybeConstUserType& input,
26                         Buffer* buffer,
27                         String_Data::BufferWriter* writer,
28                         SerializationContext* context) {
29     if (CallIsNullIfExists<Traits>(input))
30       return;
31 
32     void* custom_context = CustomContextHelper<Traits>::SetUp(input, context);
33     const size_t size = CallWithContext(Traits::GetSize, input, custom_context);
34     writer->Allocate(size, buffer);
35     memcpy((*writer)->storage(),
36            CallWithContext(Traits::GetData, input, custom_context), size);
37     CustomContextHelper<Traits>::TearDown(input, custom_context);
38   }
39 
40   static bool Deserialize(String_Data* input,
41                           UserType* output,
42                           SerializationContext* context) {
43     if (!input)
44       return CallSetToNullIfExists<Traits>(output);
45     return Traits::Read(StringDataView(input, context), output);
46   }
47 };
48 
49 }  // namespace internal
50 }  // namespace mojo
51 
52 #endif  // MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_
53