• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 //
3 // Copyright 2024 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include "src/core/lib/surface/connection_context.h"
20 
21 #include <grpc/support/alloc.h>
22 #include <grpc/support/port_platform.h>
23 
24 #include <cstddef>
25 
26 #include "src/core/util/alloc.h"
27 #include "src/core/util/orphanable.h"
28 
29 namespace grpc_core {
30 
31 namespace {
32 
ConnectionContextStorage()33 void* ConnectionContextStorage() {
34   size_t base_size = sizeof(ConnectionContext) +
35                      GPR_ROUND_UP_TO_ALIGNMENT_SIZE(
36                          connection_context_detail::
37                              BaseConnectionContextPropertiesTraits::Size());
38   static constexpr size_t alignment =
39       (GPR_CACHELINE_SIZE > GPR_MAX_ALIGNMENT &&
40        GPR_CACHELINE_SIZE % GPR_MAX_ALIGNMENT == 0)
41           ? GPR_CACHELINE_SIZE
42           : GPR_MAX_ALIGNMENT;
43   return gpr_malloc_aligned(base_size, alignment);
44 }
45 
46 }  // namespace
47 
Create()48 OrphanablePtr<ConnectionContext> ConnectionContext::Create() {
49   void* p = ConnectionContextStorage();
50   return OrphanablePtr<ConnectionContext>(new (p) ConnectionContext());
51 }
52 
ConnectionContext()53 ConnectionContext::ConnectionContext() {
54   for (size_t i = 0;
55        i < connection_context_detail::BaseConnectionContextPropertiesTraits::
56                NumProperties();
57        ++i) {
58     registered_properties()[i] = nullptr;
59   }
60 }
61 
Orphan()62 void ConnectionContext::Orphan() {
63   this->~ConnectionContext();
64   gpr_free_aligned(const_cast<ConnectionContext*>(this));
65 }
66 
~ConnectionContext()67 ConnectionContext::~ConnectionContext() {
68   for (size_t i = 0;
69        i < connection_context_detail::BaseConnectionContextPropertiesTraits::
70                NumProperties();
71        ++i) {
72     connection_context_detail::BaseConnectionContextPropertiesTraits::Destroy(
73         i, registered_properties()[i]);
74   }
75 }
76 
77 }  // namespace grpc_core
78