[libc-commits] [libc] [libc][NFC] Extract File line reader to __support (PR #244261)
Jeff Bailey via libc-commits
libc-commits at lists.llvm.org
Thu Nov 19 10:55:19 PST 2026
https://github.com/kaladron updated https://github.com/llvm/llvm-project/pull/244261
>From a9c187e20af5fe4a68329baacf31e026a3759a5d Mon Sep 17 00:00:00 2001
From: Jeff Bailey <jbailey at raspberryginger.com>
Date: Thu, 19 Nov 2026 13:01:35 +0000
Subject: [PATCH 1/2] [libc][NFC] Extract File line reader to __support
Move the line-oriented File reader and growable buffer out of pwd into
common __support headers for reuse across database parsers:
* Move DynamicBuffer and ScopedDynamicBuffer into LIBC_NAMESPACE
* Extract ReadLineResult and read_line overloads to File/line_reader.h
* Migrate FlatFileDatabase and its pwd/grp callers to the new headers
Assisted-by: Automated tooling, human reviewed.
---
libc/src/__support/CMakeLists.txt | 15 ++
libc/src/__support/File/CMakeLists.txt | 17 ++
libc/src/__support/File/line_reader.h | 168 +++++++++++++++
libc/src/__support/{pwd => }/dynamic_buffer.h | 10 +-
libc/src/__support/pwd/CMakeLists.txt | 20 +-
libc/src/__support/pwd/flat_file_db.h | 130 +-----------
libc/src/grp/CMakeLists.txt | 2 +-
libc/src/grp/grp_utils.cpp | 6 +-
libc/src/pwd/CMakeLists.txt | 2 +-
libc/src/pwd/pwd_utils.cpp | 2 +-
libc/test/src/__support/File/CMakeLists.txt | 22 ++
.../src/__support/File/line_reader_test.cpp | 191 ++++++++++++++++++
libc/test/src/__support/pwd/CMakeLists.txt | 2 +-
.../src/__support/pwd/flat_file_db_test.cpp | 10 +-
14 files changed, 435 insertions(+), 162 deletions(-)
create mode 100644 libc/src/__support/File/line_reader.h
rename libc/src/__support/{pwd => }/dynamic_buffer.h (92%)
create mode 100644 libc/test/src/__support/File/line_reader_test.cpp
diff --git a/libc/src/__support/CMakeLists.txt b/libc/src/__support/CMakeLists.txt
index 9b1089fa48c8c3..aeaf2cd3b60f7b 100644
--- a/libc/src/__support/CMakeLists.txt
+++ b/libc/src/__support/CMakeLists.txt
@@ -390,6 +390,21 @@ add_header_library(
libc.src.__support.common
)
+add_header_library(
+ dynamic_buffer
+ HDRS
+ dynamic_buffer.h
+ DEPENDS
+ libc.hdr.func.free
+ libc.hdr.func.realloc
+ libc.hdr.types.size_t
+ libc.src.__support.CPP.limits
+ libc.src.__support.CPP.span
+ libc.src.__support.CPP.type_traits
+ libc.src.__support.macros.attributes
+ libc.src.__support.macros.config
+)
+
add_header_library(
number_pair
HDRS
diff --git a/libc/src/__support/File/CMakeLists.txt b/libc/src/__support/File/CMakeLists.txt
index d3fbe37b94839b..61e20fdff7689b 100644
--- a/libc/src/__support/File/CMakeLists.txt
+++ b/libc/src/__support/File/CMakeLists.txt
@@ -42,6 +42,23 @@ add_object_library(
libc.src.string.memory_utils.inline_memcpy
)
+add_header_library(
+ line_reader
+ HDRS
+ line_reader.h
+ DEPENDS
+ .file
+ libc.hdr.errno_macros
+ libc.hdr.types.size_t
+ libc.src.__support.CPP.limits
+ libc.src.__support.CPP.span
+ libc.src.__support.dynamic_buffer
+ libc.src.__support.error_or
+ libc.src.__support.macros.attributes
+ libc.src.__support.macros.config
+ libc.src.__support.macros.optimization
+)
+
add_header_library(
dir_scan_result
HDRS
diff --git a/libc/src/__support/File/line_reader.h b/libc/src/__support/File/line_reader.h
new file mode 100644
index 00000000000000..c0c1ace72486de
--- /dev/null
+++ b/libc/src/__support/File/line_reader.h
@@ -0,0 +1,168 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Line-oriented reader for File streams.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_FILE_LINE_READER_H
+#define LLVM_LIBC_SRC___SUPPORT_FILE_LINE_READER_H
+
+#include "hdr/errno_macros.h"
+#include "hdr/types/size_t.h"
+#include "src/__support/CPP/limits.h"
+#include "src/__support/CPP/span.h"
+#include "src/__support/File/file.h"
+#include "src/__support/dynamic_buffer.h"
+#include "src/__support/error_or.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/optimization.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+// Struct to hold the result of a line read operation.
+struct ReadLineResult {
+ // Byte length of the returned line after stripping any trailing '\n' and
+ // excluding the terminating '\0'. Embedded '\0' bytes and preceding '\r'
+ // bytes are preserved and included in this count.
+ size_t bytes_read;
+ bool truncated;
+ // True only when zero raw bytes were read because the stream was already at
+ // EOF. A blank line ("\n") or a final line without a trailing newline
+ // consumes at least one raw byte and returns eof == false (with
+ // bytes_read == 0 for "\n"); the following call returns eof == true.
+ bool eof;
+};
+
+// Reads a single line from the given file into the provided buffer, stripping
+// any trailing '\n' and ensuring the result is null-terminated. A line too
+// long for the buffer is reported as truncated after draining the remainder of
+// the line up to '\n' or EOF.
+//
+// Note: POSIX getline/getdelim cannot be used here because bounded callers
+// must operate in-place within a fixed buffer without dynamic heap
+// allocations. See the DynamicBuffer overload for callers that own their
+// buffer and may grow it.
+[[nodiscard]] LIBC_INLINE ErrorOr<ReadLineResult>
+read_line(File *f, cpp::span<char> buf) {
+ if (!f)
+ return Error(EINVAL);
+ if (buf.size() < 2)
+ return Error(ERANGE);
+
+ File::FileLock lock(f);
+ size_t bytes_read = 0;
+ bool found_newline = false;
+ bool saw_eof = false;
+ bool truncated = false;
+
+ for (char &ch : buf.first(buf.size() - 1)) {
+ FileIOResult result = f->read_unlocked(&ch, 1);
+ if (result.has_error())
+ return Error(result.error);
+ if (result.value != 1) {
+ saw_eof = true;
+ break;
+ }
+ ++bytes_read;
+ if (ch == '\n') {
+ found_newline = true;
+ break;
+ }
+ }
+
+ if (!found_newline && !saw_eof) {
+ char c = '\0';
+ while (true) {
+ FileIOResult result = f->read_unlocked(&c, 1);
+ if (result.has_error())
+ return Error(result.error);
+ if (result.value != 1 || c == '\n')
+ break;
+ truncated = true;
+ }
+ }
+
+ if (f->error_unlocked())
+ return Error(EIO);
+
+ bool eof = (bytes_read == 0);
+
+ // If the line ended with a newline, strip it.
+ if (found_newline)
+ --bytes_read;
+
+ buf[bytes_read] = '\0';
+ return ReadLineResult{bytes_read, truncated, eof};
+}
+
+// Reads a single line into a caller-owned buffer, growing it as needed so
+// that arbitrarily long lines can be read. Otherwise behaves as the
+// fixed-buffer read_line overload; the result is never truncated. Does not
+// allocate when the stream is immediately at EOF (so an empty DynamicBuffer
+// stays unallocated when eof is true). On allocation failure, drains the rest
+// of the current line up to '\n' or EOF before returning ENOMEM.
+[[nodiscard]] LIBC_INLINE ErrorOr<ReadLineResult>
+read_line(File *f, DynamicBuffer &buf) {
+ if (!f)
+ return Error(EINVAL);
+
+ File::FileLock lock(f);
+ size_t bytes_read = 0;
+ bool found_newline = false;
+
+ while (true) {
+ char ch = '\0';
+ FileIOResult result = f->read_unlocked(&ch, 1);
+ if (result.has_error())
+ return Error(result.error);
+ if (result.value != 1)
+ break;
+
+ // One byte for the character just read, one for the terminator.
+ if (LIBC_UNLIKELY(bytes_read > cpp::numeric_limits<size_t>::max() - 2) ||
+ !buf.reserve(bytes_read + 2)) {
+ if (ch != '\n') {
+ char c = '\0';
+ while (true) {
+ FileIOResult drain = f->read_unlocked(&c, 1);
+ if (drain.has_error())
+ return Error(drain.error);
+ if (drain.value != 1 || c == '\n')
+ break;
+ }
+ }
+ return Error(ENOMEM);
+ }
+
+ buf.span()[bytes_read++] = ch;
+ if (ch == '\n') {
+ found_newline = true;
+ break;
+ }
+ }
+
+ if (f->error_unlocked())
+ return Error(EIO);
+
+ bool eof = (bytes_read == 0);
+
+ // If the line ended with a newline, strip it.
+ if (found_newline)
+ --bytes_read;
+
+ if (!buf.span().empty())
+ buf.span()[bytes_read] = '\0';
+ return ReadLineResult{bytes_read, /*truncated=*/false, eof};
+}
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC___SUPPORT_FILE_LINE_READER_H
diff --git a/libc/src/__support/pwd/dynamic_buffer.h b/libc/src/__support/dynamic_buffer.h
similarity index 92%
rename from libc/src/__support/pwd/dynamic_buffer.h
rename to libc/src/__support/dynamic_buffer.h
index 44d269071c173f..8160d1434e45df 100644
--- a/libc/src/__support/pwd/dynamic_buffer.h
+++ b/libc/src/__support/dynamic_buffer.h
@@ -11,8 +11,8 @@
///
//===----------------------------------------------------------------------===//
-#ifndef LLVM_LIBC_SRC___SUPPORT_PWD_DYNAMIC_BUFFER_H
-#define LLVM_LIBC_SRC___SUPPORT_PWD_DYNAMIC_BUFFER_H
+#ifndef LLVM_LIBC_SRC___SUPPORT_DYNAMIC_BUFFER_H
+#define LLVM_LIBC_SRC___SUPPORT_DYNAMIC_BUFFER_H
#include "hdr/func/free.h"
#include "hdr/func/realloc.h"
@@ -24,9 +24,8 @@
#include "src/__support/macros/config.h"
namespace LIBC_NAMESPACE_DECL {
-namespace pwd {
-// A heap-backed, growable byte buffer for the flat-file database engine.
+// A heap-backed, growable byte buffer.
//
// This type is trivially destructible by design, so an instance can be a
// constant-initialised process global. The owner releases the storage
@@ -98,7 +97,6 @@ class ScopedDynamicBuffer : public DynamicBuffer {
LIBC_INLINE ~ScopedDynamicBuffer() { this->release(); }
};
-} // namespace pwd
} // namespace LIBC_NAMESPACE_DECL
-#endif // LLVM_LIBC_SRC___SUPPORT_PWD_DYNAMIC_BUFFER_H
+#endif // LLVM_LIBC_SRC___SUPPORT_DYNAMIC_BUFFER_H
diff --git a/libc/src/__support/pwd/CMakeLists.txt b/libc/src/__support/pwd/CMakeLists.txt
index ccf32531ab69d1..fe71c91a09ca25 100644
--- a/libc/src/__support/pwd/CMakeLists.txt
+++ b/libc/src/__support/pwd/CMakeLists.txt
@@ -10,34 +10,18 @@ add_header_library(
libc.src.__support.macros.config
)
-add_header_library(
- dynamic_buffer
- HDRS
- dynamic_buffer.h
- DEPENDS
- libc.hdr.func.free
- libc.hdr.func.realloc
- libc.hdr.types.size_t
- libc.src.__support.CPP.limits
- libc.src.__support.CPP.span
- libc.src.__support.CPP.type_traits
- libc.src.__support.macros.attributes
- libc.src.__support.macros.config
-)
-
add_header_library(
flat_file_db
HDRS
flat_file_db.h
DEPENDS
- .dynamic_buffer
libc.hdr.errno_macros
libc.hdr.stdio_macros
- libc.hdr.types.size_t
libc.src.__support.CPP.functional
- libc.src.__support.CPP.limits
libc.src.__support.CPP.span
libc.src.__support.File.file
+ libc.src.__support.File.line_reader
+ libc.src.__support.dynamic_buffer
libc.src.__support.error_or
libc.src.__support.macros.attributes
libc.src.__support.macros.config
diff --git a/libc/src/__support/pwd/flat_file_db.h b/libc/src/__support/pwd/flat_file_db.h
index 501c39450285e4..68e9f1751a60cc 100644
--- a/libc/src/__support/pwd/flat_file_db.h
+++ b/libc/src/__support/pwd/flat_file_db.h
@@ -16,30 +16,18 @@
#include "hdr/errno_macros.h"
#include "hdr/stdio_macros.h"
-#include "hdr/types/size_t.h"
#include "src/__support/CPP/functional.h"
-#include "src/__support/CPP/limits.h"
#include "src/__support/CPP/span.h"
#include "src/__support/File/file.h"
+#include "src/__support/File/line_reader.h"
+#include "src/__support/dynamic_buffer.h"
#include "src/__support/error_or.h"
#include "src/__support/macros/attributes.h"
#include "src/__support/macros/config.h"
-#include "src/__support/pwd/dynamic_buffer.h"
namespace LIBC_NAMESPACE_DECL {
namespace pwd {
-// Struct to hold the result of a line read operation.
-struct ReadLineResult {
- size_t bytes_read;
- bool truncated;
- // True only when zero raw bytes were read because the stream was already at
- // EOF. A blank line ("\n") or a final line without a trailing newline
- // consumes at least one raw byte and returns eof == false (with
- // bytes_read == 0 for "\n"); the following call returns eof == true.
- bool eof;
-};
-
// Parses a record in place and fills entry.
// line is the record bytes including the terminating NUL (line.back() == '\0').
// scratch is spare writable storage for auxiliary structures (such as pointer
@@ -70,115 +58,6 @@ template <typename EntryType> class FlatFileDatabase {
return {};
}
- // Reads a single line from the given file into the provided buffer, stripping
- // any trailing '\n' and ensuring the result is null-terminated. A line too
- // long for the buffer is reported as truncated.
- //
- // Note: POSIX getline/getdelim cannot be used here because user database
- // iteration and lookups must operate in-place within a fixed, bounded buffer
- // without dynamic heap allocations during getnext. See read_line_growing for
- // the variant used by the non-reentrant interfaces, which own their buffer
- // and may grow it.
- LIBC_INLINE static ErrorOr<ReadLineResult> read_line(File *f,
- cpp::span<char> buf) {
- if (!f)
- return Error(EINVAL);
- if (buf.size() < 2)
- return Error(ERANGE);
-
- File::FileLock lock(f);
- size_t bytes_read = 0;
- FileIOResult result(0);
- bool truncated = false;
-
- for (char &ch : buf.first(buf.size() - 1)) {
- result = f->read_unlocked(&ch, 1);
- if (result.has_error())
- return Error(result.error);
- if (result.value != 1)
- break;
- ++bytes_read;
- if (ch == '\n')
- break;
- }
-
- bool eof = (bytes_read == 0);
-
- auto read_span = buf.first(bytes_read);
- if (result.value == 1 && !read_span.empty() && read_span.back() != '\n') {
- char c = '\0';
- while (true) {
- result = f->read_unlocked(&c, 1);
- if (result.has_error())
- return Error(result.error);
- if (result.value != 1 || c == '\n')
- break;
- truncated = true;
- }
- }
-
- if (f->error_unlocked())
- return Error(EIO);
-
- // If the line ended with a newline, strip it.
- if (!read_span.empty() && read_span.back() == '\n')
- --bytes_read;
-
- buf[bytes_read] = '\0';
- return ReadLineResult{bytes_read, truncated, eof};
- }
-
- // Reads a single line into a caller-owned buffer, growing it as needed so
- // that arbitrarily long records can be read. Otherwise behaves as read_line;
- // the result is never truncated.
- LIBC_INLINE static ErrorOr<ReadLineResult>
- read_line_growing(File *f, DynamicBuffer &buf) {
- if (!f)
- return Error(EINVAL);
-
- File::FileLock lock(f);
- size_t bytes_read = 0;
-
- while (true) {
- // One byte for the character about to be read, one for the terminator.
- if (bytes_read > cpp::numeric_limits<size_t>::max() - 2 ||
- !buf.reserve(bytes_read + 2)) {
- char c = '\0';
- while (true) {
- FileIOResult drain = f->read_unlocked(&c, 1);
- if (drain.has_error())
- return Error(drain.error);
- if (drain.value != 1 || c == '\n')
- break;
- }
- return Error(ENOMEM);
- }
-
- char ch = '\0';
- FileIOResult result = f->read_unlocked(&ch, 1);
- if (result.has_error())
- return Error(result.error);
- if (result.value != 1)
- break;
-
- buf.span()[bytes_read++] = ch;
- if (ch == '\n')
- break;
- }
-
- if (f->error_unlocked())
- return Error(EIO);
-
- bool eof = (bytes_read == 0);
-
- // If the line ended with a newline, strip it.
- if (bytes_read > 0 && buf.span()[bytes_read - 1] == '\n')
- --bytes_read;
-
- buf.span()[bytes_read] = '\0';
- return ReadLineResult{bytes_read, /*truncated=*/false, eof};
- }
-
public:
LIBC_INLINE constexpr explicit FlatFileDatabase(const char *path)
: file_path(path) {}
@@ -279,7 +158,7 @@ template <typename EntryType> class FlatFileDatabase {
}
while (true) {
- auto result = read_line_growing(file, buffer);
+ auto result = read_line(file, buffer);
if (!result.has_value())
return Error(result.error());
@@ -293,8 +172,7 @@ template <typename EntryType> class FlatFileDatabase {
while (true) {
// Slicing at bytes_read + 1 includes the terminating null byte written
- // by read_line_growing; the remainder of the buffer serves as scratch
- // space.
+ // by read_line; the remainder of the buffer serves as scratch space.
auto parse_res = parse_line<EntryType>(
buffer.span().first(res.bytes_read + 1),
buffer.span().subspan(res.bytes_read + 1), entry);
diff --git a/libc/src/grp/CMakeLists.txt b/libc/src/grp/CMakeLists.txt
index 398509182bae9c..3c38f1279d1f95 100644
--- a/libc/src/grp/CMakeLists.txt
+++ b/libc/src/grp/CMakeLists.txt
@@ -186,12 +186,12 @@ add_object_library(
libc.src.__support.File.platform_file
libc.src.__support.OSUtil.linux.syscall_wrappers.setgroups
libc.src.__support.ctype_utils
+ libc.src.__support.dynamic_buffer
libc.src.__support.error_or
libc.src.__support.libc_assert
libc.src.__support.macros.attributes
libc.src.__support.macros.config
libc.src.__support.macros.optimization
- libc.src.__support.pwd.dynamic_buffer
libc.src.__support.pwd.field_tokenizer
libc.src.__support.pwd.flat_file_db
libc.src.__support.str_to_integer
diff --git a/libc/src/grp/grp_utils.cpp b/libc/src/grp/grp_utils.cpp
index e7c341b7f4ef52..c1ff3c814985dd 100644
--- a/libc/src/grp/grp_utils.cpp
+++ b/libc/src/grp/grp_utils.cpp
@@ -26,12 +26,12 @@
#include "src/__support/CPP/string_view.h"
#include "src/__support/OSUtil/linux/syscall_wrappers/setgroups.h"
#include "src/__support/ctype_utils.h"
+#include "src/__support/dynamic_buffer.h"
#include "src/__support/error_or.h"
#include "src/__support/libc_assert.h"
#include "src/__support/macros/attributes.h"
#include "src/__support/macros/config.h"
#include "src/__support/macros/optimization.h"
-#include "src/__support/pwd/dynamic_buffer.h"
#include "src/__support/pwd/field_tokenizer.h"
#include "src/__support/pwd/flat_file_db.h"
#include "src/__support/str_to_integer.h"
@@ -181,7 +181,7 @@ LIBC_CONSTINIT pwd::FlatFileDatabase<struct group>
// record read so far, and is reused without shrinking. endgrent() closes the
// file stream without freeing the buffer so that pointers returned before
// endgrent() remain valid until the next non-reentrant call.
-LIBC_CONSTINIT pwd::DynamicBuffer line_buffer;
+LIBC_CONSTINIT DynamicBuffer line_buffer;
LIBC_CONSTINIT struct group grp_entry = {};
// The lookups are shared between the caller-supplied fixed buffer used by the
@@ -282,7 +282,7 @@ ErrorOr<void> populate_gid_list(cpp::string_view user, gid_t group,
pwd::ScopedFlatFileDatabase<struct group> local_db(path ? path
: group_file_path);
- pwd::ScopedDynamicBuffer buffer;
+ ScopedDynamicBuffer buffer;
struct group entry = {};
const auto open_res = local_db.setdb();
diff --git a/libc/src/pwd/CMakeLists.txt b/libc/src/pwd/CMakeLists.txt
index 0e9097ad33faa2..7b244a4e1fbc13 100644
--- a/libc/src/pwd/CMakeLists.txt
+++ b/libc/src/pwd/CMakeLists.txt
@@ -144,8 +144,8 @@ add_object_library(
libc.src.__support.File.file
libc.src.__support.File.platform_file
libc.src.__support.ctype_utils
+ libc.src.__support.dynamic_buffer
libc.src.__support.error_or
- libc.src.__support.pwd.dynamic_buffer
libc.src.__support.pwd.field_tokenizer
libc.src.__support.pwd.flat_file_db
libc.src.__support.str_to_integer
diff --git a/libc/src/pwd/pwd_utils.cpp b/libc/src/pwd/pwd_utils.cpp
index 56aa34fd4733ca..34e184d84ffb52 100644
--- a/libc/src/pwd/pwd_utils.cpp
+++ b/libc/src/pwd/pwd_utils.cpp
@@ -17,8 +17,8 @@
#include "hdr/types/struct_passwd.h"
#include "src/__support/CPP/span.h"
#include "src/__support/CPP/string_view.h"
+#include "src/__support/dynamic_buffer.h"
#include "src/__support/macros/attributes.h"
-#include "src/__support/pwd/dynamic_buffer.h"
#include "src/__support/pwd/flat_file_db.h"
#include "src/string/string_utils.h"
diff --git a/libc/test/src/__support/File/CMakeLists.txt b/libc/test/src/__support/File/CMakeLists.txt
index f880fe0ef2f527..c2477b052bcedb 100644
--- a/libc/test/src/__support/File/CMakeLists.txt
+++ b/libc/test/src/__support/File/CMakeLists.txt
@@ -31,6 +31,28 @@ add_libc_test(
libc.src.__support.File.file
)
+if(TARGET libc.src.__support.File.platform_file)
+ add_libc_test(
+ line_reader_test
+ SUITE
+ libc-support-tests
+ SRCS
+ line_reader_test.cpp
+ DEPENDS
+ libc.hdr.errno_macros
+ libc.hdr.types.size_t
+ libc.src.__support.CPP.scope
+ libc.src.__support.CPP.span
+ libc.src.__support.CPP.string_view
+ libc.src.__support.File.file
+ libc.src.__support.File.line_reader
+ libc.src.__support.File.platform_file
+ libc.src.__support.dynamic_buffer
+ libc.src.stdio.remove
+ libc.test.UnitTest.MemoryMatcher
+ )
+endif()
+
add_libc_test(
platform_file_test
SUITE
diff --git a/libc/test/src/__support/File/line_reader_test.cpp b/libc/test/src/__support/File/line_reader_test.cpp
new file mode 100644
index 00000000000000..f20f1de8d7c5d0
--- /dev/null
+++ b/libc/test/src/__support/File/line_reader_test.cpp
@@ -0,0 +1,191 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Unit tests for line_reader.
+///
+//===----------------------------------------------------------------------===//
+
+#include "hdr/errno_macros.h"
+#include "hdr/types/size_t.h"
+#include "src/__support/CPP/scope.h"
+#include "src/__support/CPP/span.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/File/file.h"
+#include "src/__support/File/line_reader.h"
+#include "src/__support/dynamic_buffer.h"
+#include "src/stdio/remove.h"
+#include "test/UnitTest/MemoryMatcher.h"
+#include "test/UnitTest/Test.h"
+
+namespace {
+
+using MemoryView = LIBC_NAMESPACE::testing::MemoryView;
+
+LIBC_NAMESPACE::File *open_temp(const char *path,
+ LIBC_NAMESPACE::cpp::string_view content,
+ const char *mode = "r") {
+ auto w = LIBC_NAMESPACE::openfile(path, "w");
+ if (!w.has_value())
+ return nullptr;
+ w.value()->write(content.data(), content.size());
+ w.value()->close();
+ auto r = LIBC_NAMESPACE::openfile(path, mode);
+ return r.has_value() ? r.value() : nullptr;
+}
+
+} // namespace
+
+TEST(LlvmLibcLineReaderTest, InvalidArgumentsAndWriteOnlyStream) {
+ char buf[8];
+ auto null_span = LIBC_NAMESPACE::read_line(nullptr, buf);
+ ASSERT_FALSE(null_span.has_value());
+ EXPECT_EQ(null_span.error(), EINVAL);
+
+ LIBC_NAMESPACE::ScopedDynamicBuffer dyn_buf;
+ auto null_dyn = LIBC_NAMESPACE::read_line(nullptr, dyn_buf);
+ ASSERT_FALSE(null_dyn.has_value());
+ EXPECT_EQ(null_dyn.error(), EINVAL);
+
+ const char *path = libc_make_test_file_path("line_reader_invalid.test");
+ LIBC_NAMESPACE::File *f = open_temp(path, "hello\n", "w");
+ ASSERT_NE(f, nullptr);
+ LIBC_NAMESPACE::cpp::scope_exit cleanup([&]() {
+ f->close();
+ LIBC_NAMESPACE::remove(path);
+ });
+
+ char one_byte[1];
+ auto small = LIBC_NAMESPACE::read_line(f, one_byte);
+ ASSERT_FALSE(small.has_value());
+ EXPECT_EQ(small.error(), ERANGE);
+
+ auto bad_span = LIBC_NAMESPACE::read_line(f, buf);
+ ASSERT_FALSE(bad_span.has_value());
+ EXPECT_EQ(bad_span.error(), EBADF);
+
+ auto bad_dyn = LIBC_NAMESPACE::read_line(f, dyn_buf);
+ ASSERT_FALSE(bad_dyn.has_value());
+ EXPECT_EQ(bad_dyn.error(), EBADF);
+ EXPECT_EQ(dyn_buf.capacity(), size_t{0});
+}
+
+TEST(LlvmLibcLineReaderTest, FixedSpanReadTruncateAndEof) {
+ const char *path = libc_make_test_file_path("line_reader_span.test");
+ LIBC_NAMESPACE::File *f = open_temp(path, "abcd\n\nefghi\nok");
+ ASSERT_NE(f, nullptr);
+ LIBC_NAMESPACE::cpp::scope_exit cleanup([&]() {
+ f->close();
+ LIBC_NAMESPACE::remove(path);
+ });
+
+ // Size 5 holds 4 chars + NUL: "abcd\n" fits, "\n" is blank, "efghi\n"
+ // truncates and drains, "ok" has no trailing newline, then EOF.
+ char buf[5];
+
+ auto r1 = LIBC_NAMESPACE::read_line(f, buf);
+ ASSERT_TRUE(r1.has_value());
+ EXPECT_EQ(r1->bytes_read, size_t{4});
+ EXPECT_FALSE(r1->truncated);
+ EXPECT_FALSE(r1->eof);
+ EXPECT_STREQ(buf, "abcd");
+
+ auto r2 = LIBC_NAMESPACE::read_line(f, buf);
+ ASSERT_TRUE(r2.has_value());
+ EXPECT_EQ(r2->bytes_read, size_t{0});
+ EXPECT_FALSE(r2->eof);
+ EXPECT_STREQ(buf, "");
+
+ auto r3 = LIBC_NAMESPACE::read_line(f, buf);
+ ASSERT_TRUE(r3.has_value());
+ EXPECT_EQ(r3->bytes_read, size_t{4});
+ EXPECT_TRUE(r3->truncated);
+ EXPECT_STREQ(buf, "efgh");
+
+ auto r4 = LIBC_NAMESPACE::read_line(f, buf);
+ ASSERT_TRUE(r4.has_value());
+ EXPECT_EQ(r4->bytes_read, size_t{2});
+ EXPECT_FALSE(r4->truncated);
+ EXPECT_FALSE(r4->eof);
+ EXPECT_STREQ(buf, "ok");
+
+ auto r5 = LIBC_NAMESPACE::read_line(f, buf);
+ ASSERT_TRUE(r5.has_value());
+ EXPECT_EQ(r5->bytes_read, size_t{0});
+ EXPECT_TRUE(r5->eof);
+ EXPECT_STREQ(buf, "");
+}
+
+TEST(LlvmLibcLineReaderTest, EmbeddedNullAndCarriageReturnPreserved) {
+ constexpr char RAW[] = "ab\0cd\r\n";
+ const char *path = libc_make_test_file_path("line_reader_nul.test");
+ LIBC_NAMESPACE::File *f =
+ open_temp(path, LIBC_NAMESPACE::cpp::string_view(RAW, sizeof(RAW) - 1));
+ ASSERT_NE(f, nullptr);
+ LIBC_NAMESPACE::cpp::scope_exit cleanup([&]() {
+ f->close();
+ LIBC_NAMESPACE::remove(path);
+ });
+
+ char buf[16];
+ auto r = LIBC_NAMESPACE::read_line(f, buf);
+ ASSERT_TRUE(r.has_value());
+ EXPECT_EQ(r->bytes_read, size_t{6});
+ EXPECT_MEM_EQ(MemoryView("ab\0cd\r\0", 7), MemoryView(buf, 7));
+}
+
+TEST(LlvmLibcLineReaderTest, DynamicBufferGrowthReuseAndEmptyEof) {
+ LIBC_NAMESPACE::ScopedDynamicBuffer dyn_buf;
+
+ // Immediate EOF on a fresh DynamicBuffer does not allocate.
+ {
+ const char *empty_path = libc_make_test_file_path("line_reader_empty.test");
+ LIBC_NAMESPACE::File *empty_f = open_temp(empty_path, "");
+ ASSERT_NE(empty_f, nullptr);
+ LIBC_NAMESPACE::cpp::scope_exit cleanup_empty([&]() {
+ empty_f->close();
+ LIBC_NAMESPACE::remove(empty_path);
+ });
+
+ auto eof = LIBC_NAMESPACE::read_line(empty_f, dyn_buf);
+ ASSERT_TRUE(eof.has_value());
+ EXPECT_TRUE(eof->eof);
+ EXPECT_EQ(dyn_buf.capacity(), size_t{0});
+ }
+
+ constexpr size_t LONG_LEN = 2500;
+ char content[LONG_LEN + 8];
+ for (size_t i = 0; i < LONG_LEN; ++i)
+ content[i] = static_cast<char>('a' + (i % 26));
+ content[LONG_LEN] = '\n';
+ content[LONG_LEN + 1] = 'h';
+ content[LONG_LEN + 2] = 'i';
+
+ const char *long_path = libc_make_test_file_path("line_reader_long.test");
+ LIBC_NAMESPACE::File *long_f = open_temp(
+ long_path, LIBC_NAMESPACE::cpp::string_view(content, LONG_LEN + 3));
+ ASSERT_NE(long_f, nullptr);
+ LIBC_NAMESPACE::cpp::scope_exit cleanup_long([&]() {
+ long_f->close();
+ LIBC_NAMESPACE::remove(long_path);
+ });
+
+ auto r1 = LIBC_NAMESPACE::read_line(long_f, dyn_buf);
+ ASSERT_TRUE(r1.has_value());
+ EXPECT_EQ(r1->bytes_read, LONG_LEN);
+ EXPECT_FALSE(r1->truncated);
+ EXPECT_MEM_EQ(MemoryView(content, LONG_LEN),
+ MemoryView(dyn_buf.span().data(), r1->bytes_read));
+
+ const size_t CAP = dyn_buf.capacity();
+ auto r2 = LIBC_NAMESPACE::read_line(long_f, dyn_buf);
+ ASSERT_TRUE(r2.has_value());
+ EXPECT_EQ(r2->bytes_read, size_t{2});
+ EXPECT_EQ(dyn_buf.capacity(), CAP);
+ EXPECT_STREQ(dyn_buf.span().data(), "hi");
+}
diff --git a/libc/test/src/__support/pwd/CMakeLists.txt b/libc/test/src/__support/pwd/CMakeLists.txt
index a63fe2ecb010db..b4554443b9912b 100644
--- a/libc/test/src/__support/pwd/CMakeLists.txt
+++ b/libc/test/src/__support/pwd/CMakeLists.txt
@@ -27,8 +27,8 @@ add_libc_test(
libc.src.__support.CPP.string_view
libc.src.__support.File.file
libc.src.__support.File.platform_file
+ libc.src.__support.dynamic_buffer
libc.src.__support.error_or
- libc.src.__support.pwd.dynamic_buffer
libc.src.__support.pwd.field_tokenizer
libc.src.__support.pwd.flat_file_db
libc.src.stdio.remove
diff --git a/libc/test/src/__support/pwd/flat_file_db_test.cpp b/libc/test/src/__support/pwd/flat_file_db_test.cpp
index 69f1370cb1421b..fc046fe26211f7 100644
--- a/libc/test/src/__support/pwd/flat_file_db_test.cpp
+++ b/libc/test/src/__support/pwd/flat_file_db_test.cpp
@@ -16,8 +16,8 @@
#include "src/__support/CPP/span.h"
#include "src/__support/CPP/string_view.h"
#include "src/__support/File/file.h"
+#include "src/__support/dynamic_buffer.h"
#include "src/__support/error_or.h"
-#include "src/__support/pwd/dynamic_buffer.h"
#include "src/__support/pwd/field_tokenizer.h"
#include "src/__support/pwd/flat_file_db.h"
#include "src/stdio/remove.h"
@@ -271,7 +271,7 @@ TEST_F(LlvmLibcFlatFileDbTest, DynamicBufferReadsArbitrarilyLongLines) {
LIBC_NAMESPACE::pwd::ScopedFlatFileDatabase<SimpleTestEntry> db(
test_file.get_path());
- LIBC_NAMESPACE::pwd::ScopedDynamicBuffer buffer;
+ LIBC_NAMESPACE::ScopedDynamicBuffer buffer;
SimpleTestEntry entry;
auto r1 = db.getnext(&entry, buffer);
@@ -314,7 +314,7 @@ TEST_F(LlvmLibcFlatFileDbTest, LookupOversizedPrecedingRecord) {
// DynamicBuffer lookup grows the buffer across oversized preceding records
// and locates the target entry.
- LIBC_NAMESPACE::pwd::ScopedDynamicBuffer dyn_buffer;
+ LIBC_NAMESPACE::ScopedDynamicBuffer dyn_buffer;
auto dyn_res = db.lookup(matcher, &entry, dyn_buffer);
ASSERT_TRUE(dyn_res.has_value());
ASSERT_TRUE(dyn_res.value());
@@ -323,7 +323,7 @@ TEST_F(LlvmLibcFlatFileDbTest, LookupOversizedPrecedingRecord) {
}
TEST_F(LlvmLibcFlatFileDbTest, DynamicBufferReserveGrowRelease) {
- LIBC_NAMESPACE::pwd::ScopedDynamicBuffer buffer;
+ LIBC_NAMESPACE::ScopedDynamicBuffer buffer;
EXPECT_EQ(buffer.capacity(), static_cast<size_t>(0));
ASSERT_TRUE(buffer.grow());
@@ -362,7 +362,7 @@ TEST_F(LlvmLibcFlatFileDbTest,
// DynamicBuffer grows until scratch requirement (2048 bytes) is satisfied.
LIBC_NAMESPACE::pwd::ScopedFlatFileDatabase<ScratchRequiringEntry> db_dyn(
test_file.get_path());
- LIBC_NAMESPACE::pwd::ScopedDynamicBuffer dyn_buffer;
+ LIBC_NAMESPACE::ScopedDynamicBuffer dyn_buffer;
ScratchRequiringEntry dyn_entry;
auto dyn_res = db_dyn.getnext(&dyn_entry, dyn_buffer);
ASSERT_TRUE(dyn_res.has_value());
>From 412589bec72decabe219c23512b9352bcd6fc384 Mon Sep 17 00:00:00 2001
From: Jeff Bailey <jbailey at raspberryginger.com>
Date: Thu, 19 Nov 2026 18:55:02 +0000
Subject: [PATCH 2/2] [libc][NFC] Simplify read_line per review feedback
Apply review feedback to File/line_reader.h:
* Assert f != nullptr instead of returning EINVAL
* Leave NUL-termination to callers and drop the < 2 byte check
* Use f->iseof_unlocked() instead of a local saw_eof flag
* Drop the unreachable f->error_unlocked() check
Assisted-by: Automated tooling, human reviewed.
---
libc/src/__support/File/CMakeLists.txt | 1 +
libc/src/__support/File/line_reader.h | 103 +++++++-----------
libc/src/__support/pwd/flat_file_db.h | 16 ++-
.../src/__support/File/line_reader_test.cpp | 97 ++++++++++-------
4 files changed, 111 insertions(+), 106 deletions(-)
diff --git a/libc/src/__support/File/CMakeLists.txt b/libc/src/__support/File/CMakeLists.txt
index 61e20fdff7689b..fd9d588b292832 100644
--- a/libc/src/__support/File/CMakeLists.txt
+++ b/libc/src/__support/File/CMakeLists.txt
@@ -54,6 +54,7 @@ add_header_library(
libc.src.__support.CPP.span
libc.src.__support.dynamic_buffer
libc.src.__support.error_or
+ libc.src.__support.libc_assert
libc.src.__support.macros.attributes
libc.src.__support.macros.config
libc.src.__support.macros.optimization
diff --git a/libc/src/__support/File/line_reader.h b/libc/src/__support/File/line_reader.h
index c0c1ace72486de..97ef6179aa074e 100644
--- a/libc/src/__support/File/line_reader.h
+++ b/libc/src/__support/File/line_reader.h
@@ -21,6 +21,7 @@
#include "src/__support/File/file.h"
#include "src/__support/dynamic_buffer.h"
#include "src/__support/error_or.h"
+#include "src/__support/libc_assert.h"
#include "src/__support/macros/attributes.h"
#include "src/__support/macros/config.h"
#include "src/__support/macros/optimization.h"
@@ -29,9 +30,9 @@ namespace LIBC_NAMESPACE_DECL {
// Struct to hold the result of a line read operation.
struct ReadLineResult {
- // Byte length of the returned line after stripping any trailing '\n' and
- // excluding the terminating '\0'. Embedded '\0' bytes and preceding '\r'
- // bytes are preserved and included in this count.
+ // Byte length of the returned line after stripping any trailing '\n'.
+ // Embedded '\0' bytes and preceding '\r' bytes are preserved and included in
+ // this count.
size_t bytes_read;
bool truncated;
// True only when zero raw bytes were read because the stream was already at
@@ -42,9 +43,10 @@ struct ReadLineResult {
};
// Reads a single line from the given file into the provided buffer, stripping
-// any trailing '\n' and ensuring the result is null-terminated. A line too
-// long for the buffer is reported as truncated after draining the remainder of
-// the line up to '\n' or EOF.
+// any trailing '\n'. Does not null-terminate buf; callers that need a C string
+// should pass a span with room for a trailing NUL and write buf[bytes_read]. A
+// line too long for the buffer is reported as truncated after draining the
+// remainder of the line up to '\n' or EOF.
//
// Note: POSIX getline/getdelim cannot be used here because bounded callers
// must operate in-place within a fixed buffer without dynamic heap
@@ -52,71 +54,59 @@ struct ReadLineResult {
// buffer and may grow it.
[[nodiscard]] LIBC_INLINE ErrorOr<ReadLineResult>
read_line(File *f, cpp::span<char> buf) {
- if (!f)
- return Error(EINVAL);
- if (buf.size() < 2)
- return Error(ERANGE);
+ LIBC_ASSERT(f != nullptr);
File::FileLock lock(f);
size_t bytes_read = 0;
+ bool saw_bytes = false;
bool found_newline = false;
- bool saw_eof = false;
bool truncated = false;
- for (char &ch : buf.first(buf.size() - 1)) {
+ for (char &ch : buf) {
FileIOResult result = f->read_unlocked(&ch, 1);
if (result.has_error())
return Error(result.error);
- if (result.value != 1) {
- saw_eof = true;
+ if (result.value != 1)
break;
- }
- ++bytes_read;
+ saw_bytes = true;
if (ch == '\n') {
found_newline = true;
break;
}
+ ++bytes_read;
}
- if (!found_newline && !saw_eof) {
+ if (!found_newline && !f->iseof_unlocked()) {
char c = '\0';
while (true) {
FileIOResult result = f->read_unlocked(&c, 1);
if (result.has_error())
return Error(result.error);
- if (result.value != 1 || c == '\n')
+ if (result.value != 1)
+ break;
+ saw_bytes = true;
+ if (c == '\n')
break;
truncated = true;
}
}
- if (f->error_unlocked())
- return Error(EIO);
-
- bool eof = (bytes_read == 0);
-
- // If the line ended with a newline, strip it.
- if (found_newline)
- --bytes_read;
-
- buf[bytes_read] = '\0';
- return ReadLineResult{bytes_read, truncated, eof};
+ return ReadLineResult{bytes_read, truncated, !saw_bytes};
}
// Reads a single line into a caller-owned buffer, growing it as needed so
// that arbitrarily long lines can be read. Otherwise behaves as the
-// fixed-buffer read_line overload; the result is never truncated. Does not
-// allocate when the stream is immediately at EOF (so an empty DynamicBuffer
-// stays unallocated when eof is true). On allocation failure, drains the rest
-// of the current line up to '\n' or EOF before returning ENOMEM.
+// fixed-buffer read_line overload; the result is never truncated and not
+// null-terminated. Does not allocate on immediate EOF or blank lines. On
+// allocation failure, drains the rest of the current line up to '\n' or EOF
+// before returning ENOMEM.
[[nodiscard]] LIBC_INLINE ErrorOr<ReadLineResult>
read_line(File *f, DynamicBuffer &buf) {
- if (!f)
- return Error(EINVAL);
+ LIBC_ASSERT(f != nullptr);
File::FileLock lock(f);
size_t bytes_read = 0;
- bool found_newline = false;
+ bool saw_bytes = false;
while (true) {
char ch = '\0';
@@ -125,42 +115,27 @@ read_line(File *f, DynamicBuffer &buf) {
return Error(result.error);
if (result.value != 1)
break;
+ saw_bytes = true;
+ if (ch == '\n')
+ break;
- // One byte for the character just read, one for the terminator.
- if (LIBC_UNLIKELY(bytes_read > cpp::numeric_limits<size_t>::max() - 2) ||
- !buf.reserve(bytes_read + 2)) {
- if (ch != '\n') {
- char c = '\0';
- while (true) {
- FileIOResult drain = f->read_unlocked(&c, 1);
- if (drain.has_error())
- return Error(drain.error);
- if (drain.value != 1 || c == '\n')
- break;
- }
+ if (LIBC_UNLIKELY(bytes_read == cpp::numeric_limits<size_t>::max()) ||
+ !buf.reserve(bytes_read + 1)) {
+ char c = '\0';
+ while (true) {
+ FileIOResult drain = f->read_unlocked(&c, 1);
+ if (drain.has_error())
+ return Error(drain.error);
+ if (drain.value != 1 || c == '\n')
+ break;
}
return Error(ENOMEM);
}
buf.span()[bytes_read++] = ch;
- if (ch == '\n') {
- found_newline = true;
- break;
- }
}
- if (f->error_unlocked())
- return Error(EIO);
-
- bool eof = (bytes_read == 0);
-
- // If the line ended with a newline, strip it.
- if (found_newline)
- --bytes_read;
-
- if (!buf.span().empty())
- buf.span()[bytes_read] = '\0';
- return ReadLineResult{bytes_read, /*truncated=*/false, eof};
+ return ReadLineResult{bytes_read, /*truncated=*/false, !saw_bytes};
}
} // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/__support/pwd/flat_file_db.h b/libc/src/__support/pwd/flat_file_db.h
index 68e9f1751a60cc..3a653db0516b91 100644
--- a/libc/src/__support/pwd/flat_file_db.h
+++ b/libc/src/__support/pwd/flat_file_db.h
@@ -112,7 +112,7 @@ template <typename EntryType> class FlatFileDatabase {
while (true) {
auto original_pos = file->tell();
- auto result = read_line(file, buffer);
+ auto result = read_line(file, buffer.first(buffer.size() - 1));
if (!result.has_value())
return Error(result.error());
@@ -130,8 +130,10 @@ template <typename EntryType> class FlatFileDatabase {
return Error(ERANGE);
}
- // Slicing at bytes_read + 1 includes the terminating null byte written
- // by read_line; the remainder of the buffer serves as scratch space.
+ buffer[res.bytes_read] = '\0';
+
+ // Slicing at bytes_read + 1 includes the terminating null byte; the
+ // remainder of the buffer serves as scratch space.
auto parse_res =
parse_line<EntryType>(buffer.first(res.bytes_read + 1),
buffer.subspan(res.bytes_read + 1), entry);
@@ -170,9 +172,13 @@ template <typename EntryType> class FlatFileDatabase {
if (res.bytes_read == 0)
continue;
+ if (!buffer.reserve(res.bytes_read + 1))
+ return Error(ENOMEM);
+ buffer.span()[res.bytes_read] = '\0';
+
while (true) {
- // Slicing at bytes_read + 1 includes the terminating null byte written
- // by read_line; the remainder of the buffer serves as scratch space.
+ // Slicing at bytes_read + 1 includes the terminating null byte; the
+ // remainder of the buffer serves as scratch space.
auto parse_res = parse_line<EntryType>(
buffer.span().first(res.bytes_read + 1),
buffer.span().subspan(res.bytes_read + 1), entry);
diff --git a/libc/test/src/__support/File/line_reader_test.cpp b/libc/test/src/__support/File/line_reader_test.cpp
index f20f1de8d7c5d0..e90011acbb72ec 100644
--- a/libc/test/src/__support/File/line_reader_test.cpp
+++ b/libc/test/src/__support/File/line_reader_test.cpp
@@ -41,38 +41,56 @@ LIBC_NAMESPACE::File *open_temp(const char *path,
} // namespace
-TEST(LlvmLibcLineReaderTest, InvalidArgumentsAndWriteOnlyStream) {
- char buf[8];
- auto null_span = LIBC_NAMESPACE::read_line(nullptr, buf);
- ASSERT_FALSE(null_span.has_value());
- EXPECT_EQ(null_span.error(), EINVAL);
+TEST(LlvmLibcLineReaderTest, EmptySpanAndWriteOnlyStream) {
+ {
+ const char *path = libc_make_test_file_path("line_reader_empty_span.test");
+ LIBC_NAMESPACE::File *f = open_temp(path, "\na\n");
+ ASSERT_NE(f, nullptr);
+ LIBC_NAMESPACE::cpp::scope_exit cleanup([&]() {
+ f->close();
+ LIBC_NAMESPACE::remove(path);
+ });
- LIBC_NAMESPACE::ScopedDynamicBuffer dyn_buf;
- auto null_dyn = LIBC_NAMESPACE::read_line(nullptr, dyn_buf);
- ASSERT_FALSE(null_dyn.has_value());
- EXPECT_EQ(null_dyn.error(), EINVAL);
+ LIBC_NAMESPACE::cpp::span<char> empty;
+ auto blank = LIBC_NAMESPACE::read_line(f, empty);
+ ASSERT_TRUE(blank.has_value());
+ EXPECT_EQ(blank->bytes_read, size_t{0});
+ EXPECT_FALSE(blank->truncated);
+ EXPECT_FALSE(blank->eof);
- const char *path = libc_make_test_file_path("line_reader_invalid.test");
- LIBC_NAMESPACE::File *f = open_temp(path, "hello\n", "w");
- ASSERT_NE(f, nullptr);
- LIBC_NAMESPACE::cpp::scope_exit cleanup([&]() {
- f->close();
- LIBC_NAMESPACE::remove(path);
- });
+ auto trunc = LIBC_NAMESPACE::read_line(f, empty);
+ ASSERT_TRUE(trunc.has_value());
+ EXPECT_EQ(trunc->bytes_read, size_t{0});
+ EXPECT_TRUE(trunc->truncated);
+ EXPECT_FALSE(trunc->eof);
- char one_byte[1];
- auto small = LIBC_NAMESPACE::read_line(f, one_byte);
- ASSERT_FALSE(small.has_value());
- EXPECT_EQ(small.error(), ERANGE);
+ auto eof = LIBC_NAMESPACE::read_line(f, empty);
+ ASSERT_TRUE(eof.has_value());
+ EXPECT_EQ(eof->bytes_read, size_t{0});
+ EXPECT_FALSE(eof->truncated);
+ EXPECT_TRUE(eof->eof);
+ }
+
+ {
+ const char *path = libc_make_test_file_path("line_reader_wonly.test");
+ LIBC_NAMESPACE::File *f = open_temp(path, "hello\n", "w");
+ ASSERT_NE(f, nullptr);
+ LIBC_NAMESPACE::cpp::scope_exit cleanup([&]() {
+ f->close();
+ LIBC_NAMESPACE::remove(path);
+ });
- auto bad_span = LIBC_NAMESPACE::read_line(f, buf);
- ASSERT_FALSE(bad_span.has_value());
- EXPECT_EQ(bad_span.error(), EBADF);
+ char buf[8];
+ auto bad_span = LIBC_NAMESPACE::read_line(f, buf);
+ ASSERT_FALSE(bad_span.has_value());
+ EXPECT_EQ(bad_span.error(), EBADF);
- auto bad_dyn = LIBC_NAMESPACE::read_line(f, dyn_buf);
- ASSERT_FALSE(bad_dyn.has_value());
- EXPECT_EQ(bad_dyn.error(), EBADF);
- EXPECT_EQ(dyn_buf.capacity(), size_t{0});
+ LIBC_NAMESPACE::ScopedDynamicBuffer dyn_buf;
+ auto bad_dyn = LIBC_NAMESPACE::read_line(f, dyn_buf);
+ ASSERT_FALSE(bad_dyn.has_value());
+ EXPECT_EQ(bad_dyn.error(), EBADF);
+ EXPECT_EQ(dyn_buf.capacity(), size_t{0});
+ }
}
TEST(LlvmLibcLineReaderTest, FixedSpanReadTruncateAndEof) {
@@ -84,41 +102,44 @@ TEST(LlvmLibcLineReaderTest, FixedSpanReadTruncateAndEof) {
LIBC_NAMESPACE::remove(path);
});
- // Size 5 holds 4 chars + NUL: "abcd\n" fits, "\n" is blank, "efghi\n"
- // truncates and drains, "ok" has no trailing newline, then EOF.
- char buf[5];
+ // 4-byte span: "abcd\n" fits, "\n" is blank, "efghi\n" truncates and drains,
+ // "ok" has no trailing newline, then EOF.
+ char buf[4];
auto r1 = LIBC_NAMESPACE::read_line(f, buf);
ASSERT_TRUE(r1.has_value());
EXPECT_EQ(r1->bytes_read, size_t{4});
EXPECT_FALSE(r1->truncated);
EXPECT_FALSE(r1->eof);
- EXPECT_STREQ(buf, "abcd");
+ EXPECT_EQ(LIBC_NAMESPACE::cpp::string_view(buf, r1->bytes_read),
+ LIBC_NAMESPACE::cpp::string_view("abcd"));
auto r2 = LIBC_NAMESPACE::read_line(f, buf);
ASSERT_TRUE(r2.has_value());
EXPECT_EQ(r2->bytes_read, size_t{0});
+ EXPECT_FALSE(r2->truncated);
EXPECT_FALSE(r2->eof);
- EXPECT_STREQ(buf, "");
auto r3 = LIBC_NAMESPACE::read_line(f, buf);
ASSERT_TRUE(r3.has_value());
EXPECT_EQ(r3->bytes_read, size_t{4});
EXPECT_TRUE(r3->truncated);
- EXPECT_STREQ(buf, "efgh");
+ EXPECT_EQ(LIBC_NAMESPACE::cpp::string_view(buf, r3->bytes_read),
+ LIBC_NAMESPACE::cpp::string_view("efgh"));
auto r4 = LIBC_NAMESPACE::read_line(f, buf);
ASSERT_TRUE(r4.has_value());
EXPECT_EQ(r4->bytes_read, size_t{2});
EXPECT_FALSE(r4->truncated);
EXPECT_FALSE(r4->eof);
- EXPECT_STREQ(buf, "ok");
+ EXPECT_EQ(LIBC_NAMESPACE::cpp::string_view(buf, r4->bytes_read),
+ LIBC_NAMESPACE::cpp::string_view("ok"));
auto r5 = LIBC_NAMESPACE::read_line(f, buf);
ASSERT_TRUE(r5.has_value());
EXPECT_EQ(r5->bytes_read, size_t{0});
+ EXPECT_FALSE(r5->truncated);
EXPECT_TRUE(r5->eof);
- EXPECT_STREQ(buf, "");
}
TEST(LlvmLibcLineReaderTest, EmbeddedNullAndCarriageReturnPreserved) {
@@ -136,7 +157,7 @@ TEST(LlvmLibcLineReaderTest, EmbeddedNullAndCarriageReturnPreserved) {
auto r = LIBC_NAMESPACE::read_line(f, buf);
ASSERT_TRUE(r.has_value());
EXPECT_EQ(r->bytes_read, size_t{6});
- EXPECT_MEM_EQ(MemoryView("ab\0cd\r\0", 7), MemoryView(buf, 7));
+ EXPECT_MEM_EQ(MemoryView("ab\0cd\r", 6), MemoryView(buf, r->bytes_read));
}
TEST(LlvmLibcLineReaderTest, DynamicBufferGrowthReuseAndEmptyEof) {
@@ -187,5 +208,7 @@ TEST(LlvmLibcLineReaderTest, DynamicBufferGrowthReuseAndEmptyEof) {
ASSERT_TRUE(r2.has_value());
EXPECT_EQ(r2->bytes_read, size_t{2});
EXPECT_EQ(dyn_buf.capacity(), CAP);
- EXPECT_STREQ(dyn_buf.span().data(), "hi");
+ EXPECT_EQ(
+ LIBC_NAMESPACE::cpp::string_view(dyn_buf.span().data(), r2->bytes_read),
+ LIBC_NAMESPACE::cpp::string_view("hi"));
}
More information about the libc-commits
mailing list