1 /*
2 * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
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 "network/softbus/softbus_session_pool.h"
16 #include "utils_log.h"
17 #include <algorithm>
18
19 namespace OHOS {
20 namespace Storage {
21 namespace DistributedFile {
22 constexpr int32_t SESSION_COUNT = 10;
GetInstance()23 SoftBusSessionPool &SoftBusSessionPool::GetInstance()
24 {
25 static SoftBusSessionPool instance;
26 return instance;
27 }
28
GenerateSessionName(const SessionInfo & sessionInfo)29 std::string SoftBusSessionPool::GenerateSessionName(const SessionInfo &sessionInfo)
30 {
31 std::lock_guard<std::mutex> createSessionMutex(sessionMutex_);
32 for (int32_t i = 0; i < SESSION_COUNT; i++) {
33 std::string sessionName = std::string(SESSION_NAME_PREFIX) + std::to_string(i);
34 auto it = sessionMap_.find(sessionName);
35 if (it == sessionMap_.end()) {
36 sessionMap_.insert(std::pair<std::string, SessionInfo>(sessionName, sessionInfo));
37 return sessionName;
38 }
39 }
40 return "";
41 }
42
AddSessionInfo(const std::string & sessionName,const SessionInfo & sessionInfo)43 void SoftBusSessionPool::AddSessionInfo(const std::string &sessionName, const SessionInfo &sessionInfo)
44 {
45 std::lock_guard<std::mutex> createSessionMutex(sessionMutex_);
46 sessionMap_.insert(std::pair<std::string, SessionInfo>(sessionName, sessionInfo));
47 }
48
DeleteSessionInfo(const std::string & sessionName)49 void SoftBusSessionPool::DeleteSessionInfo(const std::string &sessionName)
50 {
51 std::lock_guard<std::mutex> createSessionMutex(sessionMutex_);
52 sessionMap_.erase(sessionName);
53 }
54
GetSessionInfo(const std::string & sessionName,SessionInfo & sessionInfo)55 bool SoftBusSessionPool::GetSessionInfo(const std::string &sessionName, SessionInfo &sessionInfo)
56 {
57 std::lock_guard<std::mutex> createSessionMutex(sessionMutex_);
58 for (const auto &it : sessionMap_) {
59 if (it.first == sessionName) {
60 sessionInfo = it.second;
61 return true;
62 }
63 }
64 return false;
65 }
66 } // namespace DistributedFile
67 } // namespace Storage
68 } // namespace OHOS