/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once namespace folly { template size_t SharedPromise::size() const { std::lock_guard g(mutex_); return size_.value; } template SemiFuture SharedPromise::getSemiFuture() const { std::lock_guard g(mutex_); size_.value++; if (hasResult()) { return makeFuture(Try(try_.value)); } else { promises_.emplace_back(); if (interruptHandler_) { promises_.back().setInterruptHandler(interruptHandler_); } return promises_.back().getSemiFuture(); } } template Future SharedPromise::getFuture() const { return getSemiFuture().via(&InlineExecutor::instance()); } template template typename std::enable_if::value>::type SharedPromise::setException(E const& e) { setTry(Try(e)); } template void SharedPromise::setException(exception_wrapper ew) { setTry(Try(std::move(ew))); } template void SharedPromise::setInterruptHandler( std::function fn) { std::lock_guard g(mutex_); if (hasResult()) { return; } interruptHandler_ = fn; for (auto& p : promises_) { p.setInterruptHandler(fn); } } template template void SharedPromise::setValue(M&& v) { setTry(Try(std::forward(v))); } template template void SharedPromise::setWith(F&& func) { setTry(makeTryWith(std::forward(func))); } template void SharedPromise::setTry(Try&& t) { std::vector> promises; { std::lock_guard g(mutex_); if (hasResult()) { throw_exception(); } try_.value = std::move(t); promises.swap(promises_); } for (auto& p : promises) { p.setTry(Try(try_.value)); } } template bool SharedPromise::isFulfilled() const { std::lock_guard g(mutex_); return hasResult(); } } // namespace folly