1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#ifndef BRPC_ADAPTIVE_PROTOCOL_TYPE_H
19#define BRPC_ADAPTIVE_PROTOCOL_TYPE_H
20
21// To brpc developers: This is a header included by user, don't depend
22// on internal structures, use opaque pointers instead.
23
24#include "butil/strings/string_piece.h"
25#include "brpc/options.pb.h"
26
27namespace brpc {
28
29// NOTE: impl. are in brpc/protocol.cpp
30
31// Convert a case-insensitive string to corresponding ProtocolType which is
32// defined in src/brpc/options.proto
33// Returns: PROTOCOL_UNKNOWN on error.
34ProtocolType StringToProtocolType(const butil::StringPiece& type,
35 bool print_log_on_unknown);
36inline ProtocolType StringToProtocolType(const butil::StringPiece& type)
37{ return StringToProtocolType(type, true); }
38
39// Convert a ProtocolType to a c-style string.
40const char* ProtocolTypeToString(ProtocolType);
41
42// Assignable by both ProtocolType and names.
43class AdaptiveProtocolType {
44public:
45 explicit AdaptiveProtocolType() : _type(PROTOCOL_UNKNOWN) {}
46 explicit AdaptiveProtocolType(ProtocolType type) : _type(type) {}
47 ~AdaptiveProtocolType() {}
48
49 void operator=(ProtocolType type) {
50 _type = type;
51 _name.clear();
52 _param.clear();
53 }
54
55 void operator=(butil::StringPiece name) {
56 butil::StringPiece param;
57 const size_t pos = name.find(':');
58 if (pos != butil::StringPiece::npos) {
59 param = name.substr(pos + 1);
60 name.remove_suffix(name.size() - pos);
61 }
62 _type = StringToProtocolType(name);
63 if (_type == PROTOCOL_UNKNOWN) {
64 _name.assign(name.data(), name.size());
65 } else {
66 _name.clear();
67 }
68 if (!param.empty()) {
69 _param.assign(param.data(), param.size());
70 } else {
71 _param.clear();
72 }
73 };
74
75 operator ProtocolType() const { return _type; }
76
77 const char* name() const {
78 return _name.empty() ? ProtocolTypeToString(_type) : _name.c_str();
79 }
80
81 bool has_param() const { return !_param.empty(); }
82 const std::string& param() const { return _param; }
83
84private:
85 ProtocolType _type;
86 std::string _name;
87 std::string _param;
88};
89
90} // namespace brpc
91
92#endif // BRPC_ADAPTIVE_PROTOCOL_TYPE_H
93