ftwin 0.8.10
human_size.c
Go to the documentation of this file.
1
6#include "human_size.h"
7#include <ctype.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11#include <apr_strings.h>
12
13const char *format_human_size(apr_off_t size, apr_pool_t *pool)
14{
15 const char *units[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" };
16 int i = 0;
17 double readable_size = (double) size;
18
19 while (readable_size >= 1024.0 && i < (sizeof(units) / sizeof(units[0]) - 1)) {
20 readable_size /= 1024.0;
21 i++;
22 }
23
24 if (i == 0) {
25 return apr_psprintf(pool, "%d %s", (int) readable_size, units[i]);
26 }
27 else {
28 return apr_psprintf(pool, "%.1f %s", readable_size, units[i]);
29 }
30}
31
32apr_off_t parse_human_size(const char *size_str)
33{
34 char *endptr;
35 double size = strtod(size_str, &endptr);
36 apr_off_t multiplier = 1;
37
38 if (endptr == size_str) {
39 return -1; // Not a valid number
40 }
41
42 while (*endptr && isspace((unsigned char) *endptr)) {
43 endptr++;
44 }
45
46 if (*endptr) {
47 switch (toupper((unsigned char) *endptr)) {
48 case 'T':
49 multiplier = 1024LL * 1024LL * 1024LL * 1024LL;
50 break;
51 case 'G':
52 multiplier = 1024LL * 1024LL * 1024LL;
53 break;
54 case 'M':
55 multiplier = 1024LL * 1024LL;
56 break;
57 case 'K':
58 multiplier = 1024LL;
59 break;
60 default:
61 return -1; // Invalid suffix
62 }
63 }
64
65 return (apr_off_t) (size * multiplier);
66}
const char * format_human_size(apr_off_t size, apr_pool_t *pool)
Formats a size in bytes into a human-readable string.
Definition human_size.c:13
apr_off_t parse_human_size(const char *size_str)
Parses a human-readable size string (e.g., "10M", "2.5G") into bytes.
Definition human_size.c:32
Utilities for parsing and formatting human-readable file sizes.