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 "config.h" 13 #include "e2p.h" 14 15 #include <stdlib.h> 16 17 unsigned long long parse_num_blocks2(const char *arg, int log_block_size) 18 { 19 char *p; 20 unsigned long long num; 21 22 num = strtoull(arg, &p, 0); 23 24 if (p[0] && p[1]) 25 return 0; 26 27 switch (*p) { /* Using fall-through logic */ 28 case 'T': case 't': 29 num <<= 10; 30 /* fallthrough */ 31 case 'G': case 'g': 32 num <<= 10; 33 /* fallthrough */ 34 case 'M': case 'm': 35 num <<= 10; 36 /* fallthrough */ 37 case 'K': case 'k': 38 if (log_block_size < 0) 39 num <<= 10; 40 else 41 num >>= log_block_size; 42 break; 43 case 's': 44 if (log_block_size < 0) 45 num <<= 9; 46 else 47 num >>= (1+log_block_size); 48 break; 49 case '\0': 50 break; 51 default: 52 return 0; 53 } 54 return num; 55 } 56 57 unsigned long parse_num_blocks(const char *arg, int log_block_size) 58 { 59 return parse_num_blocks2(arg, log_block_size); 60 } 61 62 #ifdef DEBUG 63 #include <unistd.h> 64 #include <stdio.h> 65 66 main(int argc, char **argv) 67 { 68 unsigned long num; 69 int log_block_size = 0; 70 71 if (argc != 2 && argc != 3) { 72 fprintf(stderr, "Usage: %s arg [log_block_size]\n", argv[0]); 73 exit(1); 74 } 75 76 if (argc == 3) { 77 char *p; 78 79 log_block_size = strtol(argv[2], &p, 0); 80 if (*p) { 81 fprintf(stderr, "Bad log_block_size: %s\n", argv[2]); 82 exit(1); 83 } 84 } 85 86 num = parse_num_blocks(argv[1], log_block_size); 87 88 printf("Parsed number: %lu\n", num); 89 exit(0); 90 } 91 #endif