Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: [PATCH] ztrftime(): Fix truncation for %.



On 29 Dec 2018, at 04:27, Daniel Shahaf <d.s@xxxxxxxxxxxxxxxxxx> wrote:
>That's patently untrue.  Thanks dana for catching that.

I was pretty worried for a minute :|

OK, that aside, i think i did address all of your feedback. Hopefully this is
the final chapter in the saga of me adding a ceiling on a number

dana


diff --git a/Src/utils.c b/Src/utils.c
index e43a3cdb4..42a860b1d 100644
--- a/Src/utils.c
+++ b/Src/utils.c
@@ -3334,19 +3334,28 @@ morefmt:
 #endif
 	    switch (*fmt++) {
 	    case '.':
-		if (ztrftimebuf(&bufsize, digs))
-		    return -1;
+	    {
 		if (digs > 9)
 		    digs = 9;
+		if (ztrftimebuf(&bufsize, digs))
+		    return -1;
+		long fnsec = nsec;
 		if (digs < 9) {
 		    int trunc;
-		    for (trunc = 8 - digs; trunc; trunc--)
-			nsec /= 10;
-		    nsec = (nsec + 8) / 10;
+		    long max = 100000000;
+		    for (trunc = 8 - digs; trunc; trunc--) {
+			max /= 10;
+			fnsec /= 10;
+		    }
+		    max -= 1;
+		    fnsec = (fnsec + 5) / 10;
+		    if (fnsec > max)
+			fnsec = max;
 		}
-		sprintf(buf, "%0*ld", digs, nsec);
+		sprintf(buf, "%0*ld", digs, fnsec);
 		buf += digs;
 		break;
+	    }
 	    case '\0':
 		/* Guard against premature end of string */
 		*buf++ = '%';
diff --git a/Test/V09datetime.ztst b/Test/V09datetime.ztst
index 2041d9b40..9f67ecec3 100644
--- a/Test/V09datetime.ztst
+++ b/Test/V09datetime.ztst
@@ -114,3 +114,19 @@
 
   strftime -r '%Y' 2> /dev/null
 1:-r timestring not optional
+
+  # This tests rounding up and the use of repeated %.s
+  strftime '%Y-%m-%d %H:%M:%S.%3..%3.' 1012615322 $(( 999_999 ))
+  # These test the ceiling on rounding up
+  for 1 in %. %1. %3. %6. %9. %12.; do
+    print -rn - "$1 "
+    strftime "%Y-%m-%d %H:%M:%S.$1" 1012615322 $(( 999_999_999 ))
+  done
+0:%. truncation
+>2002-02-02 02:02:02.001.001
+>%. 2002-02-02 02:02:02.999
+>%1. 2002-02-02 02:02:02.9
+>%3. 2002-02-02 02:02:02.999
+>%6. 2002-02-02 02:02:02.999999
+>%9. 2002-02-02 02:02:02.999999999
+>%12. 2002-02-02 02:02:02.999999999



Messages sorted by: Reverse Date, Date, Thread, Author