|
| 1 | +/* Copyright (c) 2016, David Boehme. |
| 2 | + * All rights reserved. |
| 3 | + * |
| 4 | + * Redistribution and use in source and binary forms, with or without |
| 5 | + * modification, are permitted provided that the following conditions are |
| 6 | + * met: |
| 7 | + * |
| 8 | + * 1. Redistributions of source code must retain the above copyright |
| 9 | + * notice, this list of conditions and the following disclaimer. |
| 10 | + * |
| 11 | + * 2. Redistributions in binary form must reproduce the above copyright |
| 12 | + * notice, this list of conditions and the following disclaimer in the |
| 13 | + * documentation and/or other materials provided with the distribution. |
| 14 | + * |
| 15 | + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 16 | + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 17 | + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 18 | + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 19 | + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 20 | + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 21 | + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 22 | + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 23 | + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 24 | + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 25 | + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 26 | + */ |
| 27 | + |
| 28 | +/*! \file unitfmt.c |
| 29 | + * \brief Scale values to human-readable size |
| 30 | + */ |
| 31 | + |
| 32 | +#include "caliper/common/c-util/unitfmt.h" |
| 33 | + |
| 34 | +const struct unitfmt_table unitfmt_bytes[] = { |
| 35 | + { 1, "Byte(s)" }, |
| 36 | + { 1024, "KiB" }, |
| 37 | + { 1024 * 1024, "MiB" }, |
| 38 | + { 1024 * 1024 * 1024, "GiB" }, |
| 39 | + { 0, "GiB" } |
| 40 | +}; |
| 41 | + |
| 42 | +unitfmt_result |
| 43 | +unitfmt(unsigned long long val, const struct unitfmt_table table[]) |
| 44 | +{ |
| 45 | + double dval = (double) val; |
| 46 | + unitfmt_result result = { dval, table[0].symbol }; |
| 47 | + |
| 48 | + for (const struct unitfmt_table* p = table; p->factor && dval >= p->factor; ++p) { |
| 49 | + result.val = dval / p->factor; |
| 50 | + result.symbol = p->symbol; |
| 51 | + } |
| 52 | + |
| 53 | + return result; |
| 54 | +} |
0 commit comments