[libc-commits] [libc] [libc][stdio] Implement getline POSIX function. (PR #242975)

via libc-commits libc-commits at lists.llvm.org
Sun Nov 15 22:38:41 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libc

Author: Alexey Samsonov (vonosmas)

<details>
<summary>Changes</summary>

Partially based on PR #<!-- -->219601, but with many changes to implementation, and added tests.

This is an implementation of POSIX [getline](https://pubs.opengroup.org/onlinepubs/9799919799/functions/getline.html) function. It's mostly a straightforward per-byte reading, but with manual malloc/free buffer management required for that function. Some notes:

* implementation is generic to be trivially reusable for `getdelim`
* ad-hoc dynamic buffer management, similar to what we do in other functions like `scandir` (there's no unified vector, deliberately)
* we carefully implement POSIX spec where even invalid input arguments to `getline` set the error bit on the input stream.
* unit tests cover various cases (including buffer overflows) by using fakes and templates to prevent buffers from growing large as they would in the normal production version.

Assisted by: Gemini, human-reviewed

Co-authored by: @<!-- -->afnrow 

---

Patch is 43.23 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/242975.diff


13 Files Affected:

- (modified) libc/config/linux/aarch64/entrypoints.txt (+1) 
- (modified) libc/config/linux/riscv/entrypoints.txt (+1) 
- (modified) libc/config/linux/x86_64/entrypoints.txt (+1) 
- (modified) libc/include/stdio.yaml (+9) 
- (modified) libc/src/__support/File/file.h (+2) 
- (modified) libc/src/stdio/CMakeLists.txt (+1) 
- (modified) libc/src/stdio/generic/CMakeLists.txt (+41) 
- (added) libc/src/stdio/generic/getdelim_impl.h (+186) 
- (added) libc/src/stdio/generic/getline.cpp (+41) 
- (added) libc/src/stdio/getline.h (+29) 
- (modified) libc/test/src/stdio/CMakeLists.txt (+59) 
- (added) libc/test/src/stdio/getdelim_impl_test.cpp (+363) 
- (added) libc/test/src/stdio/getline_test.cpp (+434) 


``````````diff
diff --git a/libc/config/linux/aarch64/entrypoints.txt b/libc/config/linux/aarch64/entrypoints.txt
index 4f96b13ba478ee..8fabaf03f32717 100644
--- a/libc/config/linux/aarch64/entrypoints.txt
+++ b/libc/config/linux/aarch64/entrypoints.txt
@@ -1389,6 +1389,7 @@ if(LLVM_LIBC_FULL_BUILD)
     libc.src.stdio.getc_unlocked
     libc.src.stdio.getchar
     libc.src.stdio.getchar_unlocked
+    libc.src.stdio.getline
     libc.src.stdio.pclose
     libc.src.stdio.perror
     libc.src.stdio.popen
diff --git a/libc/config/linux/riscv/entrypoints.txt b/libc/config/linux/riscv/entrypoints.txt
index 8d3f601139800a..13df830035bc92 100644
--- a/libc/config/linux/riscv/entrypoints.txt
+++ b/libc/config/linux/riscv/entrypoints.txt
@@ -1602,6 +1602,7 @@ if(LLVM_LIBC_FULL_BUILD)
     libc.src.stdio.getc_unlocked
     libc.src.stdio.getchar
     libc.src.stdio.getchar_unlocked
+    libc.src.stdio.getline
     libc.src.stdio.pclose
     libc.src.stdio.perror
     libc.src.stdio.popen
diff --git a/libc/config/linux/x86_64/entrypoints.txt b/libc/config/linux/x86_64/entrypoints.txt
index 56c3968cc083c7..f20c759d80432a 100644
--- a/libc/config/linux/x86_64/entrypoints.txt
+++ b/libc/config/linux/x86_64/entrypoints.txt
@@ -1606,6 +1606,7 @@ if(LLVM_LIBC_FULL_BUILD)
     libc.src.stdio.getc_unlocked
     libc.src.stdio.getchar
     libc.src.stdio.getchar_unlocked
+    libc.src.stdio.getline
     libc.src.stdio.pclose
     libc.src.stdio.perror
     libc.src.stdio.popen
diff --git a/libc/include/stdio.yaml b/libc/include/stdio.yaml
index 251840d8670a63..4a54f4673c639d 100644
--- a/libc/include/stdio.yaml
+++ b/libc/include/stdio.yaml
@@ -37,6 +37,7 @@ macros:
 types:
   - type_name: rsize_t
   - type_name: size_t
+  - type_name: ssize_t
   - type_name: off_t
   - type_name: cookie_io_functions_t
   - type_name: FILE
@@ -329,6 +330,14 @@ functions:
       - posix
     return_type: int
     arguments: []
+  - name: getline
+    standards:
+      - posix
+    return_type: ssize_t
+    arguments:
+      - type: char **__restrict
+      - type: size_t *__restrict
+      - type: FILE *__restrict
   - name: pclose
     standards:
       - posix
diff --git a/libc/src/__support/File/file.h b/libc/src/__support/File/file.h
index 40f04a1631c5f4..bdb9d105d10614 100644
--- a/libc/src/__support/File/file.h
+++ b/libc/src/__support/File/file.h
@@ -279,6 +279,8 @@ class File {
 
   LIBC_INLINE bool error_unlocked() const { return err; }
 
+  LIBC_INLINE void set_error_unlocked() { err = true; }
+
   LIBC_INLINE bool error() {
     FileLock l(this);
     return error_unlocked();
diff --git a/libc/src/stdio/CMakeLists.txt b/libc/src/stdio/CMakeLists.txt
index 1b166dd366b33a..cba596c67345dd 100644
--- a/libc/src/stdio/CMakeLists.txt
+++ b/libc/src/stdio/CMakeLists.txt
@@ -386,6 +386,7 @@ add_stdio_entrypoint_object(getc)
 add_stdio_entrypoint_object(getc_unlocked)
 add_stdio_entrypoint_object(getchar)
 add_stdio_entrypoint_object(getchar_unlocked)
+add_stdio_entrypoint_object(getline)
 add_stdio_entrypoint_object(fgets)
 add_stdio_entrypoint_object(ungetc)
 add_stdio_entrypoint_object(scanf)
diff --git a/libc/src/stdio/generic/CMakeLists.txt b/libc/src/stdio/generic/CMakeLists.txt
index e05a9e1bd9be78..33f7524c93a9b1 100644
--- a/libc/src/stdio/generic/CMakeLists.txt
+++ b/libc/src/stdio/generic/CMakeLists.txt
@@ -608,6 +608,47 @@ add_generic_entrypoint_object(
     libc.src.__support.File.platform_file
 )
 
+if(TARGET libc.src.__support.File.file)
+  add_header_library(
+    getdelim_impl
+    HDRS
+      getdelim_impl.h
+    DEPENDS
+      libc.hdr.errno_macros
+      libc.hdr.types.size_t
+      libc.hdr.types.ssize_t
+      libc.src.__support.CPP.limits
+      libc.src.__support.CPP.new
+      libc.src.__support.CPP.unique_ptr
+      libc.src.__support.File.file
+      libc.src.__support.checked_ptr
+      libc.src.__support.error_or
+      libc.src.__support.macros.attributes
+      libc.src.__support.macros.config
+      libc.src.__support.macros.optimization
+      libc.src.string.memory_utils.inline_memcpy
+  )
+endif()
+
+add_generic_entrypoint_object(
+  getline
+  SRCS
+    getline.cpp
+  HDRS
+    ../getline.h
+  DEPENDS
+    .getdelim_impl
+    libc.hdr.types.FILE
+    libc.hdr.types.size_t
+    libc.hdr.types.ssize_t
+    libc.src.__support.File.file
+    libc.src.__support.File.platform_file
+    libc.src.__support.common
+    libc.src.__support.libc_errno
+    libc.src.__support.macros.config
+    libc.src.__support.macros.null_check
+)
+
 add_generic_entrypoint_object(
   ungetc
   SRCS
diff --git a/libc/src/stdio/generic/getdelim_impl.h b/libc/src/stdio/generic/getdelim_impl.h
new file mode 100644
index 00000000000000..387ca98611887f
--- /dev/null
+++ b/libc/src/stdio/generic/getdelim_impl.h
@@ -0,0 +1,186 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Implementation of getdelim logic shared by getline and getdelim.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_STDIO_GENERIC_GETDELIM_IMPL_H
+#define LLVM_LIBC_SRC_STDIO_GENERIC_GETDELIM_IMPL_H
+
+#include "hdr/errno_macros.h"
+#include "hdr/types/size_t.h"
+#include "hdr/types/ssize_t.h"
+#include "src/__support/CPP/limits.h"
+#include "src/__support/CPP/new.h"
+#include "src/__support/CPP/unique_ptr.h"
+#include "src/__support/File/file.h"
+#include "src/__support/checked_ptr.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"
+#include "src/string/memory_utils/inline_memcpy.h"
+
+namespace LIBC_NAMESPACE_DECL {
+namespace internal {
+
+LIBC_INLINE constexpr size_t default_max_capacity() {
+  if constexpr (cpp::numeric_limits<ssize_t>::digits <
+                cpp::numeric_limits<size_t>::digits) {
+    return static_cast<size_t>(cpp::numeric_limits<ssize_t>::max()) + 1;
+  } else {
+    return cpp::numeric_limits<size_t>::max();
+  }
+}
+
+// Manages the caller-owned (*lineptr, *n) buffer via RAII so that any newly
+// allocated or grown buffer and its capacity are always written back to the
+// caller's pointers on scope exit, keeping *lineptr valid for free() even if
+// reading or subsequent growth fails.
+// TODO: Replace with a dynamic array container once available.
+template <size_t MaxCapacity> class LineBuffer {
+  static_assert(MaxCapacity >= 2, "MaxCapacity must be at least 2");
+
+  static constexpr size_t INITIAL_CAPACITY = 64;
+
+  char *&out_ptr;
+  size_t &out_cap;
+  cpp::unique_ptr<char[]> buffer;
+  size_t length = 0;
+  size_t capacity = 0;
+
+  LIBC_INLINE bool ensure_capacity() {
+    // Ensure `length + 2` (for the incoming char and trailing null terminator)
+    // cannot overflow `size_t` or exceed `MaxCapacity` (which is >= 2).
+    if (LIBC_UNLIKELY(length > MaxCapacity - 2))
+      return false;
+
+    if (LIBC_LIKELY(capacity >= length + 2))
+      return true;
+
+    size_t new_capacity = next_capacity(capacity);
+
+    CheckedPtr<char[]> bigger_buffer =
+        make_unique_for_overwrite<char[]>(new_capacity);
+    if (LIBC_UNLIKELY(!bigger_buffer))
+      return false;
+
+    if (length > 0)
+      inline_memcpy(bigger_buffer.get(), buffer.get(), length);
+
+    capacity = new_capacity;
+    buffer = bigger_buffer.take_unique();
+    return true;
+  }
+
+public:
+  LIBC_INLINE static constexpr size_t next_capacity(size_t current_capacity) {
+    if constexpr (MaxCapacity <= INITIAL_CAPACITY) {
+      return MaxCapacity;
+    } else {
+      if (current_capacity < INITIAL_CAPACITY / 2)
+        return INITIAL_CAPACITY;
+      if (current_capacity > MaxCapacity / 2)
+        return MaxCapacity;
+      return current_capacity * 2;
+    }
+  }
+
+  LIBC_INLINE LineBuffer(char *&ptr, size_t &cap)
+      : out_ptr(ptr), out_cap(cap), buffer(ptr),
+        capacity(ptr != nullptr ? cap : 0) {
+    out_ptr = nullptr;
+  }
+
+  LineBuffer(const LineBuffer &) = delete;
+  LineBuffer &operator=(const LineBuffer &) = delete;
+  LineBuffer(LineBuffer &&) = delete;
+  LineBuffer &operator=(LineBuffer &&) = delete;
+
+  LIBC_INLINE ~LineBuffer() {
+    if (buffer) {
+      out_cap = capacity;
+      out_ptr = buffer.release();
+    }
+  }
+
+  LIBC_INLINE constexpr size_t size() const { return length; }
+
+  [[nodiscard]] LIBC_INLINE bool push_back(char c) {
+    if (LIBC_UNLIKELY(!ensure_capacity()))
+      return false;
+
+    buffer[length++] = c;
+    return true;
+  }
+
+  LIBC_INLINE void null_terminate() { buffer[length] = '\0'; }
+};
+
+template <size_t MaxCapacity = default_max_capacity()>
+LIBC_INLINE ErrorOr<ssize_t> getdelim_impl(char **__restrict lineptr,
+                                           size_t *__restrict n, int delim,
+                                           File *__restrict stream) {
+  static_assert(MaxCapacity >= 2 && MaxCapacity <= default_max_capacity(),
+                "MaxCapacity must be within [2, default_max_capacity()]");
+  File::FileLock lock(stream);
+
+  if (lineptr == nullptr || n == nullptr) {
+    stream->set_error_unlocked();
+    return Error(EINVAL);
+  }
+
+  if (stream->try_set_orientation_unlocked(File::Orientation::BYTE) !=
+      File::Orientation::BYTE) {
+    stream->set_error_unlocked();
+    return Error(EINVAL);
+  }
+
+  if (stream->iseof_unlocked())
+    return -1;
+
+  LineBuffer<MaxCapacity> line_buf(*lineptr, *n);
+  const unsigned char target = static_cast<unsigned char>(delim);
+
+  while (true) {
+    unsigned char c = 0;
+    auto result = stream->read_unlocked(&c, 1);
+    if (LIBC_UNLIKELY(result.has_error())) {
+      stream->set_error_unlocked();
+      return Error(result.error);
+    }
+    if (result.value != 1)
+      break;
+
+    if (LIBC_UNLIKELY(line_buf.size() == MaxCapacity - 1)) {
+      stream->set_error_unlocked();
+      return Error(EOVERFLOW);
+    }
+
+    if (LIBC_UNLIKELY(!line_buf.push_back(static_cast<char>(c)))) {
+      stream->set_error_unlocked();
+      return Error(ENOMEM);
+    }
+
+    if (c == target)
+      break;
+  }
+
+  if (line_buf.size() == 0)
+    return -1;
+
+  line_buf.null_terminate();
+  return static_cast<ssize_t>(line_buf.size());
+}
+
+} // namespace internal
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC_STDIO_GENERIC_GETDELIM_IMPL_H
diff --git a/libc/src/stdio/generic/getline.cpp b/libc/src/stdio/generic/getline.cpp
new file mode 100644
index 00000000000000..23126b6202bbf8
--- /dev/null
+++ b/libc/src/stdio/generic/getline.cpp
@@ -0,0 +1,41 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Implementation of getline.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/stdio/getline.h"
+
+#include "hdr/types/FILE.h"
+#include "hdr/types/size_t.h"
+#include "hdr/types/ssize_t.h"
+#include "src/__support/File/file.h"
+#include "src/__support/common.h"
+#include "src/__support/libc_errno.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/null_check.h"
+#include "src/stdio/generic/getdelim_impl.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+LLVM_LIBC_FUNCTION(ssize_t, getline,
+                   (char **__restrict lineptr, size_t *__restrict n,
+                    ::FILE *__restrict stream)) {
+  LIBC_CRASH_ON_NULLPTR(stream);
+  auto result = internal::getdelim_impl(lineptr, n, '\n',
+                                        reinterpret_cast<File *>(stream));
+  if (!result.has_value()) {
+    libc_errno = result.error();
+    return -1;
+  }
+  return result.value();
+}
+
+} // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/stdio/getline.h b/libc/src/stdio/getline.h
new file mode 100644
index 00000000000000..9286ed7ebb1408
--- /dev/null
+++ b/libc/src/stdio/getline.h
@@ -0,0 +1,29 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Implementation header of getline.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_STDIO_GETLINE_H
+#define LLVM_LIBC_SRC_STDIO_GETLINE_H
+
+#include "hdr/types/FILE.h"
+#include "hdr/types/size_t.h"
+#include "hdr/types/ssize_t.h"
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+ssize_t getline(char **__restrict lineptr, size_t *__restrict n,
+                ::FILE *__restrict stream);
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC_STDIO_GETLINE_H
diff --git a/libc/test/src/stdio/CMakeLists.txt b/libc/test/src/stdio/CMakeLists.txt
index 18997d34506477..e813627f37b8b2 100644
--- a/libc/test/src/stdio/CMakeLists.txt
+++ b/libc/test/src/stdio/CMakeLists.txt
@@ -688,6 +688,65 @@ add_libc_test(
     libc.test.UnitTest.ErrnoSetterMatcher
 )
 
+add_libc_test(
+  getdelim_impl_test
+  SUITE
+    libc-stdio-tests
+  SRCS
+    getdelim_impl_test.cpp
+  DEPENDS
+    libc.hdr.errno_macros
+    libc.hdr.func.free
+    libc.hdr.func.malloc
+    libc.hdr.stdint_proxy
+    libc.hdr.stdio_macros
+    libc.hdr.types.size_t
+    libc.hdr.types.ssize_t
+    libc.src.__support.CPP.limits
+    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.file_io_result
+    libc.src.__support.error_or
+    libc.src.stdio.generic.getdelim_impl
+    libc.src.string.memory_utils.inline_memcpy
+)
+
+add_libc_test(
+  getline_test
+  SUITE
+    libc-stdio-tests
+  SRCS
+    getline_test.cpp
+  DEPENDS
+    libc.hdr.errno_macros
+    libc.hdr.func.free
+    libc.hdr.func.malloc
+    libc.hdr.stdio_macros
+    libc.hdr.types.FILE
+    libc.hdr.types.size_t
+    libc.hdr.types.ssize_t
+    libc.src.__support.CPP.scope
+    libc.src.__support.CPP.string_view
+    libc.src.__support.libc_errno
+    libc.src.stdio.clearerr
+    libc.src.stdio.fclose
+    libc.src.stdio.feof
+    libc.src.stdio.ferror
+    libc.src.stdio.fmemopen
+    libc.src.stdio.fopen
+    libc.src.stdio.fseek
+    libc.src.stdio.fwrite
+    libc.src.stdio.getline
+    libc.src.stdio.remove
+    libc.src.stdio.setvbuf
+    libc.src.stdio.ungetc
+    libc.src.wchar.fwide
+    libc.test.UnitTest.ErrnoCheckingTest
+    libc.test.UnitTest.ErrnoSetterMatcher
+)
+
 add_libc_test(
   ftell_test
   SUITE
diff --git a/libc/test/src/stdio/getdelim_impl_test.cpp b/libc/test/src/stdio/getdelim_impl_test.cpp
new file mode 100644
index 00000000000000..887dca478439df
--- /dev/null
+++ b/libc/test/src/stdio/getdelim_impl_test.cpp
@@ -0,0 +1,363 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 the getdelim_impl helper.
+///
+//===----------------------------------------------------------------------===//
+
+#include "hdr/errno_macros.h"
+#include "hdr/func/free.h"
+#include "hdr/func/malloc.h"
+#include "hdr/stdint_proxy.h"
+#include "hdr/stdio_macros.h"
+#include "hdr/types/size_t.h"
+#include "hdr/types/ssize_t.h"
+#include "src/__support/CPP/limits.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/file_io_result.h"
+#include "src/__support/File/file_mode.h"
+#include "src/__support/error_or.h"
+#include "src/stdio/generic/getdelim_impl.h"
+#include "src/string/memory_utils/inline_memcpy.h"
+#include "test/UnitTest/Test.h"
+
+namespace {
+
+using LIBC_NAMESPACE::File;
+using LIBC_NAMESPACE::FileIOResult;
+using LIBC_NAMESPACE::FileMode;
+using LIBC_NAMESPACE::cpp::scope_exit;
+using LIBC_NAMESPACE::cpp::span;
+using LIBC_NAMESPACE::cpp::string_view;
+
+class TestFile : public File {
+  span<const char> data;
+  size_t pos = 0;
+  size_t fail_at_byte = LIBC_NAMESPACE::cpp::numeric_limits<size_t>::max();
+  int fail_errno = 0;
+  uint8_t stream_buf[32]{};
+
+  static FileIOResult read_func(File *f, void *dst, size_t len) {
+    auto *tf = static_cast<TestFile *>(f);
+    if (tf->fail_at_byte <= tf->pos)
+      return {0, tf->fail_errno};
+
+    if (tf->pos >= tf->data.size())
+      return 0;
+
+    size_t remaining = tf->data.size() - tf->pos;
+    size_t count = len < remaining ? len : remaining;
+    if (tf->fail_at_byte < tf->pos + count)
+      count = tf->fail_at_byte - tf->pos;
+
+    LIBC_NAMESPACE::inline_memcpy(dst, tf->data.data() + tf->pos, count);
+    tf->pos += count;
+    return count;
+  }
+
+  static int close_func(File *) { return 0; }
+
+public:
+  explicit TestFile(span<const char> bytes, int bufmode = _IOFBF)
+      : File(/*wf=*/nullptr, &read_func, /*sf=*/nullptr, &close_func,
+             bufmode == _IONBF ? nullptr : stream_buf,
+             bufmode == _IONBF ? 0 : sizeof(stream_buf), bufmode,
+             /*owned=*/false, FileMode("r")),
+        data(bytes) {}
+
+  explicit TestFile(string_view str, int bufmode = _IOFBF)
+      : TestFile(span<const char>(str.data(), str.size()), bufmode) {}
+
+  ~TestFile() { (void)close(); }
+
+  void set_fail_at(size_t byte_offset, int err_val) {
+    fail_at_byte = byte_offset;
+    fail_errno = err_val;
+  }
+
+  void set_data(string_view str) {
+    data = span<const char>(str.data(), str.size());
+  }
+
+  size_t raw_pos() const { return pos; }
+};
+
+} // namespace
+
+TEST(LlvmLibcGetdelimImplTest, CustomColonDelimiter) {
+  TestFile file(string_view("root:x:0:0\n"));
+  char *line = nullptr;
+  size_t cap = 0;
+  scope_exit cleanup([&] { ::free(line); });
+
+  auto res = LIBC_NAMESPACE::internal::getdelim_impl(&line, &cap, ':', &file);
+  ASSERT_TRUE(res.has_value());
+  EXPECT_EQ(res.value(), ssize_t(5));
+  EXPECT_STREQ(line, "root:");
+  EXPECT_GE(cap, size_t(6));
+
+  res = LIBC_NAMESPACE::internal::getdelim_impl(&line, &cap, ':', &file);
+  ASSERT_TRUE(res.has_value());
+  EXPECT_EQ(res.value(), ssize_t(2));
+  EXPECT_STREQ(line, "x:");
+
+  res = LIBC_NAMESPACE::internal::getdelim_impl(&line, &cap, ':', &file);
+  ASSERT_TRUE(res.has_value());
+  EXPECT_EQ(res.value(), ssize_t(2));
+  EXPECT_STREQ(line, "0:");
+
+  res = LIBC_NAMESPACE::internal::getdelim_impl(&line, &cap, ':', &file);
+  ASSERT_TRUE(res.has_value());
+  EXPECT_EQ(res.value(), ssize_t(2));
+  EXPECT_STREQ(line, "0\n");
+  EXPECT_TRUE(file.iseof());
+  EXPECT_FALSE(file.error());
+
+  res = LIBC_NAMESPACE::internal::getdelim_impl(&line, &cap, ':', &file);
+  ASSERT_TRUE(res.has_value());
+  EXPECT_EQ(res.value(), ssize_t(-1));
+}
+
+TEST(LlvmLibcGetdelimImplTest, NullByteDelimiter) {
+  constexpr char RAW[] = "first\0second\0third";
+  TestFile file(span<const char>(RAW, sizeof(RAW) - 1));
+  char *line = nullptr;
+  size_t cap = 0;
+  scope_exit cleanup([&] { ::free(line); });
+
+  auto res = LIBC_NAMESPACE::internal::getdelim_impl(&line, &cap, '\0', &file);
+  ASSERT_TRUE(res.has_value());
+  ASSERT_EQ(res.value(), ssize_t(6));
+  EXPECT_EQ(string_view(line, 6), string_view("first\0", 6));
+  EXPECT_EQ(line[6], '\0');
+
+  res = LIBC_NAMESPACE::internal::getdelim_impl(&line, &cap, '\0', &file);
+  ASSERT_TRUE(res.has_value());
+  ASSERT_EQ(res.value(), ssize_t(7));
+  EXPECT_EQ(string_view(line, 7), string_view("second\0", 7));
+  EXPECT_EQ(line[7], '\0');
+
+  res = LIBC_NAMESPACE::internal::getdelim_impl(&line, &c...
[truncated]

``````````

</details>


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


More information about the libc-commits mailing list