From 15fa34d3d67d951ee357eee713ff2b9737cd8a54 Mon Sep 17 00:00:00 2001
From: Koichi Murase <myoga.murase@gmail.com>
Date: Tue, 4 May 2021 14:04:55 +0900
Subject: [PATCH] mapfile: buffered read in more cases

---
 builtins/mapfile.def | 16 +++++++---------
 1 file changed, 7 insertions(+), 9 deletions(-)

diff --git a/builtins/mapfile.def b/builtins/mapfile.def
index 65c3cb4f..011dd4a6 100644
--- a/builtins/mapfile.def
+++ b/builtins/mapfile.def
@@ -180,19 +180,17 @@ mapfile (fd, line_count_goal, origin, nskip, callback_quantum, callback, array_n
     }
   else if (invisible_p (entry))
     VUNSETATTR (entry, att_invisible);	/* no longer invisible */
-      
+
   if (flags & MAPF_CLEARARRAY)
     array_flush (array_cell (entry));
 
+  unbuffered_read = callback || line_count_goal;
+
 #ifndef __CYGWIN__
-  unbuffered_read = (lseek (fd, 0L, SEEK_CUR) < 0) && (errno == ESPIPE);
-#else
-  unbuffered_read = 1;
+  if (lseek (fd, 0L, SEEK_CUR) >= 0)
+    unbuffered_read = 0;
 #endif
 
-  if (delim != '\n')
-    unbuffered_read = 1;
-
   zreset ();
 
   /* Skip any lines at beginning of file? */
@@ -215,11 +213,11 @@ mapfile (fd, line_count_goal, origin, nskip, callback_quantum, callback, array_n
       /* Has a callback been registered and if so is it time to call it? */
       if (callback && line_count && (line_count % callback_quantum) == 0) 
 	{
-	  run_callback (callback, array_index, line);
-
 	  /* Reset the buffer for bash own stream. */
 	  if (unbuffered_read == 0)
 	    zsyncfd (fd);
+
+	  run_callback (callback, array_index, line);
 	}
 
       /* XXX - bad things can happen if the callback modifies ENTRY, e.g.,
-- 
2.21.3

