[libc-commits] [libc] [libc][NFC] Extract File line reader to __support (PR #244261)

Pavel Labath via libc-commits libc-commits at lists.llvm.org
Thu Nov 19 08:48:29 PST 2026


================
@@ -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;
----------------
labath wrote:

Is this different from f->geteof_unlocked()?

https://github.com/llvm/llvm-project/pull/244261


More information about the libc-commits mailing list