/* Copyright (C) 2014 InfiniDB, Inc.

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; version 2 of
   the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
   MA 02110-1301, USA. */

/*******************************************************************************
 * $Id: we_getfilesizes.h 4450 2013-04-15 14:13:24Z chao $
 *
 *******************************************************************************/
#pragma once

#include <unistd.h>
#include <string>

#include "bytestream.h"

#include "atomicops.h"

namespace WriteEngine
{
/** @brief Get all file sizes for the given table
 */
class WE_GetFileSizes
{
 public:
  static int processTable(messageqcpp::ByteStream& bs, std::string& errMsg, int key);
  static int processFileName(messageqcpp::ByteStream& bs, std::string& errMsg, int key);
};

class ActiveThreadCounter
{
 public:
  ActiveThreadCounter(int size) : factiveThreadCount(size)
  {
  }
  virtual ~ActiveThreadCounter()
  {
  }

  void decr()
  {
    int atc;

    for (;;)
    {
      atc = factiveThreadCount.load(std::memory_order_relaxed);

      if (atc <= 0)  // hopefully atc will never be < 0!
        return;

      if (factiveThreadCount.compare_exchange_weak(atc, atc - 1, std::memory_order_relaxed))
        return;

      atomicops::atomicYield();
    }
  }

  uint32_t cur()
  {
    return factiveThreadCount.load(std::memory_order_relaxed);
  }

 private:
  ActiveThreadCounter(const ActiveThreadCounter& rhs);
  ActiveThreadCounter& operator=(const ActiveThreadCounter& rhs);

  std::atomic<int32_t> factiveThreadCount;
};

}  // namespace WriteEngine
