emacs-diffs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

master 51f5c4b773: Fix off-by-one error in string-truncate-left


From: Lars Ingebrigtsen
Subject: master 51f5c4b773: Fix off-by-one error in string-truncate-left
Date: Sat, 23 Jul 2022 02:59:00 -0400 (EDT)

branch: master
commit 51f5c4b773e11dd50f9fc6887362324b6d4dc755
Author: Lars Ingebrigtsen <larsi@gnus.org>
Commit: Lars Ingebrigtsen <larsi@gnus.org>

    Fix off-by-one error in string-truncate-left
    
    * lisp/emacs-lisp/subr-x.el (string-truncate-left): Fix off-by-one
    error (bug#56685).
---
 lisp/emacs-lisp/subr-x.el            | 8 ++++++--
 test/lisp/emacs-lisp/subr-x-tests.el | 5 +++++
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/lisp/emacs-lisp/subr-x.el b/lisp/emacs-lisp/subr-x.el
index 5037ae47e8..d5d7bfeb6f 100644
--- a/lisp/emacs-lisp/subr-x.el
+++ b/lisp/emacs-lisp/subr-x.el
@@ -107,12 +107,16 @@ characters; nil stands for the empty string."
 
 ;;;###autoload
 (defun string-truncate-left (string length)
-  "Truncate STRING to LENGTH, replacing initial surplus with \"...\"."
+  "If STRING is longer than LENGTH, return a truncated version.
+When truncating, \"...\" is always prepended to the string, so
+the resulting string may be longer than the original if LENGTH is
+3 or smaller."
   (let ((strlen (length string)))
     (if (<= strlen length)
        string
       (setq length (max 0 (- length 3)))
-      (concat "..." (substring string (max 0 (- strlen 1 length)))))))
+      (concat "..." (substring string (min (1- strlen)
+                                           (max 0 (- strlen length))))))))
 
 (defsubst string-blank-p (string)
   "Check whether STRING is either empty or only whitespace.
diff --git a/test/lisp/emacs-lisp/subr-x-tests.el 
b/test/lisp/emacs-lisp/subr-x-tests.el
index 99c0e82215..7a3efe9db6 100644
--- a/test/lisp/emacs-lisp/subr-x-tests.el
+++ b/test/lisp/emacs-lisp/subr-x-tests.el
@@ -766,5 +766,10 @@
     (should (equal (sort (hash-table-keys h) #'string<) '(a b c)))
     (should (equal (sort (hash-table-values h) #'<) '(1 2 3)))))
 
+(ert-deftest test-string-truncate-left ()
+  (should (equal (string-truncate-left "band" 3) "...d"))
+  (should (equal (string-truncate-left "band" 2) "...d"))
+  (should (equal (string-truncate-left "longstring" 8) "...tring")))
+
 (provide 'subr-x-tests)
 ;;; subr-x-tests.el ends here



reply via email to

[Prev in Thread] Current Thread [Next in Thread]