Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(97)

Unified Diff: webrtc/base/bytebuffer.cc

Issue 1844333006: Add WriteUVarint to ByteBufferWriter and ReadUVarint to ByteBufferReader (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Fix typo Created 4 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « webrtc/base/bytebuffer.h ('k') | webrtc/base/bytebuffer_unittest.cc » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: webrtc/base/bytebuffer.cc
diff --git a/webrtc/base/bytebuffer.cc b/webrtc/base/bytebuffer.cc
index cf4ce42574e959e8df76c23b6b6b37e45b1b94fc..9730ff23d6787ca7e555d1aa2a5f8c0878aa6552 100644
--- a/webrtc/base/bytebuffer.cc
+++ b/webrtc/base/bytebuffer.cc
@@ -88,6 +88,20 @@ void ByteBufferWriter::WriteUInt64(uint64_t val) {
WriteBytes(reinterpret_cast<const char*>(&v), 8);
}
+// Serializes an unsigned varint in the format described by
+// https://developers.google.com/protocol-buffers/docs/encoding#varints
+// with the caveat that integers are 64-bit, not 128-bit.
+void ByteBufferWriter::WriteUVarint(uint64_t val) {
+ while (val >= 0x80) {
+ // Write 7 bits at a time, then set the msb to a continuation byte (msb=1).
+ char byte = static_cast<char>(val) | 0x80;
+ WriteBytes(&byte, 1);
+ val >>= 7;
+ }
+ char last_byte = static_cast<char>(val);
+ WriteBytes(&last_byte, 1);
+}
+
void ByteBufferWriter::WriteString(const std::string& val) {
WriteBytes(val.c_str(), val.size());
}
@@ -220,6 +234,29 @@ bool ByteBufferReader::ReadUInt64(uint64_t* val) {
}
}
+bool ByteBufferReader::ReadUVarint(uint64_t* val) {
+ if (!val) {
+ return false;
+ }
+ // Integers are deserialized 7 bits at a time, with each byte having a
+ // continuation byte (msb=1) if there are more bytes to be read.
+ uint64_t v = 0;
+ for (int i = 0; i < 64; i += 7) {
+ char byte;
+ if (!ReadBytes(&byte, 1)) {
+ return false;
+ }
+ // Read the first 7 bits of the byte, then offset by bits read so far.
+ v |= (static_cast<uint64_t>(byte) & 0x7F) << i;
+ // True if the msb is not a continuation byte.
+ if (static_cast<uint64_t>(byte) < 0x80) {
+ *val = v;
+ return true;
+ }
+ }
+ return false;
+}
+
bool ByteBufferReader::ReadString(std::string* val, size_t len) {
if (!val) return false;
« no previous file with comments | « webrtc/base/bytebuffer.h ('k') | webrtc/base/bytebuffer_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698