pw_kvs: Reduce stack usage of FlashPartition

Reduce stack usage of FlashPartition::IsRegionErased() by removing the
erased_patter_buffer[]. This is a 256 byte savings of stack usage for
the current Pigweed config.

Change-Id: I018554cdf5011f83977c7d7ccb4dbb1bd4da5109
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/13680
Commit-Queue: David Rogers <davidrogers@google.com>
Reviewed-by: Armando Montanez <amontanez@google.com>
Reviewed-by: Keir Mierle <keir@google.com>
diff --git a/pw_kvs/flash_memory.cc b/pw_kvs/flash_memory.cc
index 0e8af99..c3871f6 100644
--- a/pw_kvs/flash_memory.cc
+++ b/pw_kvs/flash_memory.cc
@@ -83,23 +83,21 @@
   }
 
   byte buffer[kMaxFlashAlignment];
-
-  // TODO(pwrev/215): Stop using erased_pattern_buffer to save stack.
-  byte erased_pattern_buffer[kMaxFlashAlignment];
-
+  const byte erased_byte = flash_.erased_memory_content();
   size_t offset = 0;
-  std::memset(erased_pattern_buffer,
-              int(flash_.erased_memory_content()),
-              sizeof(erased_pattern_buffer));
   *is_erased = false;
   while (length > 0u) {
     // Check earlier that length is aligned, no need to round up
     size_t read_size = std::min(sizeof(buffer), length);
     TRY(Read(source_flash_address + offset, read_size, buffer).status());
-    if (std::memcmp(buffer, erased_pattern_buffer, read_size)) {
-      // Detected memory chunk is not entirely erased
-      return Status::OK;
+
+    for (byte b : std::span(buffer, read_size)) {
+      if (b != erased_byte) {
+        // Detected memory chunk is not entirely erased
+        return Status::OK;
+      }
     }
+
     offset += read_size;
     length -= read_size;
   }
diff --git a/pw_kvs/flash_partition_test.cc b/pw_kvs/flash_partition_test.cc
index 5e90ac9..df3d1c6 100644
--- a/pw_kvs/flash_partition_test.cc
+++ b/pw_kvs/flash_partition_test.cc
@@ -138,9 +138,17 @@
     ASSERT_EQ(block_size, status.size());
   }
 
+  // Preset the flag to make sure the check actually sets it.
+  bool is_erased = true;
+  ASSERT_EQ(Status::OK,
+            test_partition.IsRegionErased(
+                0, test_partition.size_bytes(), &is_erased));
+  ASSERT_EQ(false, is_erased);
+
   ASSERT_EQ(Status::OK, test_partition.Erase());
 
-  bool is_erased;
+  // Preset the flag to make sure the check actually sets it.
+  is_erased = false;
   ASSERT_EQ(Status::OK,
             test_partition.IsRegionErased(
                 0, test_partition.size_bytes(), &is_erased));