parse_num.c revision b4e0163d53613ae47f79c661f7c1e2009a271c79
1/*
2 * parse_num.c		- Parse the number of blocks
3 *
4 * Copyright (C) 2004,2005  Theodore Ts'o <tytso@mit.edu>
5 *
6 * This file can be redistributed under the terms of the GNU Library General
7 * Public License
8 */
9
10#include "e2p.h"
11
12#include <stdlib.h>
13
14unsigned long long parse_num_blocks2(const char *arg, int log_block_size)
15{
16	char *p;
17	unsigned long long num;
18
19	num = strtoull(arg, &p, 0);
20
21	if (p[0] && p[1])
22		return 0;
23
24	switch (*p) {		/* Using fall-through logic */
25	case 'T': case 't':
26		num <<= 10;
27	case 'G': case 'g':
28		num <<= 10;
29	case 'M': case 'm':
30		num <<= 10;
31	case 'K': case 'k':
32		num >>= log_block_size;
33		break;
34	case 's':
35		num >>= (1+log_block_size);
36		break;
37	case '\0':
38		break;
39	default:
40		return 0;
41	}
42	return num;
43}
44
45unsigned long parse_num_blocks(const char *arg, int log_block_size)
46{
47	return parse_num_blocks2(arg, log_block_size);
48}
49
50#ifdef DEBUG
51#include <unistd.h>
52#include <stdio.h>
53
54main(int argc, char **argv)
55{
56	unsigned long num;
57	int log_block_size = 0;
58
59	if (argc != 2) {
60		fprintf(stderr, "Usage: %s arg\n", argv[0]);
61		exit(1);
62	}
63
64	num = parse_num_blocks(argv[1], log_block_size);
65
66	printf("Parsed number: %lu\n", num);
67	exit(0);
68}
69#endif
70