1 //
2 // Copyright (C) 2020 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 #include <string>
17
18 #include <android-base/strings.h>
19
20 namespace cuttlefish {
21
22 class CommandParser {
23 public:
CommandParser(const std::string & command)24 explicit CommandParser(const std::string& command) : copy_command_(command) {
25 command_ = copy_command_;
26 };
27
28 ~CommandParser() = default;
29
30 CommandParser(CommandParser&&) = default;
31 CommandParser& operator=(CommandParser&&) = default;
32
33 inline void SkipPrefix();
34 inline void SkipPrefixAT();
35 inline void SkipComma();
36 inline void SkipWhiteSpace();
37
38 std::string_view GetNextStr();
39 std::string_view GetNextStr(char flag);
40 std::string GetNextStrDeciToHex(); /* for AT+CRSM */
41
42 int GetNextInt();
43 int GetNextHexInt();
44
45 const std::string_view* operator->() const { return &command_; }
46 const std::string_view& operator*() const { return command_; }
47 bool operator==(const std::string &rhs) const { return command_ == rhs; }
48 std::string_view::const_reference& operator[](int index) const { return command_[index]; }
49
50 private:
51 std::string copy_command_;
52 std::string_view command_;
53 };
54
55 /**
56 * Skip the substring before the first '=', including '='
57 * updates command_
58 * If '=' not exists, command_ remains unchanged
59 */
SkipPrefix()60 inline void CommandParser::SkipPrefix() {
61 auto pos = command_.find('=');
62 if (pos != std::string_view::npos) {
63 command_.remove_prefix(std::min(pos + 1, command_.size()));
64 }
65 }
66
67 /**
68 * Skip the next "AT" substring
69 * updates command_
70 */
SkipPrefixAT()71 inline void CommandParser::SkipPrefixAT() {
72 android::base::ConsumePrefix(&command_, std::string_view("AT"));
73 }
74
75 /**
76 * Skip the next comma
77 * updates command_
78 */
SkipComma()79 inline void CommandParser::SkipComma() {
80 auto pos = command_.find(',');
81 if (pos != std::string_view::npos) {
82 command_.remove_prefix(std::min(pos + 1, command_.size()));
83 }
84 }
85
86 /**
87 * Skip the next whitespace
88 * updates command_
89 */
SkipWhiteSpace()90 inline void CommandParser::SkipWhiteSpace() {
91 auto pos = command_.find(' ');
92 if (pos != std::string_view::npos) {
93 command_.remove_prefix(std::min(pos + 1, command_.size()));
94 }
95 }
96
97 } // namespace cuttlefish
98