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 #define LOG_TAG "media_synchronization_tests"
18 
19 #include <mediautils/Synchronization.h>
20 
21 #include <gtest/gtest.h>
22 #include <utils/Log.h>
23 
24 using namespace android;
25 using namespace android::mediautils;
26 
27 // Simple Test Class
28 template <typename T>
29 class MyObject : public RefBase {
30     T value_;
31   public:
MyObject(const T & value)32     MyObject(const T& value) : value_(value) {}
MyObject(const MyObject<T> & mo)33     MyObject(const MyObject<T>& mo) : value_(mo.get()) {}
get() const34     T get() const { return value_; }
set(const T & value)35     void set(const T& value) { value_ = value; }
36 };
37 
TEST(media_synchronization_tests,atomic_wp)38 TEST(media_synchronization_tests, atomic_wp) {
39   sp<MyObject<int>> refobj = new MyObject<int>(20);
40   atomic_wp<MyObject<int>> wpobj = refobj;
41 
42   // we can promote.
43   ASSERT_EQ(20, wpobj.load().promote()->get());
44 
45   // same underlying object for sp and atomic_wp.
46   ASSERT_EQ(refobj.get(), wpobj.load().promote().get());
47 
48   // behavior is consistent with same underlying object.
49   wpobj.load().promote()->set(10);
50   ASSERT_EQ(10, refobj->get());
51   refobj->set(5);
52   ASSERT_EQ(5, wpobj.load().promote()->get());
53 
54   // we can clear our weak ptr.
55   wpobj = nullptr;
56   ASSERT_EQ(nullptr, wpobj.load().promote());
57 
58   // didn't affect our original obj.
59   ASSERT_NE(nullptr, refobj.get());
60 }
61 
TEST(media_synchronization_tests,atomic_sp)62 TEST(media_synchronization_tests, atomic_sp) {
63   sp<MyObject<int>> refobj = new MyObject<int>(20);
64   atomic_sp<MyObject<int>> spobj = refobj;
65 
66   // same underlying object for sp and atomic_sp.
67   ASSERT_EQ(refobj.get(), spobj.load().get());
68 
69   // behavior is consistent with same underlying object.
70   ASSERT_EQ(20, spobj.load()->get());
71   spobj.load()->set(10);
72   ASSERT_EQ(10, refobj->get());
73   refobj->set(5);
74   ASSERT_EQ(5, spobj.load()->get());
75 
76   // we can clear spobj.
77   spobj = nullptr;
78   ASSERT_EQ(nullptr, spobj.load().get());
79 
80   // didn't affect our original obj.
81   ASSERT_NE(nullptr, refobj.get());
82 }
83