blob: e4dc1fedb11c9e32a0cea1a60e50489a7b23e5f4 [file] [log] [blame]
Dominik Laskowski8e89c2a2020-04-27 16:08:19 -07001/*
2 * Copyright 2020 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 <algorithm>
18#include <future>
19#include <string>
20#include <thread>
21#include <vector>
22
23#include <gtest/gtest.h>
24
25#include "Promise.h"
26
27namespace android {
28namespace {
29
30using Bytes = std::vector<uint8_t>;
31
32Bytes decrement(Bytes bytes) {
33 std::transform(bytes.begin(), bytes.end(), bytes.begin(), [](auto b) { return b - 1; });
34 return bytes;
35}
36
37} // namespace
38
39TEST(PromiseTest, yield) {
40 EXPECT_EQ(42, promise::yield(42).get());
41
42 auto ptr = std::make_unique<char>('!');
43 auto future = promise::yield(std::move(ptr));
44 EXPECT_EQ('!', *future.get());
45}
46
47TEST(PromiseTest, chain) {
48 std::packaged_task<const char*()> fetchString([] { return "ifmmp-"; });
49
50 std::packaged_task<Bytes(std::string)> appendString([](std::string str) {
51 str += "!xpsme";
52 return Bytes{str.begin(), str.end()};
53 });
54
55 std::packaged_task<std::future<Bytes>(Bytes)> decrementBytes(
56 [](Bytes bytes) { return promise::defer(decrement, std::move(bytes)); });
57
58 auto fetch = fetchString.get_future();
59 std::thread fetchThread(std::move(fetchString));
60
61 std::thread appendThread, decrementThread;
62
63 EXPECT_EQ("hello, world",
64 promise::chain(std::move(fetch))
65 .then([](const char* str) { return std::string(str); })
66 .then([&](std::string str) {
67 auto append = appendString.get_future();
68 appendThread = std::thread(std::move(appendString), std::move(str));
69 return append;
70 })
71 .then([&](Bytes bytes) {
72 auto decrement = decrementBytes.get_future();
73 decrementThread = std::thread(std::move(decrementBytes),
74 std::move(bytes));
75 return decrement;
76 })
77 .then([](std::future<Bytes> bytes) { return bytes; })
78 .then([](const Bytes& bytes) {
79 return std::string(bytes.begin(), bytes.end());
80 })
81 .get());
82
83 fetchThread.join();
84 appendThread.join();
85 decrementThread.join();
86}
87
88} // namespace android