1 /* -*- Mode: c++ -*- */
2 /***************************************************************************
3  *            bytesize_parser.cc
4  *
5  *  Sat Mar  4 18:00:12 CET 2017
6  *  Copyright 2017 Goran Mekić
7  *  meka@tilda.center
8  ****************************************************************************/
9 
10 /*
11  *  This file is part of DrumGizmo.
12  *
13  *  DrumGizmo is free software; you can redistribute it and/or modify
14  *  it under the terms of the GNU Lesser General Public License as published by
15  *  the Free Software Foundation; either version 3 of the License, or
16  *  (at your option) any later version.
17  *
18  *  DrumGizmo is distributed in the hope that it will be useful,
19  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *  GNU Lesser General Public License for more details.
22  *
23  *  You should have received a copy of the GNU Lesser General Public License
24  *  along with DrumGizmo; if not, write to the Free Software
25  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
26  */
27 #include "bytesizeparser.h"
28 #include <iostream>
29 #include <stdexcept>
30 
31 
suffixToSize(const char & suffix)32 static std::size_t suffixToSize(const char& suffix)
33 {
34 	int size = 1;
35 	switch(suffix)
36 	{
37 	case 'k':
38 		size <<= 10;
39 		break;
40 	case 'M':
41 		size <<= 20;
42 		break;
43 	case 'G':
44 		size <<= 30;
45 		break;
46 	default:
47 		size = 0;
48 		break;
49 	}
50 	return size;
51 }
52 
53 
byteSizeParser(const std::string & argument)54 std::size_t byteSizeParser(const std::string& argument)
55 {
56 	std::string::size_type suffix_index;
57 	std::size_t size;
58 	std::string suffix;
59 	bool error = false;
60 
61 	if(argument.find('-') != std::string::npos)
62 	{
63 		error = true;
64 	}
65 
66 	try
67 	{
68 		size = std::stoi(argument, &suffix_index);
69 	}
70 	catch(std::invalid_argument&)
71 	{
72 		std::cerr << "Invalid argument for diskstreamsize" << std::endl;
73 		error = true;
74 	}
75 	catch(std::out_of_range&)
76 	{
77 		std::cerr << "Number too big. Try using bigger suffix for diskstreamsize" << std::endl;
78 		error = true;
79 	}
80 	if(!error)
81 	{
82 		suffix = argument.substr(suffix_index);
83 		if (suffix.length() > 1)
84 		{
85 			error = true;
86 		}
87 	}
88 	if(!error && suffix.size() > 0)
89 	{
90 		std::size_t suffix_size = suffixToSize(suffix[0]);
91 		size *= suffix_size;
92 	}
93 	if(error)
94 	{
95 		return 0;
96 	}
97 	return size;
98 }
99