AU: Release bspatch memory as early as possible.

Release the memory as soon as the bspatch file is written out in order
to reduce overall peak memory usage.

BUG=chromium:220750
TEST=unit tests; trybots

Change-Id: I0d82976c207c6bb57287f6ea1a79e214db1f08c7
Reviewed-on: https://gerrit.chromium.org/gerrit/47232
Tested-by: Darin Petkov <petkov@chromium.org>
Reviewed-by: Gilad Arnold <garnold@chromium.org>
Commit-Queue: Darin Petkov <petkov@chromium.org>
diff --git a/delta_performer.cc b/delta_performer.cc
index 74e21e2..12f0e20 100644
--- a/delta_performer.cc
+++ b/delta_performer.cc
@@ -721,6 +721,11 @@
         utils::WriteAll(fd, &buffer_[0], operation.data_length()));
   }
 
+  // Update the buffer to release the patch data memory as soon as the patch
+  // file is written out.
+  buffer_offset_ += operation.data_length();
+  DiscardBufferHeadBytes(operation.data_length());
+
   int fd = is_kernel_partition ? kernel_fd_ : fd_;
   const string& path = StringPrintf("/dev/fd/%d", fd);
 
@@ -760,10 +765,6 @@
     TEST_AND_RETURN_FALSE(
         utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
   }
-
-  // Update buffer.
-  buffer_offset_ += operation.data_length();
-  DiscardBufferHeadBytes(operation.data_length());
   return true;
 }
 
@@ -1101,7 +1102,10 @@
 
 void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
   hash_calculator_.Update(&buffer_[0], count);
-  buffer_.erase(buffer_.begin(), buffer_.begin() + count);
+  // Copy the remainder data into a temporary vector first to ensure that any
+  // unused memory in the updated |buffer_| will be released.
+  vector<char> temp(buffer_.begin() + count, buffer_.end());
+  buffer_.swap(temp);
 }
 
 bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,