Add clear method to ProtoOutputStream so it is reusable by just
rewinding its internal pointer.
Bug: 72319159
Test: atest incidentd_test and atest statsd_test
Change-Id: Id046b987a7460d68300e5d4d46ae56aec1eba2d0
diff --git a/libs/protoutil/include/android/util/EncodedBuffer.h b/libs/protoutil/include/android/util/EncodedBuffer.h
index e568e4c..0a8a5aa 100644
--- a/libs/protoutil/include/android/util/EncodedBuffer.h
+++ b/libs/protoutil/include/android/util/EncodedBuffer.h
@@ -64,6 +64,11 @@
size_t mOffset;
};
+ /**
+ * Clears the buffer by rewinding its write pointer to avoid de/allocate buffers in heap.
+ */
+ void clear();
+
/******************************** Write APIs ************************************************/
/**
diff --git a/libs/protoutil/include/android/util/ProtoOutputStream.h b/libs/protoutil/include/android/util/ProtoOutputStream.h
index faea9b2..52830d3 100644
--- a/libs/protoutil/include/android/util/ProtoOutputStream.h
+++ b/libs/protoutil/include/android/util/ProtoOutputStream.h
@@ -123,6 +123,11 @@
EncodedBuffer::iterator data(); // Get the reader apis of the data.
bool flush(int fd); // Flush data directly to a file descriptor.
+ /**
+ * Clears the ProtoOutputStream so the buffer can be reused instead of deallocation/allocation again.
+ */
+ void clear();
+
// Please don't use the following functions to dump protos unless you are familiar with protobuf encoding.
void writeRawVarint(uint64_t varint);
void writeLengthDelimitedHeader(uint32_t id, size_t size);
diff --git a/libs/protoutil/src/EncodedBuffer.cpp b/libs/protoutil/src/EncodedBuffer.cpp
index 435ae88..3a5e2e9 100644
--- a/libs/protoutil/src/EncodedBuffer.cpp
+++ b/libs/protoutil/src/EncodedBuffer.cpp
@@ -106,6 +106,13 @@
return mBuffers[p.index()] + p.offset();
}
+void
+EncodedBuffer::clear()
+{
+ mWp.rewind();
+ mEp.rewind();
+}
+
/******************************** Write APIs ************************************************/
size_t
EncodedBuffer::size() const
diff --git a/libs/protoutil/src/ProtoOutputStream.cpp b/libs/protoutil/src/ProtoOutputStream.cpp
index f24abae..9d9ffec 100644
--- a/libs/protoutil/src/ProtoOutputStream.cpp
+++ b/libs/protoutil/src/ProtoOutputStream.cpp
@@ -36,6 +36,18 @@
{
}
+
+void
+ProtoOutputStream::clear()
+{
+ mBuffer.clear();
+ mCopyBegin = 0;
+ mCompact = false;
+ mDepth = 0;
+ mObjectId = 0;
+ mExpectedObjectToken = 0LL;
+}
+
bool
ProtoOutputStream::write(uint64_t fieldId, double val)
{