From 28c0b58c2e10d5e9990d4f889a18d21b533c02a4 Mon Sep 17 00:00:00 2001
From: Yorhel <git@yorhel.nl>
Date: Thu, 22 Nov 2012 13:47:10 +0100
Subject: [PATCH] Clip directory sizes to make sure they are positive

I realized that I used addparentstats() with negative values when
removing stuff, so it had to be done this way (without rewriting
everything). It's a simple solution, anyway.
---
 src/util.c | 4 ++--
 src/util.h | 9 ++++++---
 2 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/src/util.c b/src/util.c
index ce000e6..5da9db5 100644
--- a/src/util.c
+++ b/src/util.c
@@ -186,8 +186,8 @@ static void freedir_hlnk(struct dir *d) {
           if(pt==par)
             i=0;
     if(i) {
-      par->size -= d->size;
-      par->asize -= d->asize;
+      par->size = adds64(par->size, -d->size);
+      par->asize = adds64(par->size, -d->asize);
     }
   }
 
diff --git a/src/util.h b/src/util.h
index 5c63876..933bf97 100644
--- a/src/util.h
+++ b/src/util.h
@@ -81,11 +81,14 @@ char *getpath(struct dir *);
 /* returns the root element of the given dir struct */
 struct dir *getroot(struct dir *);
 
-/* Add two positive signed 64-bit integers. Returns INT64_MAX if the result
- * would overflow.
+/* Add two signed 64-bit integers. Returns INT64_MAX if the result would
+ * overflow, or 0 if it would be negative. At least one of the integers must be
+ * positive.
  * I use uint64_t's to detect the overflow, as (a + b < 0) relies on undefined
  * behaviour, and (INT64_MAX - b >= a) didn't work for some reason. */
-#define adds64(a, b) ((uint64_t)(a) + (uint64_t)(b) > (uint64_t)INT64_MAX ? INT64_MAX : (a)+(b))
+#define adds64(a, b) ((a) > 0 && (b) > 0\
+    ? ((uint64_t)(a) + (uint64_t)(b) > (uint64_t)INT64_MAX ? INT64_MAX : (a)+(b))\
+    : (a)+(b) < 0 ? 0 : (a)+(b))
 
 /* Adds a value to the size, asize and items fields of *d and its parents */
 void addparentstats(struct dir *, int64_t, int64_t, int);
-- 
GitLab