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