]> git.ozlabs.org Git - ccan/blobdiff - ccan/tally/tally.c
tally: Slightly simplify tally_new
[ccan] / ccan / tally / tally.c
index b89b0600ac301d0f5d088cb5a31176c841e1c8c3..a5eedcb951bfafc819701a740bcad64e68f162ac 100644 (file)
@@ -1,4 +1,4 @@
-#include "config.h"
+/* Licensed under LGPLv3+ - see LICENSE file for details */
 #include <ccan/tally/tally.h>
 #include <ccan/build_assert/build_assert.h>
 #include <ccan/likely/likely.h>
@@ -7,6 +7,7 @@
 #include <string.h>
 #include <stdio.h>
 #include <assert.h>
+#include <stdlib.h>
 
 #define SIZET_BITS (sizeof(size_t)*CHAR_BIT)
 
@@ -27,18 +28,21 @@ struct tally *tally_new(unsigned buckets)
        if (buckets == 0)
                buckets = 1;
 
-       /* Check for overflow. */
-       if (buckets && SIZE_MAX / buckets < sizeof(tally->counts[0]))
+       /* Overly cautious check for overflow. */
+       if (sizeof(*tally) * buckets / sizeof(*tally) != buckets)
+               return NULL;
+       tally = (struct tally *)malloc(
+               sizeof(*tally) + sizeof(tally->counts[0])*(buckets-1));
+       if (tally == NULL) {
                return NULL;
-       tally = malloc(sizeof(*tally) + sizeof(tally->counts[0])*(buckets-1));
-       if (tally) {
-               tally->max = ((size_t)1 << (SIZET_BITS - 1));
-               tally->min = ~tally->max;
-               tally->total[0] = tally->total[1] = 0;
-               tally->buckets = buckets;
-               tally->step_bits = 0;
-               memset(tally->counts, 0, sizeof(tally->counts[0])*buckets);
        }
+
+       tally->max = ((size_t)1 << (SIZET_BITS - 1));
+       tally->min = ~tally->max;
+       tally->total[0] = tally->total[1] = 0;
+       tally->buckets = buckets;
+       tally->step_bits = 0;
+       memset(tally->counts, 0, sizeof(tally->counts[0])*buckets);
        return tally;
 }
 
@@ -322,7 +326,7 @@ ssize_t tally_total(const struct tally *tally, ssize_t *overflow)
        }
 
        /* If result is negative, make sure we can represent it. */
-       if (tally->total[1] & (1 << (SIZET_BITS-1))) {
+       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
@@ -448,7 +452,7 @@ char *tally_histogram(const struct tally *tally,
                        largest_bucket = tally->counts[i];
        }
 
-       p = graph = malloc(height * (width + 1) + 1);
+       p = graph = (char *)malloc(height * (width + 1) + 1);
        if (!graph) {
                free(tmp);
                return NULL;