[libc-commits] [PATCH] D127914: [libc] fix line buffered empty file writes

Michael Jones via Phabricator via libc-commits libc-commits at lists.llvm.org
Thu Jun 16 09:55:12 PDT 2022


This revision was automatically updated to reflect the committed changes.
Closed by commit rG5bcda1d3a937: [libc] fix line buffered empty file writes (authored by michaelrj).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127914/new/

https://reviews.llvm.org/D127914

Files:
  libc/src/__support/File/file.cpp
  libc/test/src/__support/File/file_test.cpp


Index: libc/test/src/__support/File/file_test.cpp
===================================================================
--- libc/test/src/__support/File/file_test.cpp
+++ libc/test/src/__support/File/file_test.cpp
@@ -458,3 +458,30 @@
   ASSERT_EQ(f_lbf->close(), 0);
   ASSERT_EQ(f_nbf->close(), 0);
 }
+
+TEST(LlvmLibcFileTest, WriteNothing) {
+  const char WRITE_DATA[] = "";
+  constexpr size_t WRITE_SIZE = 0;
+  constexpr size_t FILE_BUFFER_SIZE = 5;
+  char file_buffer_fbf[FILE_BUFFER_SIZE];
+  char file_buffer_lbf[FILE_BUFFER_SIZE];
+  char file_buffer_nbf[FILE_BUFFER_SIZE];
+  StringFile *f_fbf =
+      new_string_file(file_buffer_fbf, FILE_BUFFER_SIZE, _IOFBF, false, "w");
+  StringFile *f_lbf =
+      new_string_file(file_buffer_lbf, FILE_BUFFER_SIZE, _IOLBF, false, "w");
+  StringFile *f_nbf =
+      new_string_file(file_buffer_nbf, FILE_BUFFER_SIZE, _IONBF, false, "w");
+
+  ASSERT_EQ(WRITE_SIZE, f_fbf->write(WRITE_DATA, WRITE_SIZE));
+  ASSERT_EQ(WRITE_SIZE, f_lbf->write(WRITE_DATA, WRITE_SIZE));
+  ASSERT_EQ(WRITE_SIZE, f_nbf->write(WRITE_DATA, WRITE_SIZE));
+
+  ASSERT_FALSE(f_fbf->error_unlocked());
+  ASSERT_FALSE(f_lbf->error_unlocked());
+  ASSERT_FALSE(f_nbf->error_unlocked());
+
+  ASSERT_EQ(f_fbf->close(), 0);
+  ASSERT_EQ(f_lbf->close(), 0);
+  ASSERT_EQ(f_nbf->close(), 0);
+}
Index: libc/src/__support/File/file.cpp
===================================================================
--- libc/src/__support/File/file.cpp
+++ libc/src/__support/File/file.cpp
@@ -130,9 +130,9 @@
 size_t File::write_unlocked_lbf(const void *data, size_t len) {
   constexpr char NEWLINE_CHAR = '\n';
   size_t last_newline = len;
-  for (size_t i = len - 1; i > 0; --i) {
-    if (static_cast<const char *>(data)[i] == NEWLINE_CHAR) {
-      last_newline = i;
+  for (size_t i = len; i > 1; --i) {
+    if (static_cast<const char *>(data)[i - 1] == NEWLINE_CHAR) {
+      last_newline = i - 1;
       break;
     }
   }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D127914.437583.patch
Type: text/x-patch
Size: 1942 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libc-commits/attachments/20220616/abb4b216/attachment.bin>


More information about the libc-commits mailing list