[libc-commits] [libc] [libc] Support _IONBF buffering for read_unlocked (PR #120677)

Jack Huang via libc-commits libc-commits at lists.llvm.org
Thu Dec 19 19:33:27 PST 2024


https://github.com/jackhong12 created https://github.com/llvm/llvm-project/pull/120677

Support _IONBF buffering for read_unlocked. Add the functions read_unlocked_nbf() and read_unlocked_fbf().

Fixes: #120155

>From 2bea94078fe0ad94969634cdadbb3c7444c09af9 Mon Sep 17 00:00:00 2001
From: jack <jackhuang1205 at gmail.com>
Date: Fri, 20 Dec 2024 11:25:52 +0800
Subject: [PATCH] [libc] Support _IONBF buffering for read_unlocked

- Add the functions read_unlocked_nbf and read_unlocked_fbf.
---
 libc/src/__support/File/file.cpp | 23 +++++++++++++++++++++++
 libc/src/__support/File/file.h   |  3 +++
 2 files changed, 26 insertions(+)

diff --git a/libc/src/__support/File/file.cpp b/libc/src/__support/File/file.cpp
index 972249fef96bcf..cb8e1dff9fe96e 100644
--- a/libc/src/__support/File/file.cpp
+++ b/libc/src/__support/File/file.cpp
@@ -190,6 +190,17 @@ FileIOResult File::read_unlocked(void *data, size_t len) {
 
   prev_op = FileOp::READ;
 
+  if (bufmode == _IONBF) { // unbuffered.
+    return read_unlocked_nbf(static_cast<uint8_t *>(data), len);
+  } else if (bufmode == _IOFBF) { // fully buffered
+    return read_unlocked_fbf(static_cast<uint8_t *>(data), len);
+  } else /*if (bufmode == _IOLBF) */ { // line buffered
+    // There is no line buffered mode for read. Use fully buffer instead.
+    return read_unlocked_fbf(static_cast<uint8_t *>(data), len);
+  }
+}
+
+FileIOResult File::read_unlocked_fbf(uint8_t *data, size_t len) {
   cpp::span<uint8_t> bufref(static_cast<uint8_t *>(buf), bufsize);
   cpp::span<uint8_t> dataref(static_cast<uint8_t *>(data), len);
 
@@ -245,6 +256,18 @@ FileIOResult File::read_unlocked(void *data, size_t len) {
   return {transfer_size + available_data, result.error};
 }
 
+FileIOResult File::read_unlocked_nbf(uint8_t *data, size_t len) {
+  auto result = platform_read(this, data, len);
+
+  if (result.has_error() || result < len) {
+    if (!result.has_error())
+      eof = true;
+    else
+      err = true;
+  }
+  return result;
+}
+
 int File::ungetc_unlocked(int c) {
   // There is no meaning to unget if:
   // 1. You are trying to push back EOF.
diff --git a/libc/src/__support/File/file.h b/libc/src/__support/File/file.h
index 42e1d11b4ab1a0..548f051a1b9f5c 100644
--- a/libc/src/__support/File/file.h
+++ b/libc/src/__support/File/file.h
@@ -280,6 +280,9 @@ class File {
   FileIOResult write_unlocked_fbf(const uint8_t *data, size_t len);
   FileIOResult write_unlocked_nbf(const uint8_t *data, size_t len);
 
+  FileIOResult read_unlocked_fbf(uint8_t *data, size_t len);
+  FileIOResult read_unlocked_nbf(uint8_t *data, size_t len);
+
   constexpr void adjust_buf() {
     if (read_allowed() && (buf == nullptr || bufsize == 0)) {
       // We should allow atleast one ungetc operation.



More information about the libc-commits mailing list