leb128.cc (1600B)
1 /* 2 * Copyright (c) 2023 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 "modules/rtp_rtcp/source/leb128.h" 12 13 #include <cstdint> 14 15 namespace webrtc { 16 17 int Leb128Size(uint64_t value) { 18 int size = 0; 19 while (value >= 0x80) { 20 ++size; 21 value >>= 7; 22 } 23 return size + 1; 24 } 25 26 uint64_t ReadLeb128(const uint8_t*& read_at, const uint8_t* end) { 27 uint64_t value = 0; 28 int fill_bits = 0; 29 while (read_at != end && fill_bits < 64 - 7) { 30 uint8_t leb128_byte = *read_at; 31 value |= uint64_t{leb128_byte & 0x7Fu} << fill_bits; 32 ++read_at; 33 fill_bits += 7; 34 if ((leb128_byte & 0x80) == 0) { 35 return value; 36 } 37 } 38 // Read 9 bytes and didn't find the terminator byte. Check if 10th byte 39 // is that terminator, however to fit result into uint64_t it may carry only 40 // single bit. 41 if (read_at != end && *read_at <= 1) { 42 value |= uint64_t{*read_at} << fill_bits; 43 ++read_at; 44 return value; 45 } 46 // Failed to find terminator leb128 byte. 47 read_at = nullptr; 48 return 0; 49 } 50 51 int WriteLeb128(uint64_t value, uint8_t* buffer) { 52 int size = 0; 53 while (value >= 0x80) { 54 buffer[size] = 0x80 | (value & 0x7F); 55 ++size; 56 value >>= 7; 57 } 58 buffer[size] = value; 59 ++size; 60 return size; 61 } 62 63 } // namespace webrtc