xref: /aosp_15_r20/external/webrtc/logging/rtc_event_log/events/rtc_event_field_extraction.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2021 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "logging/rtc_event_log/events/rtc_event_field_extraction.h"
12 
13 #include <algorithm>
14 #include <limits>
15 
16 #include "rtc_base/checks.h"
17 
18 namespace webrtc_event_logging {
19 
20 // The bitwidth required to encode values in the range
21 // [0, `max_pos_magnitude`] using an unsigned representation.
UnsignedBitWidth(uint64_t max_magnitude)22 uint8_t UnsignedBitWidth(uint64_t max_magnitude) {
23   uint8_t required_bits = 1;
24   while (max_magnitude >>= 1) {
25     ++required_bits;
26   }
27   return required_bits;
28 }
29 
30 // The bitwidth required to encode signed values in the range
31 // [-`max_neg_magnitude`, `max_pos_magnitude`] using a signed
32 // 2-complement representation.
SignedBitWidth(uint64_t max_pos_magnitude,uint64_t max_neg_magnitude)33 uint8_t SignedBitWidth(uint64_t max_pos_magnitude, uint64_t max_neg_magnitude) {
34   const uint8_t bitwidth_positive =
35       max_pos_magnitude > 0 ? UnsignedBitWidth(max_pos_magnitude) : 0;
36   const uint8_t bitwidth_negative =
37       (max_neg_magnitude > 1) ? UnsignedBitWidth(max_neg_magnitude - 1) : 0;
38   return 1 + std::max(bitwidth_positive, bitwidth_negative);
39 }
40 
41 // Return the maximum integer of a given bit width.
MaxUnsignedValueOfBitWidth(uint64_t bit_width)42 uint64_t MaxUnsignedValueOfBitWidth(uint64_t bit_width) {
43   RTC_DCHECK_GE(bit_width, 1);
44   RTC_DCHECK_LE(bit_width, 64);
45   return (bit_width == 64) ? std::numeric_limits<uint64_t>::max()
46                            : ((static_cast<uint64_t>(1) << bit_width) - 1);
47 }
48 
49 // Computes the delta between `previous` and `current`, under the assumption
50 // that `bit_mask` is the largest value before wrap-around occurs. The bitmask
51 // must be of the form 2^x-1. (We use the wrap-around to more efficiently
52 // compress counters that wrap around at different bit widths than the
53 // backing C++ data type.)
UnsignedDelta(uint64_t previous,uint64_t current,uint64_t bit_mask)54 uint64_t UnsignedDelta(uint64_t previous, uint64_t current, uint64_t bit_mask) {
55   RTC_DCHECK_LE(previous, bit_mask);
56   RTC_DCHECK_LE(current, bit_mask);
57   return (current - previous) & bit_mask;
58 }
59 
60 }  // namespace webrtc_event_logging
61