xref: /aosp_15_r20/external/grpc-grpc/src/core/lib/transport/call_size_estimator.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Copyright 2024 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <grpc/support/port_platform.h>
16 
17 #include "src/core/lib/transport/call_size_estimator.h"
18 
19 #include <algorithm>
20 
21 namespace grpc_core {
22 
UpdateCallSizeEstimate(size_t size)23 void CallSizeEstimator::UpdateCallSizeEstimate(size_t size) {
24   size_t cur = call_size_estimate_.load(std::memory_order_relaxed);
25   if (cur < size) {
26     // size grew: update estimate
27     call_size_estimate_.compare_exchange_weak(
28         cur, size, std::memory_order_relaxed, std::memory_order_relaxed);
29     // if we lose: never mind, something else will likely update soon enough
30   } else if (cur == size) {
31     // no change: holding pattern
32   } else if (cur > 0) {
33     // size shrank: decrease estimate
34     call_size_estimate_.compare_exchange_weak(
35         cur, std::min(cur - 1, (255 * cur + size) / 256),
36         std::memory_order_relaxed, std::memory_order_relaxed);
37     // if we lose: never mind, something else will likely update soon enough
38   }
39 }
40 
41 }  // namespace grpc_core
42