blob: bd0462b3b62f7399712d9c7880ff36ce61bd68a3 [file] [log] [blame]
Dominik Laskowski04534e22022-10-10 10:55:40 -04001/*
2 * Copyright 2022 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#include <ftl/non_null.h>
18#include <gtest/gtest.h>
19
20#include <memory>
21#include <string>
22#include <string_view>
23
24namespace android::test {
25namespace {
26
27void get_length(const ftl::NonNull<std::shared_ptr<std::string>>& string_ptr,
28 ftl::NonNull<std::size_t*> length_ptr) {
29 // No need for `nullptr` checks.
30 *length_ptr = string_ptr->length();
31}
32
33using Pair = std::pair<ftl::NonNull<std::shared_ptr<int>>, std::shared_ptr<int>>;
34
35Pair dupe_if(ftl::NonNull<std::unique_ptr<int>> non_null_ptr, bool condition) {
36 // Move the underlying pointer out, so `non_null_ptr` must not be accessed after this point.
37 auto unique_ptr = std::move(non_null_ptr).take();
38
39 auto non_null_shared_ptr = ftl::as_non_null(std::shared_ptr<int>(std::move(unique_ptr)));
40 auto nullable_shared_ptr = condition ? non_null_shared_ptr.get() : nullptr;
41
42 return {std::move(non_null_shared_ptr), std::move(nullable_shared_ptr)};
43}
44
45} // namespace
46
47// Keep in sync with example usage in header file.
48TEST(NonNull, Example) {
49 const auto string_ptr = ftl::as_non_null(std::make_shared<std::string>("android"));
50 std::size_t size;
51 get_length(string_ptr, ftl::as_non_null(&size));
52 EXPECT_EQ(size, 7u);
53
54 auto ptr = ftl::as_non_null(std::make_unique<int>(42));
55 const auto [ptr1, ptr2] = dupe_if(std::move(ptr), true);
56 EXPECT_EQ(ptr1.get(), ptr2);
57}
58
59namespace {
60
61constexpr std::string_view kApple = "apple";
62constexpr std::string_view kOrange = "orange";
63
64using StringViewPtr = ftl::NonNull<const std::string_view*>;
65constexpr StringViewPtr kApplePtr = ftl::as_non_null(&kApple);
66constexpr StringViewPtr kOrangePtr = ftl::as_non_null(&kOrange);
67
68constexpr StringViewPtr longest(StringViewPtr ptr1, StringViewPtr ptr2) {
69 return ptr1->length() > ptr2->length() ? ptr1 : ptr2;
70}
71
72static_assert(longest(kApplePtr, kOrangePtr) == kOrangePtr);
73
74} // namespace
75} // namespace android::test