pw_stream: Construct MemoryWriter w/prepopulated buffer

No-Docs-Update-Reason: Adding helper constructor, usage in header.
Change-Id: Ic85c45d92096b47ff88dc7284fe4921aa7063335
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/48720
Reviewed-by: Armando Montanez <amontanez@google.com>
Reviewed-by: Wyatt Hepler <hepler@google.com>
Pigweed-Auto-Submit: Prashanth Swaminathan <prashanthsw@google.com>
Commit-Queue: Auto-Submit <auto-submit@pigweed.google.com.iam.gserviceaccount.com>
diff --git a/pw_stream/memory_stream_test.cc b/pw_stream/memory_stream_test.cc
index 4b47b2c..0e42fa5 100644
--- a/pw_stream/memory_stream_test.cc
+++ b/pw_stream/memory_stream_test.cc
@@ -40,7 +40,18 @@
       memory_writer.Write(&kExpectedStruct, sizeof(kExpectedStruct));
   EXPECT_EQ(status, OkStatus());
   EXPECT_EQ(memory_writer.bytes_written(), sizeof(kExpectedStruct));
-}  // namespace
+}
+
+TEST(MemoryWriter, BytesWrittenOnConstruction) {
+  constexpr size_t bytes_written = kSinkBufferSize / 2;
+  std::memset(memory_buffer.data(), 1u, bytes_written);
+  MemoryWriter memory_writer(memory_buffer, bytes_written);
+  EXPECT_EQ(memory_writer.bytes_written(), bytes_written);
+  EXPECT_EQ(memcmp(memory_writer.WrittenData().data(),
+                   memory_buffer.data(),
+                   bytes_written),
+            0);
+}
 
 TEST(MemoryWriter, ValidateContents) {
   MemoryWriter memory_writer(memory_buffer);
diff --git a/pw_stream/public/pw_stream/memory_stream.h b/pw_stream/public/pw_stream/memory_stream.h
index 1ccf9ab..2690068 100644
--- a/pw_stream/public/pw_stream/memory_stream.h
+++ b/pw_stream/public/pw_stream/memory_stream.h
@@ -27,6 +27,16 @@
  public:
   constexpr MemoryWriter(ByteSpan dest) : dest_(dest) {}
 
+  // Construct writer with prepopulated data in the buffer. The number of
+  // pre-written bytes is provided as `bytes_written`.
+  //
+  // Precondition: The number of pre-written bytes must not be greater than the
+  // size of the provided buffer.
+  constexpr MemoryWriter(ByteSpan dest, size_t bytes_written)
+      : dest_(dest), bytes_written_(bytes_written) {
+    PW_ASSERT(bytes_written_ <= dest.size_bytes());
+  }
+
   size_t bytes_written() const { return bytes_written_; }
 
   size_t ConservativeWriteLimit() const override {