1 /*
2  * Copyright (C) 2021 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 
17 #pragma once
18 
19 #include <chrono>
20 #include <string>
21 
22 namespace android::hardware::health::storage::test {
23 
24 // Dev GC timeout. This is the timeout used by vold.
25 const uint64_t kDevGcTimeoutSec = 120;
26 const std::chrono::seconds kDevGcTimeout{kDevGcTimeoutSec};
27 // Dev GC timeout tolerance. The HAL may not immediately return after the
28 // timeout, so include an acceptable tolerance.
29 const std::chrono::seconds kDevGcTolerance{3};
30 // Time accounted for RPC calls.
31 const std::chrono::milliseconds kRpcTime{1000};
32 
33 template <typename R>
to_string(std::chrono::duration<R,std::milli> time)34 std::string to_string(std::chrono::duration<R, std::milli> time) {
35     return std::to_string(time.count()) + "ms";
36 }
37 
38 /** An atomic boolean flag that indicates whether a task has finished. */
39 class Flag {
40   public:
OnFinish()41     void OnFinish() {
42         std::unique_lock<std::mutex> lock(mutex_);
43         OnFinishLocked(&lock);
44     }
45     template <typename R, typename P>
Wait(std::chrono::duration<R,P> duration)46     bool Wait(std::chrono::duration<R, P> duration) {
47         std::unique_lock<std::mutex> lock(mutex_);
48         return WaitLocked(&lock, duration);
49     }
50 
51   protected:
52     /** Will unlock. */
OnFinishLocked(std::unique_lock<std::mutex> * lock)53     void OnFinishLocked(std::unique_lock<std::mutex>* lock) {
54         finished_ = true;
55         lock->unlock();
56         cv_.notify_all();
57     }
58     template <typename R, typename P>
WaitLocked(std::unique_lock<std::mutex> * lock,std::chrono::duration<R,P> duration)59     bool WaitLocked(std::unique_lock<std::mutex>* lock, std::chrono::duration<R, P> duration) {
60         cv_.wait_for(*lock, duration, [this] { return finished_; });
61         return finished_;
62     }
63 
64     bool finished_{false};
65     std::mutex mutex_;
66     std::condition_variable cv_;
67 };
68 
69 }  // namespace android::hardware::health::storage::test
70