1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <grpc/support/port_platform.h>
16
17 #include "src/core/ext/transport/binder/client/connection_id_generator.h"
18
19 #ifndef GRPC_NO_BINDER
20
21 #include "absl/strings/str_cat.h"
22
23 namespace {
24 // Make sure `s` does not contain characters other than numbers, alphabets,
25 // period and underscore
Normalize(absl::string_view str_view)26 std::string Normalize(absl::string_view str_view) {
27 std::string s = std::string(str_view);
28 for (size_t i = 0; i < s.length(); i++) {
29 if (!isalnum(s[i]) && s[i] != '.') {
30 s[i] = '_';
31 }
32 }
33 return s;
34 }
35
36 // Remove prefix of the string if the string is longer than len
StripToLength(const std::string & s,size_t len)37 std::string StripToLength(const std::string& s, size_t len) {
38 if (s.length() > len) {
39 return s.substr(s.length() - len, len);
40 }
41 return s;
42 }
43 } // namespace
44
45 namespace grpc_binder {
46
Generate(absl::string_view uri)47 std::string ConnectionIdGenerator::Generate(absl::string_view uri) {
48 // reserve some room for serial number
49 const size_t kReserveForNumbers = 15;
50 std::string s =
51 StripToLength(Normalize(uri), kPathLengthLimit - kReserveForNumbers);
52 std::string ret;
53 {
54 grpc_core::MutexLock l(&m_);
55 // Insert a hyphen before serial number
56 ret = absl::StrCat(s, "-", ++count_);
57 }
58 GPR_ASSERT(ret.length() < kPathLengthLimit);
59 return ret;
60 }
61
GetConnectionIdGenerator()62 ConnectionIdGenerator* GetConnectionIdGenerator() {
63 static ConnectionIdGenerator* cig = new ConnectionIdGenerator();
64 return cig;
65 }
66
67 } // namespace grpc_binder
68 #endif
69