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