text: /* Copyright 2021 Threadpool Authors. All Rights Reserved.
  
  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.
  ==============================================================================*/
  
  #ifndef ONESHOT_QUEUE_MANAGER_HPP__
  #define ONESHOT_QUEUE_MANAGER_HPP__
  
  #include <atomic>
  #include <ranges>
  
  #include "include/concepts.hpp"
  #include "include/work_queue.hpp"
  
  namespace thp {
  namespace rng = std::ranges;
  
  struct oneshot_manager_queue : task_queue {
  protected:
    struct node {
      std::unique_ptr<task_queue> tasks;
      std::once_flag done;
    };
  
  public:
    oneshot_manager_queue& push(std::unique_ptr<task_queue> r) {
      {
        std::unique_lock l(mu_);
        nodes_.emplace_back(std::make_shared<node>(std::move(r)));
      }
       return *this;
    }
  
    virtual void serve() override {
      std::weak_ptr<node> n{};
      {
        std::shared_lock l(mu_);
        if (!nodes_.empty())
          n = nodes_.front();
      }
      if (auto q = n.lock()) {
        q->tasks->serve();
        std::call_once(q->done, [this] {
          std::unique_lock l(mu_);
          nodes_.pop_front();
        });
      }
    }
  
    virtual bool empty() const {
      std::shared_lock l(mu_);
      return nodes_.empty();
    }
  
    virtual size_t size() const {
      std::shared_lock l(mu_);
      if (!nodes_.empty()) {
        return nodes_.front()->tasks->size();
      }
      return 0u;
    }
  
  protected:
  
    virtual std::unique_ptr<executable> pop() override {
      return {};
    }
  
    mutable std::shared_mutex mu_;
    std::deque<std::shared_ptr<node>> nodes_;
  };
  
  } // namespace thp
  
  #endif // ONESHOT_QUEUE_MANAGER_HPP__
  