]> git.eshelyaron.com Git - emacs.git/commitdiff
Don’t read before BEG in insert-file-contents
authorPaul Eggert <eggert@cs.ucla.edu>
Thu, 24 Jul 2025 00:44:38 +0000 (17:44 -0700)
committerEshel Yaron <me@eshelyaron.com>
Fri, 25 Jul 2025 08:12:48 +0000 (10:12 +0200)
* src/fileio.c (Finsert_file_contents): Don’t sample bytes before BEG.
Give up optimizing if the file size shrinks to less than BEG.

(cherry picked from commit e026b57f077e4a6dcce9c24e31dbf7107b88d409)

src/fileio.c

index c042089ac8575cd27d1d0074147a5eb5982b65e5..2dad90ac600a80f1bec443a6874f6ddfbf56005b 100644 (file)
@@ -4347,9 +4347,11 @@ by calling `format-decode', which see.  */)
                    curpos = beg_offset + nread;
                  else
                    {
-                     off_t curmax = end_offset - 3 * 1024;
-                     if (curmax < curpos)
-                       curpos = xlseek (fd, curmax, SEEK_SET, orig_filename);
+                     off_t tailbeg = (curpos <= beg_offset + nread
+                                      ? beg_offset + nread
+                                      : min (curpos, end_offset - 3 * 1024));
+                     if (tailbeg != curpos)
+                       curpos = xlseek (fd, tailbeg, SEEK_SET, orig_filename);
                    }
 
                  /* When appending the last 3 KiB, read extra bytes
@@ -4544,7 +4546,13 @@ by calling `format-decode', which see.  */)
                     be smaller than its head.  */
                  off_t offset_from_beg = endpos - beg_offset;
                  if (offset_from_beg < same_at_start - BEGV_BYTE)
-                   same_at_start = max (0, offset_from_beg) + BEGV_BYTE;
+                   {
+                     /* Give up if the file shrank to less than BEG.  */
+                     giveup_match_end = offset_from_beg < 0;
+
+                     if (!giveup_match_end)
+                       same_at_start = offset_from_beg + BEGV_BYTE;
+                   }
                }
            }
        }