1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "command.h"
18 
19 #include <algorithm>
20 #include <string>
21 #include <vector>
22 
Commands()23 static std::vector<Command*>& Commands() {
24   // commands is used in the constructor of Command. Defining it as a static
25   // variable in a function makes sure it is initialized before use.
26   static std::vector<Command*> commands;
27   return commands;
28 }
29 
FindCommandByName(const std::string & cmd_name)30 Command* Command::FindCommandByName(const std::string& cmd_name) {
31   for (auto& command : Commands()) {
32     if (command->Name() == cmd_name) {
33       return command;
34     }
35   }
36   return nullptr;
37 }
38 
CompareCommandByName(Command * cmd1,Command * cmd2)39 static bool CompareCommandByName(Command* cmd1, Command* cmd2) {
40   return cmd1->Name() < cmd2->Name();
41 }
42 
GetAllCommands()43 const std::vector<Command*>& Command::GetAllCommands() {
44   std::sort(Commands().begin(), Commands().end(), CompareCommandByName);
45   return Commands();
46 }
47 
RegisterCommand(Command * cmd)48 void Command::RegisterCommand(Command* cmd) {
49   Commands().push_back(cmd);
50 }
51 
UnRegisterCommand(Command * cmd)52 void Command::UnRegisterCommand(Command* cmd) {
53   for (auto it = Commands().begin(); it != Commands().end(); ++it) {
54     if (*it == cmd) {
55       Commands().erase(it);
56       break;
57     }
58   }
59 }
60