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