+ssize_t tally_total(const struct tally *tally, ssize_t *overflow)
+{
+ if (overflow) {
+ *overflow = tally->total[1];
+ return tally->total[0];
+ }
+
+ /* If result is negative, make sure we can represent it. */
+ if (tally->total[1] & ((size_t)1 << (SIZET_BITS-1))) {
+ /* Must have only underflowed once, and must be able to
+ * represent result at ssize_t. */
+ if ((~tally->total[1])+1 != 0
+ || (ssize_t)tally->total[0] >= 0) {
+ /* Underflow, return minimum. */
+ return (ssize_t)((size_t)1 << (SIZET_BITS - 1));
+ }
+ } else {
+ /* Result is positive, must not have overflowed, and must be
+ * able to represent as ssize_t. */
+ if (tally->total[1] || (ssize_t)tally->total[0] < 0) {
+ /* Overflow. Return maximum. */
+ return (ssize_t)~((size_t)1 << (SIZET_BITS - 1));
+ }
+ }
+ return tally->total[0];
+}
+