olp-cpp-sdk 1.24.0
Loading...
Searching...
No Matches
CancellationContext.inl
1/*
2 * Copyright (C) 2019 HERE Europe B.V.
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 * SPDX-License-Identifier: Apache-2.0
17 * License-Filename: LICENSE
18 */
19
20#pragma once
21
22namespace olp {
23namespace client {
24
25inline CancellationContext::CancellationContext()
26 : impl_(std::make_shared<CancellationContextImpl>()) {}
27
28inline bool CancellationContext::ExecuteOrCancelled(
29 const std::function<CancellationToken()>& execute_fn,
30 const std::function<void()>& cancel_fn) {
31 if (!impl_) {
32 return true;
33 }
34
35 std::lock_guard<std::recursive_mutex> lock(impl_->mutex_);
36
37 if (impl_->is_cancelled_) {
38 if (cancel_fn) {
39 cancel_fn();
40 }
41 return false;
42 }
43
44 if (execute_fn) {
45 impl_->sub_operation_cancel_token_ = execute_fn();
46 }
47
48 return true;
49}
50
51inline void CancellationContext::CancelOperation() {
52 if (!impl_) {
53 return;
54 }
55
56 std::lock_guard<std::recursive_mutex> lock(impl_->mutex_);
57 if (impl_->is_cancelled_) {
58 return;
59 }
60
61 impl_->sub_operation_cancel_token_.Cancel();
62 impl_->sub_operation_cancel_token_ = CancellationToken();
63 impl_->is_cancelled_ = true;
64}
65
66inline bool CancellationContext::IsCancelled() const {
67 if (!impl_) {
68 return false;
69 }
70
71 std::lock_guard<std::recursive_mutex> lock(impl_->mutex_);
72 return impl_->is_cancelled_;
73}
74
75inline size_t CancellationContextHash::operator()(
76 const CancellationContext& context) const {
77 return std::hash<
78 std::shared_ptr<CancellationContext::CancellationContextImpl>>()(
79 context.impl_);
80}
81
82inline bool CancellationContextEquality::operator()(
83 const CancellationContext& lhs, const CancellationContext& rhs) const {
84 return lhs.impl_ == rhs.impl_;
85}
86
87} // namespace client
88} // namespace olp
A wrapper that manages the cancellation state of an asynchronous operation in a thread-safe way.
Definition CancellationContext.h:40
Cancels service requests.
Definition CancellationToken.h:33
Rules all the other namespaces.
Definition AppleSignInProperties.h:24