tally: Fix a c++ warning
[ccan] / ccan / tally / tally.c
1 /* Licensed under LGPLv3+ - see LICENSE file for details */
2 #include <ccan/tally/tally.h>
3 #include <ccan/build_assert/build_assert.h>
4 #include <ccan/likely/likely.h>
5 #include <stdint.h>
6 #include <limits.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <assert.h>
10 #include <stdlib.h>
11
12 #define SIZET_BITS (sizeof(size_t)*CHAR_BIT)
13
14 /* We use power of 2 steps.  I tried being tricky, but it got buggy. */
15 struct tally {
16         ssize_t min, max;
17         size_t total[2];
18         /* This allows limited frequency analysis. */
19         unsigned buckets, step_bits;
20         size_t counts[1 /* Actually: [buckets] */ ];
21 };
22
23 struct tally *tally_new(unsigned buckets)
24 {
25         struct tally *tally;
26
27         /* There is always 1 bucket. */
28         if (buckets == 0)
29                 buckets = 1;
30
31         /* Overly cautious check for overflow. */
32         if (sizeof(*tally) * buckets / sizeof(*tally) != buckets)
33                 return NULL;
34         tally = (struct tally *)malloc(
35                 sizeof(*tally) + sizeof(tally->counts[0])*(buckets-1));
36         if (tally) {
37                 tally->max = ((size_t)1 << (SIZET_BITS - 1));
38                 tally->min = ~tally->max;
39                 tally->total[0] = tally->total[1] = 0;
40                 tally->buckets = buckets;
41                 tally->step_bits = 0;
42                 memset(tally->counts, 0, sizeof(tally->counts[0])*buckets);
43         }
44         return tally;
45 }
46
47 static unsigned bucket_of(ssize_t min, unsigned step_bits, ssize_t val)
48 {
49         /* Don't over-shift. */
50         if (step_bits == SIZET_BITS)
51                 return 0;
52         assert(step_bits < SIZET_BITS);
53         return (size_t)(val - min) >> step_bits;
54 }
55
56 /* Return the min value in bucket b. */
57 static ssize_t bucket_min(ssize_t min, unsigned step_bits, unsigned b)
58 {
59         /* Don't over-shift. */
60         if (step_bits == SIZET_BITS)
61                 return min;
62         assert(step_bits < SIZET_BITS);
63         return min + ((ssize_t)b << step_bits);
64 }
65
66 /* Does shifting by this many bits truncate the number? */
67 static bool shift_overflows(size_t num, unsigned bits)
68 {
69         if (bits == 0)
70                 return false;
71
72         return ((num << bits) >> 1) != (num << (bits - 1));
73 }
74
75 /* When min or max change, we may need to shuffle the frequency counts. */
76 static void renormalize(struct tally *tally,
77                         ssize_t new_min, ssize_t new_max)
78 {
79         size_t range, spill;
80         unsigned int i, old_min;
81
82         /* Uninitialized?  Don't do anything... */
83         if (tally->max < tally->min)
84                 goto update;
85
86         /* If we don't have sufficient range, increase step bits until
87          * buckets cover entire range of ssize_t anyway. */
88         range = (new_max - new_min) + 1;
89         while (!shift_overflows(tally->buckets, tally->step_bits)
90                && range > ((size_t)tally->buckets << tally->step_bits)) {
91                 /* Collapse down. */
92                 for (i = 1; i < tally->buckets; i++) {
93                         tally->counts[i/2] += tally->counts[i];
94                         tally->counts[i] = 0;
95                 }
96                 tally->step_bits++;
97         }
98
99         /* Now if minimum has dropped, move buckets up. */
100         old_min = bucket_of(new_min, tally->step_bits, tally->min);
101         memmove(tally->counts + old_min,
102                 tally->counts,
103                 sizeof(tally->counts[0]) * (tally->buckets - old_min));
104         memset(tally->counts, 0, sizeof(tally->counts[0]) * old_min);
105
106         /* If we moved boundaries, adjust buckets to that ratio. */
107         spill = (tally->min - new_min) % (1 << tally->step_bits);
108         for (i = 0; i < tally->buckets-1; i++) {
109                 size_t adjust = (tally->counts[i] >> tally->step_bits) * spill;
110                 tally->counts[i] -= adjust;
111                 tally->counts[i+1] += adjust;
112         }
113
114 update:
115         tally->min = new_min;
116         tally->max = new_max;
117 }
118
119 void tally_add(struct tally *tally, ssize_t val)
120 {
121         ssize_t new_min = tally->min, new_max = tally->max;
122         bool need_renormalize = false;
123
124         if (val < tally->min) {
125                 new_min = val;
126                 need_renormalize = true;
127         }
128         if (val > tally->max) {
129                 new_max = val;
130                 need_renormalize = true;
131         }
132         if (need_renormalize)
133                 renormalize(tally, new_min, new_max);
134
135         /* 128-bit arithmetic!  If we didn't want exact mean, we could just
136          * pull it out of counts. */
137         if (val > 0 && tally->total[0] + val < tally->total[0])
138                 tally->total[1]++;
139         else if (val < 0 && tally->total[0] + val > tally->total[0])
140                 tally->total[1]--;
141         tally->total[0] += val;
142         tally->counts[bucket_of(tally->min, tally->step_bits, val)]++;
143 }
144
145 size_t tally_num(const struct tally *tally)
146 {
147         size_t i, num = 0;
148         for (i = 0; i < tally->buckets; i++)
149                 num += tally->counts[i];
150         return num;
151 }
152
153 ssize_t tally_min(const struct tally *tally)
154 {
155         return tally->min;
156 }
157
158 ssize_t tally_max(const struct tally *tally)
159 {
160         return tally->max;
161 }
162
163 /* FIXME: Own ccan module please! */
164 static unsigned fls64(uint64_t val)
165 {
166 #if HAVE_BUILTIN_CLZL
167         if (val <= ULONG_MAX) {
168                 /* This is significantly faster! */
169                 return val ? sizeof(long) * CHAR_BIT - __builtin_clzl(val) : 0;
170         } else {
171 #endif
172         uint64_t r = 64;
173
174         if (!val)
175                 return 0;
176         if (!(val & 0xffffffff00000000ull)) {
177                 val <<= 32;
178                 r -= 32;
179         }
180         if (!(val & 0xffff000000000000ull)) {
181                 val <<= 16;
182                 r -= 16;
183         }
184         if (!(val & 0xff00000000000000ull)) {
185                 val <<= 8;
186                 r -= 8;
187         }
188         if (!(val & 0xf000000000000000ull)) {
189                 val <<= 4;
190                 r -= 4;
191         }
192         if (!(val & 0xc000000000000000ull)) {
193                 val <<= 2;
194                 r -= 2;
195         }
196         if (!(val & 0x8000000000000000ull)) {
197                 val <<= 1;
198                 r -= 1;
199         }
200         return r;
201 #if HAVE_BUILTIN_CLZL
202         }
203 #endif
204 }
205
206 /* This is stolen straight from Hacker's Delight. */
207 static uint64_t divlu64(uint64_t u1, uint64_t u0, uint64_t v)
208 {
209         const uint64_t b = 4294967296ULL; // Number base (32 bits).
210         uint32_t un[4],           // Dividend and divisor
211                 vn[2];            // normalized and broken
212                                   // up into halfwords.
213         uint32_t q[2];            // Quotient as halfwords.
214         uint64_t un1, un0,        // Dividend and divisor
215                 vn0;              // as fullwords.
216         uint64_t qhat;            // Estimated quotient digit.
217         uint64_t rhat;            // A remainder.
218         uint64_t p;               // Product of two digits.
219         int64_t s, i, j, t, k;
220
221         if (u1 >= v)              // If overflow, return the largest
222                 return (uint64_t)-1; // possible quotient.
223
224         s = 64 - fls64(v);                // 0 <= s <= 63.
225         vn0 = v << s;             // Normalize divisor.
226         vn[1] = vn0 >> 32;        // Break divisor up into
227         vn[0] = vn0 & 0xFFFFFFFF; // two 32-bit halves.
228
229         // Shift dividend left.
230         un1 = ((u1 << s) | (u0 >> (64 - s))) & (-s >> 63);
231         un0 = u0 << s;
232         un[3] = un1 >> 32;        // Break dividend up into
233         un[2] = un1;              // four 32-bit halfwords
234         un[1] = un0 >> 32;        // Note: storing into
235         un[0] = un0;              // halfwords truncates.
236
237         for (j = 1; j >= 0; j--) {
238                 // Compute estimate qhat of q[j].
239                 qhat = (un[j+2]*b + un[j+1])/vn[1];
240                 rhat = (un[j+2]*b + un[j+1]) - qhat*vn[1];
241         again:
242                 if (qhat >= b || qhat*vn[0] > b*rhat + un[j]) {
243                         qhat = qhat - 1;
244                         rhat = rhat + vn[1];
245                         if (rhat < b) goto again;
246                 }
247
248                 // Multiply and subtract.
249                 k = 0;
250                 for (i = 0; i < 2; i++) {
251                         p = qhat*vn[i];
252                         t = un[i+j] - k - (p & 0xFFFFFFFF);
253                         un[i+j] = t;
254                         k = (p >> 32) - (t >> 32);
255                 }
256                 t = un[j+2] - k;
257                 un[j+2] = t;
258
259                 q[j] = qhat;              // Store quotient digit.
260                 if (t < 0) {              // If we subtracted too
261                         q[j] = q[j] - 1;  // much, add back.
262                         k = 0;
263                         for (i = 0; i < 2; i++) {
264                                 t = un[i+j] + vn[i] + k;
265                                 un[i+j] = t;
266                                 k = t >> 32;
267                         }
268                         un[j+2] = un[j+2] + k;
269                 }
270         } // End j.
271
272         return q[1]*b + q[0];
273 }
274
275 static int64_t divls64(int64_t u1, uint64_t u0, int64_t v)
276 {
277         int64_t q, uneg, vneg, diff, borrow;
278
279         uneg = u1 >> 63;          // -1 if u < 0.
280         if (uneg) {               // Compute the absolute
281                 u0 = -u0;         // value of the dividend u.
282                 borrow = (u0 != 0);
283                 u1 = -u1 - borrow;
284         }
285
286         vneg = v >> 63;           // -1 if v < 0.
287         v = (v ^ vneg) - vneg;    // Absolute value of v.
288
289         if ((uint64_t)u1 >= (uint64_t)v)
290                 goto overflow;
291
292         q = divlu64(u1, u0, v);
293
294         diff = uneg ^ vneg;       // Negate q if signs of
295         q = (q ^ diff) - diff;    // u and v differed.
296
297         if ((diff ^ q) < 0 && q != 0) {    // If overflow, return the largest
298         overflow:                          // possible neg. quotient.
299                 q = 0x8000000000000000ULL;
300         }
301         return q;
302 }
303
304 ssize_t tally_mean(const struct tally *tally)
305 {
306         size_t count = tally_num(tally);
307         if (!count)
308                 return 0;
309
310         if (sizeof(tally->total[0]) == sizeof(uint32_t)) {
311                 /* Use standard 64-bit arithmetic. */
312                 int64_t total = tally->total[0]
313                         | (((uint64_t)tally->total[1]) << 32);
314                 return total / count;
315         }
316         return divls64(tally->total[1], tally->total[0], count);
317 }
318
319 ssize_t tally_total(const struct tally *tally, ssize_t *overflow)
320 {
321         if (overflow) {
322                 *overflow = tally->total[1];
323                 return tally->total[0];
324         }
325
326         /* If result is negative, make sure we can represent it. */
327         if (tally->total[1] & ((size_t)1 << (SIZET_BITS-1))) {
328                 /* Must have only underflowed once, and must be able to
329                  * represent result at ssize_t. */
330                 if ((~tally->total[1])+1 != 0
331                     || (ssize_t)tally->total[0] >= 0) {
332                         /* Underflow, return minimum. */
333                         return (ssize_t)((size_t)1 << (SIZET_BITS - 1));
334                 }
335         } else {
336                 /* Result is positive, must not have overflowed, and must be
337                  * able to represent as ssize_t. */
338                 if (tally->total[1] || (ssize_t)tally->total[0] < 0) {
339                         /* Overflow.  Return maximum. */
340                         return (ssize_t)~((size_t)1 << (SIZET_BITS - 1));
341                 }
342         }
343         return tally->total[0];
344 }
345
346 static ssize_t bucket_range(const struct tally *tally, unsigned b, size_t *err)
347 {
348         ssize_t min, max;
349
350         min = bucket_min(tally->min, tally->step_bits, b);
351         if (b == tally->buckets - 1)
352                 max = tally->max;
353         else
354                 max = bucket_min(tally->min, tally->step_bits, b+1) - 1;
355
356         /* FIXME: Think harder about cumulative error; is this enough?. */
357         *err = (max - min + 1) / 2;
358         /* Avoid overflow. */
359         return min + (max - min) / 2;
360 }
361
362 ssize_t tally_approx_median(const struct tally *tally, size_t *err)
363 {
364         size_t count = tally_num(tally), total = 0;
365         unsigned int i;
366
367         for (i = 0; i < tally->buckets; i++) {
368                 total += tally->counts[i];
369                 if (total * 2 >= count)
370                         break;
371         }
372         return bucket_range(tally, i, err);
373 }
374
375 ssize_t tally_approx_mode(const struct tally *tally, size_t *err)
376 {
377         unsigned int i, min_best = 0, max_best = 0;
378
379         for (i = 0; i < tally->buckets; i++) {
380                 if (tally->counts[i] > tally->counts[min_best]) {
381                         min_best = max_best = i;
382                 } else if (tally->counts[i] == tally->counts[min_best]) {
383                         max_best = i;
384                 }
385         }
386
387         /* We can have more than one best, making our error huge. */
388         if (min_best != max_best) {
389                 ssize_t min, max;
390                 min = bucket_range(tally, min_best, err);
391                 max = bucket_range(tally, max_best, err);
392                 max += *err;
393                 *err += (size_t)(max - min);
394                 return min + (max - min) / 2;
395         }
396
397         return bucket_range(tally, min_best, err);
398 }
399
400 static unsigned get_max_bucket(const struct tally *tally)
401 {
402         unsigned int i;
403
404         for (i = tally->buckets; i > 0; i--)
405                 if (tally->counts[i-1])
406                         break;
407         return i;
408 }
409
410 char *tally_histogram(const struct tally *tally,
411                       unsigned width, unsigned height)
412 {
413         unsigned int i, count, max_bucket, largest_bucket;
414         struct tally *tmp;
415         char *graph, *p;
416
417         assert(width >= TALLY_MIN_HISTO_WIDTH);
418         assert(height >= TALLY_MIN_HISTO_HEIGHT);
419
420         /* Ignore unused buckets. */
421         max_bucket = get_max_bucket(tally);
422
423         /* FIXME: It'd be nice to smooth here... */
424         if (height >= max_bucket) {
425                 height = max_bucket;
426                 tmp = NULL;
427         } else {
428                 /* We create a temporary then renormalize so < height. */
429                 /* FIXME: Antialias properly! */
430                 tmp = tally_new(tally->buckets);
431                 if (!tmp)
432                         return NULL;
433                 tmp->min = tally->min;
434                 tmp->max = tally->max;
435                 tmp->step_bits = tally->step_bits;
436                 memcpy(tmp->counts, tally->counts,
437                        sizeof(tally->counts[0]) * tmp->buckets);
438                 while ((max_bucket = get_max_bucket(tmp)) >= height)
439                         renormalize(tmp, tmp->min, tmp->max * 2);
440                 /* Restore max */
441                 tmp->max = tally->max;
442                 tally = tmp;
443                 height = max_bucket;
444         }
445
446         /* Figure out longest line, for scale. */
447         largest_bucket = 0;
448         for (i = 0; i < tally->buckets; i++) {
449                 if (tally->counts[i] > largest_bucket)
450                         largest_bucket = tally->counts[i];
451         }
452
453         p = graph = malloc(height * (width + 1) + 1);
454         if (!graph) {
455                 free(tmp);
456                 return NULL;
457         }
458
459         for (i = 0; i < height; i++) {
460                 unsigned covered = 1, row;
461
462                 /* People expect minimum at the bottom. */
463                 row = height - i - 1;
464                 count = (double)tally->counts[row] / largest_bucket * (width-1)+1;
465
466                 if (row == 0)
467                         covered = snprintf(p, width, "%zi", tally->min);
468                 else if (row == height - 1)
469                         covered = snprintf(p, width, "%zi", tally->max);
470                 else if (row == bucket_of(tally->min, tally->step_bits, 0))
471                         *p = '+';
472                 else
473                         *p = '|';
474
475                 if (covered > width)
476                         covered = width;
477                 p += covered;
478
479                 if (count > covered)
480                         count -= covered;
481                 else
482                         count = 0;
483
484                 memset(p, '*', count);
485                 p += count;
486                 *p = '\n';
487                 p++;
488         }
489         *p = '\0';
490         free(tmp);
491         return graph;
492 }