xref: /aosp_15_r20/external/armnn/samples/common/src/Utils/CmdArgsParser.cpp (revision 89c4ff92f2867872bb9e2354d150bf0c8c502810)
1 //
2 // Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 
6 #include "CmdArgsParser.hpp"
7 #include <iostream>
8 /*
9  * Checks that a particular option was specified by the user
10  */
CheckOptionSpecified(const std::map<std::string,std::string> & options,const std::string & option)11 bool CheckOptionSpecified(const std::map<std::string, std::string>& options, const std::string& option)
12 {
13     auto it = options.find(option);
14     return it!=options.end();
15 }
16 
17 /*
18  * Retrieves the user provided option
19  */
GetSpecifiedOption(const std::map<std::string,std::string> & options,const std::string & option)20 std::string GetSpecifiedOption(const std::map<std::string, std::string>& options, const std::string& option)
21 {
22     if (CheckOptionSpecified(options, option)){
23         return options.at(option);
24     }
25     else
26     {
27         throw std::invalid_argument("Required option: " + option + " not defined.");
28     }
29 }
30 
31 /*
32  * Parses all the command line options provided by the user and stores in a map.
33  */
ParseOptions(std::map<std::string,std::string> & options,std::map<std::string,std::string> & acceptedOptions,char * argv[],int argc)34 int ParseOptions(std::map<std::string, std::string>& options, std::map<std::string, std::string>& acceptedOptions,
35                  char *argv[], int argc)
36 {
37     for (int i = 1; i < argc; ++i)
38     {
39         std::string currentOption = std::string(argv[i]);
40         auto it = acceptedOptions.find(currentOption);
41         if (it != acceptedOptions.end())
42         {
43             if (i + 1 < argc && std::string(argv[i + 1]).rfind("--", 0) != 0)
44             {
45                 std::string value = argv[++i];
46                 options.insert({it->first, value});
47             }
48             else if (std::string(argv[i]) == "HELP")
49             {
50                 std::cout << "Available options" << std::endl;
51                 for (auto & acceptedOption : acceptedOptions)
52                 {
53                     std::cout << acceptedOption.first << " : " << acceptedOption.second << std::endl;
54                 }
55                 return 2;
56             }
57             else
58             {
59                 std::cerr << std::string(argv[i]) << " option requires one argument." << std::endl;
60                 return 1;
61             }
62         }
63         else
64         {
65             std::cerr << "Unrecognised option: " << std::string(argv[i]) << std::endl;
66             return 1;
67         }
68     }
69     return 0;
70 }
71