/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2018-Present Couchbase, Inc.
 *
 *   Use of this software is governed by the Business Source License included
 *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified
 *   in that file, in accordance with the Business Source License, use of this
 *   software will be governed by the Apache License, Version 2.0, included in
 *   the file licenses/APL2.txt.
 */
#pragma once

#include "dcp/dcp-types.h"
#include "evp_engine_test.h"
#include "evp_store_single_threaded_test.h"
#include "vbucket_fwd.h"
#include <memcached/engine_error.h>
#include <gsl/gsl>

class Item;
class MockDcpProducer;
class MockActiveStream;
struct DcpMessageProducersIface;

/**
 * Test fixture for unit tests related to DCP.
 */
class DCPTest : public EventuallyPersistentEngineTest {
protected:
    void SetUp() override;

    void TearDown() override;

    // Create a DCP producer; initially with no streams associated.
    void create_dcp_producer(
            int flags = 0,
            IncludeValue includeVal = IncludeValue::Yes,
            IncludeXattrs includeXattrs = IncludeXattrs::Yes,
            std::vector<std::pair<std::string, std::string>> controls = {});

    // Setup a DCP producer and attach a stream and cursor to it.
    void setup_dcp_stream(
            int flags = 0,
            IncludeValue includeVal = IncludeValue::Yes,
            IncludeXattrs includeXattrs = IncludeXattrs::Yes,
            std::vector<std::pair<std::string, std::string>> controls = {});

    cb::engine_errc destroy_dcp_stream();

    struct StreamRequestResult {
        cb::engine_errc status;
        uint64_t rollbackSeqno;
    };

    /**
     * Helper function to simplify calling producer->streamRequest() - provides
     * sensible default values for common invocations.
     */
    static StreamRequestResult doStreamRequest(DcpProducer& producer,
                                               uint64_t startSeqno = 0,
                                               uint64_t endSeqno = ~0,
                                               uint64_t snapStart = 0,
                                               uint64_t snapEnd = ~0,
                                               uint64_t vbUUID = 0);

    /**
     * Helper function to simplify the process of preparing DCP items to be
     * fetched from the stream via step().
     * Should be called once all expected items are present in the vbuckets'
     * checkpoint, it will then run the correct background tasks to
     * copy CheckpointManager items to the producers' readyQ.
     */
    static void prepareCheckpointItemsForStep(
            DcpMessageProducersIface& msgProducers,
            MockDcpProducer& producer,
            VBucket& vb);

    /*
     * Creates an item with the key \"key\", containing json data and xattrs.
     * @return a unique_ptr to a newly created item.
     */
    std::unique_ptr<Item> makeItemWithXattrs();

    /*
     * Creates an item with the key \"key\", containing json data and no xattrs.
     * @return a unique_ptr to a newly created item.
     */
    std::unique_ptr<Item> makeItemWithoutXattrs();

    /* Add items onto the vbucket and wait for the checkpoint to be removed */
    void addItemsAndRemoveCheckpoint(int numItems);

    void removeCheckpoint(int numItems);

    void runCheckpointProcessor(DcpMessageProducersIface& producers);

    std::shared_ptr<MockDcpProducer> producer;
    std::shared_ptr<MockActiveStream> stream;
    VBucketPtr vb0;

    /*
     * Fake callback emulating dcp_add_failover_log
     */
    static cb::engine_errc fakeDcpAddFailoverLog(
            const std::vector<vbucket_failover_t>&) {
        callbackCount++;
        return cb::engine_errc::success;
    }

    // callbackCount needs to be static as its used inside of the static
    // function fakeDcpAddFailoverLog.
    static int callbackCount;
};

class FlowControlTest : public KVBucketTest,
                        public ::testing::WithParamInterface<bool> {
protected:
    void SetUp() override;

    bool flowControlEnabled;
};


/* Copyright 2019-2020 Canaan Inc.
 *
 * 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
#include <gsl/gsl-lite.hpp>
#include <type_traits>

#if defined(_MSC_VER)
#ifdef NNCASE_DLL
#define NNCASE_API __declspec(dllexport)
#elif defined(NNCASE_SHARED_LIBS)
#define NNCASE_API __declspec(dllimport)
#else
#define NNCASE_API
#endif
#else
#define NNCASE_API
#endif

#if defined(_MSC_VER)
#define NNCASE_UNREACHABLE() __assume(0)
#else
#define NNCASE_UNREACHABLE() __builtin_unreachable()
#endif

#if gsl_CPP17_OR_GREATER
#define NNCASE_INLINE_VAR inline
#define NNCASE_UNUSED [[maybe_unused]]
namespace nncase
{
template <class Callable, class... Args>
using invoke_result_t = std::invoke_result_t<Callable, Args...>;
}
#else
#define NNCASE_INLINE_VAR
#if defined(_MSC_VER)
#define NNCASE_UNUSED
#else
#define NNCASE_UNUSED __attribute__((unused))
#endif
namespace nncase
{
template <class Callable, class... Args>
using invoke_result_t = std::result_of_t<Callable(Args...)>;
}
#endif

#define NNCASE_LITTLE_ENDIAN 1

#define NNCASE_HAVE_STD_BYTE gsl_CPP17_OR_GREATER
#define NNCASE_NODISCARD gsl_NODISCARD
#define NNCASE_NORETURN gsl_NORETURN

#define BEGIN_NS_NNCASE_RUNTIME \
    namespace nncase            \
    {                           \
        namespace runtime       \
        {
#define END_NS_NNCASE_RUNTIME \
    }                         \
    }

#define BEGIN_NS_NNCASE_RT_STACKVM \
    namespace nncase               \
    {                              \
        namespace runtime          \
        {                          \
            namespace stackvm      \
            {
#define END_NS_NNCASE_RT_STACKVM \
    }                            \
    }                            \
    }

#define BEGIN_NS_NNCASE_KERNELS \
    namespace nncase            \
    {                           \
        namespace kernels       \
        {

#define END_NS_NNCASE_KERNELS \
    }                         \
    }

#ifndef DEFINE_ENUM_BITMASK_OPERATORS
#define DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE) gsl_DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE)
#endif

namespace nncase
{
struct default_init_t
{
};

NNCASE_INLINE_VAR constexpr default_init_t default_init {};
}


#pragma once

#include <gsl/string_span>

#include <fmt/format.h>

#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <sstream>
#include <cctype>
#include <iosfwd>

// Thanks Stackoverflow...

std::string ucs2_to_local(const std::wstring &);
std::wstring local_to_ucs2(const std::string &);
std::string ucs2_to_utf8(const std::wstring &);
std::wstring utf8_to_ucs2(const std::string &);

// trim from start
inline std::string &ltrim(std::string &s) {
	s.erase(s.begin(), find_if(s.begin(), s.end(), [](auto c) { return !std::isspace(c); }));
	return s;
}

// trim from end
inline std::string &rtrim(std::string &s) {
	s.erase(find_if(s.rbegin(), s.rend(), [](auto c) { return !std::isspace(c); }).base(), s.end());
	return s;
}

// trim from both ends
inline std::string &trim(std::string &s) {
	return ltrim(rtrim(s));
}

inline std::vector<gsl::cstring_span<>>& split(gsl::cstring_span<> s,
	char delim,
	std::vector<gsl::cstring_span<>>& elems,
	bool trimItems = false,
	bool keepEmpty = false) {

	int pos = 0;
	while (pos < s.size()) {
		auto ch = s[pos++];

		// Empty item
		if (ch == delim) {
			if (keepEmpty) {
				elems.push_back({});
			}
			continue;
		}

		if (trimItems && isspace(ch)) {
			// Skip all chars that are considered whitespace
			continue;
		}

		auto start = pos - 1; // Start of item
		size_t count = 1; // Size of item

		// Seek past all of the item's content
		while (pos < s.size()) {
			ch = s[pos++];
			if (ch == delim) {
				break; // reached the end of the item
			}
			count++;
		}

		// Trim whitespace at the end of the string
		if (trimItems) {
			while (count > 0 && isspace(s[start + count - 1])) {
				count--;
			}
		}

		if (count != 0) {
			elems.push_back(s.subspan(start, count));
		} else if (keepEmpty) {
			elems.push_back({});
		}

	}

	return elems;
}

inline std::vector<gsl::cstring_span<>> split(gsl::cstring_span<> s, char delim, bool trim = false, bool keepEmpty = false) {
	std::vector<gsl::cstring_span<>> elems;
	split(s, delim, elems, trim, keepEmpty);
	return elems;
}

inline std::vector<std::string>& split(const std::string& s, char delim, std::vector<std::string>& elems, bool trimItems = false, bool keepEmpty = false) {
	std::stringstream ss(s);
	std::string item;
	while (getline(ss, item, delim)) {
		if (trimItems) {
			item = trim(item);
		}
		if (keepEmpty || !item.empty()) {
			elems.push_back(item);
		}
	}
	return elems;
}

inline std::vector<std::string> split(const std::string& s, char delim, bool trim = false, bool keepEmpty = false) {
	std::vector<std::string> elems;
	split(s, delim, elems, trim, keepEmpty);
	return elems;
}

inline std::string tolower(const std::string &s) {
	auto needsConversion = std::any_of(s.begin(), s.end(), [](char a) {
		return std::tolower(a) != a;
	});
	if (needsConversion) {
		std::string result = s;
		std::transform(result.begin(), result.end(), result.begin(), [](char ch) { return std::tolower((int)ch); });
		return result;
	} else {
		return s;
	}
}

inline std::string tounderscore(const std::string &s) {
	auto needsConversion = std::any_of(s.begin(), s.end(), [](char a) {
		return a == ' ';
	});
	if (needsConversion) {
		std::string result = s;
		std::transform(result.begin(), result.end(), result.begin(), [](char ch){
			if (ch == ' '){
				return '_';
			}
			return ch;
		});
		return result;
	}
	else {
		return s;
	}
}

inline std::string toupper(const std::string &s) {
	auto needsConversion = std::any_of(s.begin(), s.end(), [](char a) {
		return std::toupper(a) != a;
	});
	if (needsConversion) {
		std::string result = s;
		std::transform(result.begin(), result.end(), result.begin(), [](char ch) { return std::toupper((int)ch); });
		return result;
	}
	else {
		return s;
	}
}

// Nice to have operator for serializing vectors in the logger
namespace std {
	template<typename T>
	void format_arg(fmt::BasicFormatter<char> &f, const char *&format_str, const std::vector<T> &v) {
		using namespace std;

		f.writer().write("[");
		for (size_t i = 0; i < v.size(); ++i) {
			f.writer().write("{}", v[i]);
			if (i != v.size() - 1) {
				f.writer().write(", ");
			}
		}
		f.writer().write("]");
	}
}

inline bool endsWith(const std::string &str, const std::string &suffix) {
	if (suffix.length() > str.length()) {
		return false; // Short-circuit
	}

	return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
}


#pragma once

#include <string_view>
#include <gsl/span>
#include <spirv_cross.hpp>

namespace babylon
{
    class ShaderCompiler
    {
    public:
        ShaderCompiler();
        ~ShaderCompiler();

        struct ShaderInfo
        {
            std::unique_ptr<const spirv_cross::Compiler> Compiler;
            gsl::span<uint8_t> Bytes;
        };

        void Compile(std::string_view vertexSource, std::string_view fragmentSource, std::function<void (ShaderInfo, ShaderInfo)> onCompiled);
    };
}


#ifndef VolViz_AtomicCache_h
#define VolViz_AtomicCache_h

#include <gsl/gsl>

#include <atomic>

#pragma clang diagnostic ignored "-Wpadded"

namespace VolViz {

/// Class represening a cached value, that has a very basic thread safety.
/// The thread saftey is as follows: the cache'd value must not be accessed
/// from different threads (at least without external synchronization), but
/// the cache can be marked dirty from any thread.
/// A typical use case is to cache a derived property that depends on some
/// shared (beween threads) resources (e.g. AtomicWrapper<> objects) and the
/// cached value is frequently accessed but the dependent resource does not
/// change so often.
///
/// @tparam T the cached type
template <class T> class AtomicCache {
public:
  /// Creates a dirty cache with the given fetch operation.
  /// @tparam FetchOp the fetch operation. It takes no parameter and returns an
  /// object convertible to T.
  /// @note At construction no fetch operation is issued.
  template <class FetchOp>
  AtomicCache(FetchOp fetchOperation)
      : fetchOperation_(fetchOperation) {
    Expects(fetchOperation_);
    dirtyFlag_.clear();
  }

  /// Marks the cache as dirty, i.e. a fetch operations must be perfomed on the
  /// next read.
  /// @note this method is thread safe.
  inline void markAsDirty() noexcept { dirtyFlag_.clear(); }

  /// Returns the cached object. If the cache is dirty, a fetch operations is
  /// performed first.
  /// @note This method must not be called from more than one thread.
  inline operator T const &() const noexcept {
    if (dirtyFlag_.test_and_set()) return value_;

    Expects(fetchOperation_);
    value_ = std::move(fetchOperation_());
    return value_;
  }

private:
  /// The caced value
  mutable T value_;

  /// The atomic dirty flag
  mutable std::atomic_flag dirtyFlag_;

  /// The fetch operation
  std::function<T()> const fetchOperation_;
};

} // namespace VolViz

#endif // VolViz_AtomicCache_h


//
// Copyright (C) Microsoft Corporation. All rights reserved.
//

#pragma once

#include <intsafe.h>
#include <gsl/gsl>

namespace arcana
{
    void set_thread_name(DWORD threadId, gsl::czstring<> threadName);
}


#pragma once

#include "CesiumGltfReader/Library.h"

#include <CesiumAsync/AsyncSystem.h>
#include <CesiumAsync/Future.h>
#include <CesiumAsync/HttpHeaders.h>
#include <CesiumAsync/IAssetAccessor.h>
#include <CesiumGltf/Model.h>
#include <CesiumJsonReader/ExtensionReaderContext.h>
#include <CesiumJsonReader/IExtensionJsonHandler.h>

#include <gsl/span>

#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <vector>

namespace CesiumGltfReader {

/**
 * @brief The result of reading a glTF model with
 * {@link GltfReader::readModel}.
 */
struct CESIUMGLTFREADER_API ModelReaderResult {
  /**
   * @brief The read model, or std::nullopt if the model could not be read.
   */
  std::optional<CesiumGltf::Model> model;

  /**
   * @brief Errors, if any, that occurred during the load process.
   */
  std::vector<std::string> errors;

  /**
   * @brief Warnings, if any, that occurred during the load process.
   */
  std::vector<std::string> warnings;
};

/**
 * @brief The result of reading an image with
 * {@link GltfReader::readImage}.
 */
struct CESIUMGLTFREADER_API ImageReaderResult {

  /**
   * @brief The {@link ImageCesium} that was read.
   *
   * This will be `std::nullopt` if the image could not be read.
   */
  std::optional<CesiumGltf::ImageCesium> image;

  /**
   * @brief Error messages that occurred while trying to read the image.
   */
  std::vector<std::string> errors;

  /**
   * @brief Warning messages that occurred while reading the image.
   */
  std::vector<std::string> warnings;
};

/**
 * @brief Options for how to read a glTF.
 */
struct CESIUMGLTFREADER_API ReadModelOptions {
  /**
   * @brief Whether data URLs in buffers and images should be automatically
   * decoded as part of the load process.
   */
  bool decodeDataUrls = true;

  /**
   * @brief Whether data URLs should be cleared after they are successfully
   * decoded.
   *
   * This reduces the memory usage of the model.
   */
  bool clearDecodedDataUrls = true;

  /**
   * @brief Whether embedded images in {@link Model::buffers} should be
   * automatically decoded as part of the load process.
   *
   * The {@link ImageSpec::mimeType} property is ignored, and instead the
   * [stb_image](https://github.com/nothings/stb) library is used to decode
   * images in `JPG`, `PNG`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, or `PIC` format.
   */
  bool decodeEmbeddedImages = true;

  /**
   * @brief Whether geometry compressed using the `KHR_draco_mesh_compression`
   * extension should be automatically decoded as part of the load process.
   */
  bool decodeDraco = true;
};

/**
 * @brief Reads glTF models and images.
 */
class CESIUMGLTFREADER_API GltfReader {
public:
  /**
   * @brief Constructs a new instance.
   */
  GltfReader();

  /**
   * @brief Gets the context used to control how extensions are loaded from glTF
   * files.
   */
  CesiumJsonReader::ExtensionReaderContext& getExtensions();

  /**
   * @brief Gets the context used to control how extensions are loaded from glTF
   * files.
   */
  const CesiumJsonReader::ExtensionReaderContext& getExtensions() const;

  /**
   * @brief Reads a glTF or binary glTF (GLB) from a buffer.
   *
   * @param data The buffer from which to read the glTF.
   * @param options Options for how to read the glTF.
   * @return The result of reading the glTF.
   */
  ModelReaderResult readModel(
      const gsl::span<const std::byte>& data,
      const ReadModelOptions& options = ReadModelOptions()) const;

  /**
   * @brief Accepts the result of {@link readModel} and resolves any remaining
   * external buffers and images.
   *
   * @param asyncSystem The async system to use for resolving external data.
   * @param baseUrl The base url that all the external uris are relative to.
   * @param headers The http headers needed to make any external data requests.
   * @param pAssetAccessor The asset accessor to use to request the external
   * buffers and images.
   * @param result The result of the synchronous readModel invocation.
   */
  static CesiumAsync::Future<ModelReaderResult> resolveExternalData(
      CesiumAsync::AsyncSystem asyncSystem,
      const std::string& baseUrl,
      const CesiumAsync::HttpHeaders& headers,
      std::shared_ptr<CesiumAsync::IAssetAccessor> pAssetAccessor,
      ModelReaderResult&& result);

  /**
   * @brief Reads an image from a buffer.
   *
   * The [stb_image](https://github.com/nothings/stb) library is used to decode
   * images in `JPG`, `PNG`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, or `PIC` format.
   *
   * @param data The buffer from which to read the image.
   * @return The result of reading the image.
   */
  static ImageReaderResult readImage(const gsl::span<const std::byte>& data);

private:
  CesiumJsonReader::ExtensionReaderContext _context;
};

} // namespace CesiumGltfReader


#pragma once
#include <string>
#include <ntdll.h>
#include <gsl/span>

namespace pe
{
  class module : public HINSTANCE__
  {
  public:
    module() = delete;
    uintptr_t handle() const;
    template <class T>
    inline auto rva_to(uint32_t rva)
    {
      return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(this) + rva);
    }
    template <class T>
    inline auto rva_to(uint32_t rva) const
    {
      return reinterpret_cast<const T *>(reinterpret_cast<uintptr_t>(this) + rva);
    }
    std::wstring base_name() const;
    std::wstring full_name() const;
    IMAGE_DOS_HEADER *dos_header();
    const IMAGE_DOS_HEADER *dos_header() const;
    IMAGE_NT_HEADERS *nt_header();
    const IMAGE_NT_HEADERS *nt_header() const;
    size_t size() const;
    gsl::span<class segment> segments();
    gsl::span<const class segment> segments() const;
    class segment *segment(const char* namename);
    const class segment *segment(const char* name) const;
    class export_directory *export_directory();
    const class export_directory *export_directory() const;
    void *find_function(const char *name) const;
    void *find_function(uint32_t num) const;
  };
  class module *get_module(const wchar_t *name = nullptr);
  class module *get_module_from_address(void *pc);
  const class module *get_module_from_address(const void *pc);
  class module *instance_module();
}

#include "module.inl"


#ifndef _UI_HELPERS_H_
#define _UI_HELPERS_H_

#define OEMRESOURCE

#include <algorithm>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <vector>

#include <ppl.h>

#include <gsl/gsl>
#include <range/v3/all.hpp>

// Included before windows.h, because pfc.h includes winsock2.h
#include "../pfc/pfc.h"

#include <windows.h>
#include <WindowsX.h>
#include <SHLWAPI.H>
#include <vssym32.h>
#include <uxtheme.h>
#include <shldisp.h>
#include <ShlObj.h>
#include <gdiplus.h>
#include <Usp10.h>
#include <CommonControls.h>
#include <intsafe.h>

#include <wil/resource.h>

#include "../mmh/stdafx.h"

#ifndef RECT_CX
#define RECT_CX(rc) ((rc).right - (rc).left)
#endif

#ifndef RECT_CY
#define RECT_CY(rc) ((rc).bottom - (rc).top)
#endif

#include "literals.h"

#include "handle.h"
#include "win32_helpers.h"
#include "ole.h"

#include "dialog.h"
#include "dpi.h"
#include "container_window.h"
#include "message_hook.h"
#include "trackbar.h"
#include "solid_fill.h"
#include "theming.h"

#include "gdi.h"
#include "text_drawing.h"
#include "list_view/list_view.h"
#include "drag_image.h"
#include "info_box.h"
#include "menu.h"

#include "ole/data_object.h"
#include "ole/enum_format_etc.h"

#endif


#ifndef PROGRESS_BAR_OBSERVER_H_0L8ZR7QT
#define PROGRESS_BAR_OBSERVER_H_0L8ZR7QT

#include "rang.hpp"

#include <atomic>
#include <cmath>
#include <cstdint>
#include <gsl/gsl>
#include <iomanip>
#include <sens_loc/util/console.h>
#include <taskflow/core/observer.hpp>

namespace sens_loc::util {

class progress_bar_observer : public tf::ExecutorObserverInterface {
  public:
    constexpr static int max_bars = 50;

    progress_bar_observer(std::int64_t total_tasks)
        : _total_tasks{total_tasks}
        , _done{0} {
        Expects(total_tasks >= 1);
    }

    progress_bar_observer(const progress_bar_observer&) = delete;
    progress_bar_observer(progress_bar_observer&&)      = delete;
    progress_bar_observer& operator=(const progress_bar_observer&) = delete;
    progress_bar_observer& operator=(progress_bar_observer&&) = delete;
    ~progress_bar_observer() override                         = default;

    void set_up(unsigned /*num_workers*/) override {}
    void on_entry(unsigned /*worker_id*/, tf::TaskView /*task_view*/) override;
    void on_exit(unsigned /*worker_id*/, tf::TaskView /*task_view*/) override;

  private:
    void print_bar(bool increment) noexcept;

    std::int64_t      _total_tasks;
    std::int64_t      _done;
    std::atomic<bool> _inital_output = false;
};
}  // namespace sens_loc::util

#endif /* end of include guard: PROGRESS_BAR_OBSERVER_H_0L8ZR7QT */


#pragma once
#include "icommand.h"
#include "optioninfo.h"
#include "configaccess.h"
#include "config.h"
#include "format.h"
#include "streamreader.h"
#include <gsl/gsl>
#include <cmdlime/errors.h>
#include <cmdlime/customnames.h>
#include <cmdlime/detail/configaccess.h>
#include <cmdlime/detail/flag.h>
#include <sstream>
#include <functional>
#include <memory>

namespace cmdlime::detail{

template <typename TConfig>
class Command : public ICommand{
public:
    enum class Type{
        Normal,
        SubCommand
    };

    Command(const std::string& name,
            std::function<std::optional<TConfig>&()> commandGetter,
            Type type)
        : info_(name, {}, {})
        , commandGetter_(commandGetter)
        , type_(type)
    {
    }

    OptionInfo& info() override
    {
        return info_;
    }

    const OptionInfo& info() const override
    {
        return info_;
    }

private:
    void read(const std::vector<std::string>& commandLine) override
    {
        auto& commandCfg = commandGetter_();
        if (!commandCfg.has_value()){
            commandCfg.emplace();
            if (helpFlag_){
                detail::ConfigAccess<TConfig>(*commandCfg).addFlag(std::move(helpFlag_));
                detail::ConfigAccess<TConfig>(*commandCfg).addHelpFlagToCommands(programName_);
            }
        }
        commandCfg->read(commandLine);
    }

    void enableHelpFlag(const std::string& programName) override
    {
        programName_ = programName + " " + info_.name();
        using NameProvider = typename detail::Format<detail::ConfigAccess<TConfig>::format()>::nameProvider;
        helpFlag_ = std::make_unique<detail::Flag>(NameProvider::name("help"),
                                                   std::string{},
                                                   [this]()->bool&{return helpFlagValue_;},
                                                   detail::Flag::Type::Exit);
        helpFlag_->info().addDescription("show usage info and exit");
    }

    bool isHelpFlagSet() const override
    {
        return helpFlagValue_;
    }

    bool isSubCommand() const override
    {
        return type_ == Type::SubCommand;
    }

    std::string usageInfo() const override
    {
        auto& commandCfg = commandGetter_();
        if (!commandCfg.has_value())
            return {};
        return commandCfg->usageInfo(programName_);
    }

    std::string usageInfoDetailed() const override
    {
        auto& commandCfg = commandGetter_();
        if (!commandCfg.has_value())
            return {};
        return commandCfg->usageInfoDetailed(programName_);
    }

    std::vector<not_null<ICommand*>> commandList() override
    {
        auto& commandCfg = commandGetter_();
        if (!commandCfg.has_value())
            return {};
        return detail::ConfigAccess<TConfig>(*commandCfg).commandList();
    }

private:
    OptionInfo info_;
    std::function<std::optional<TConfig>&()> commandGetter_;
    Type type_;
    std::string programName_;
    std::unique_ptr<IFlag> helpFlag_;
    bool helpFlagValue_ = false;
};

template<typename T, typename TConfig>
class CommandCreator{
    using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider;
public:
    CommandCreator(TConfig& cfg,
                   const std::string& varName,
                   std::function<std::optional<T>&()> commandGetter,
                   typename Command<T>::Type type = Command<T>::Type::Normal)
        : cfg_(cfg)
    {
        static_assert (std::is_base_of_v<Config<ConfigAccess<TConfig>::format()>, T>,
                       "Command's type must be a subclass of Config<FormatType> and have the same format as its parent config.");
        Expects(!varName.empty());
        command_ = std::make_unique<Command<T>>(NameProvider::fullName(varName), commandGetter, type);
    }

    CommandCreator<T, TConfig>& operator<<(const std::string& info)
    {
        command_->info().addDescription(info);
        return *this;
    }

    CommandCreator<T, TConfig>& operator<<(const Name& customName)
    {
        command_->info().resetName(customName.value());
        return *this;
    }

    operator std::optional<T>()
    {
        ConfigAccess<TConfig>{cfg_}.addCommand(std::move(command_));
        return std::optional<T>{};
    }

private:
    std::unique_ptr<Command<T>> command_;
    TConfig& cfg_;
};

template <typename T, typename TConfig>
CommandCreator<T, TConfig> makeCommandCreator(TConfig& cfg,
                                              const std::string& varName,
                                              std::function<std::optional<T>&()> commandGetter,
                                              typename Command<T>::Type type = Command<T>::Type::Normal)
{
    return CommandCreator<T, TConfig>{cfg, varName, commandGetter, type};
}

}


// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#pragma once
#include <windows.h>

// Include ABI composition headers for interop with DCOMP surface handle from MediaEngine
#include <windows.ui.composition.h>
#include <windows.ui.composition.interop.h>

// Include prior to WinRT Headers
#include <wil/cppwinrt.h>

// WinRT Headers
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.ApplicationModel.Core.h>
#include <winrt/Windows.UI.Core.h>
#include <winrt/Windows.UI.Composition.h>
#include <winrt/Windows.UI.Input.h>
#include <winrt/Windows.Media.Protection.h>
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Storage.Streams.h>
#include <winrt/Windows.Web.Http.Headers.h>
#include <winrt/Windows.Data.Xml.Dom.h>
#include <winrt/Windows.Security.Cryptography.h>
#include <winrt/Windows.ApplicationModel.h>

// Direct3D
#include <d3d11.h>

// Windows Implementation Library
#include <wil/com.h>
#include <wil/resource.h>
#include <wil/result_macros.h>

// MediaFoundation headers
#include <mfapi.h>
#include <mferror.h>
#include <mfmediaengine.h>
#include <mfidl.h>
#include <mfcontentdecryptionmodule.h>

// STL headers
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include <tuple>
#include <array>

// GSL (C++ Guidelines Support Library)
#include <gsl/span>


#pragma once

#include <gsl/span>

namespace std {
using gsl::span;
}  // namespace std


/*
 *     Copyright 2021-Present Couchbase, Inc.
 *
 *   Use of this software is governed by the Business Source License included
 *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified
 *   in that file, in accordance with the Business Source License, use of this
 *   software will be governed by the Apache License, Version 2.0, included in
 *   the file licenses/APL2.txt.
 */

#pragma once

#include <mcbp/protocol/status.h>
#include <cstdint>
#include <functional>
#include <gsl/gsl>

struct EngineIface;

/**
 * Callback for any function producing stats.
 *
 * @param key the stat's key
 * @param value the stat's value in an ascii form (e.g. text form of a number)
 * @param cookie magic callback cookie
 */
using AddStatFn = std::function<void(std::string_view key,
                                     std::string_view value,
                                     gsl::not_null<const void*> cookie)>;

/**
 * Callback for adding a response backet
 * @param key The key to put in the response
 * @param extras The data to put in the extended field in the response
 * @param body The data body
 * @param datatype This is currently not used and should be set to 0
 * @param status The status code of the return packet (see in protocol_binary
 *               for the legal values)
 * @param cas The cas to put in the return packet
 * @param cookie The cookie provided by the frontend
 * @return true if return message was successfully created, false if an
 *              error occured that prevented the message from being sent
 */
using AddResponseFn = std::function<bool(std::string_view key,
                                         std::string_view extras,
                                         std::string_view body,
                                         uint8_t datatype,
                                         cb::mcbp::Status status,
                                         uint64_t cas,
                                         const void* cookie)>;


#ifndef CONTROLLERS_IMAGEOPERATIONACTIONCONTROLLER_H
#define CONTROLLERS_IMAGEOPERATIONACTIONCONTROLLER_H

#include <QObject>

#include "s3d/cv/image_operation/image_operation.h"

#include <QAction>

#include <gsl/gsl>

class ImageOperationActionController : public QObject {
  Q_OBJECT

public:
  ImageOperationActionController(gsl::not_null<QAction*> action,
                                 gsl::not_null<s3d::image_operation::ImageOperation*> imageOperation);

  virtual void onActionTriggered() = 0;

signals:
  void imageOperationTriggered();

protected:
  QAction* m_action;
  s3d::image_operation::ImageOperation* m_imageOperation;
};

#endif //CONTROLLERS_IMAGEOPERATIONACTIONCONTROLLER_H


/*
 *  Copyright (C) 2021 FISCO BCOS.
 *  SPDX-License-Identifier: Apache-2.0
 *  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.
 *
 * @brief interface of Table
 * @file Table.h
 * @author: xingqiangbai
 * @date: 2021-04-07
 */
#pragma once

#include "Common.h"
#include "StorageInterface.h"
#include <future>
#include <gsl/span>

namespace bcos
{
namespace storage
{
class Table
{
public:
    Table(StorageInterface* _db, TableInfo::ConstPtr _tableInfo)
      : m_storage(_db), m_tableInfo(std::move(_tableInfo))
    {}

    Table(const Table&) = default;
    Table(Table&&) = default;
    Table& operator=(const Table&) = default;
    Table& operator=(Table&&) = default;
    ~Table() {}

    std::optional<Entry> getRow(std::string_view _key);
    std::vector<std::optional<Entry>> getRows(
        const std::variant<const gsl::span<std::string_view const>,
            const gsl::span<std::string const>>& _keys);
    std::vector<std::string> getPrimaryKeys(const std::optional<const Condition>& _condition);

    void setRow(std::string_view _key, Entry _entry);

    void asyncGetPrimaryKeys(std::optional<const Condition> const& _condition,
        std::function<void(Error::UniquePtr, std::vector<std::string>)> _callback) noexcept;

    void asyncGetRow(std::string_view _key,
        std::function<void(Error::UniquePtr, std::optional<Entry>)> _callback) noexcept;

    void asyncGetRows(const std::variant<const gsl::span<std::string_view const>,
                          const gsl::span<std::string const>>& _keys,
        std::function<void(Error::UniquePtr, std::vector<std::optional<Entry>>)>
            _callback) noexcept;

    void asyncSetRow(
        std::string_view key, Entry entry, std::function<void(Error::UniquePtr)> callback) noexcept;

    TableInfo::ConstPtr tableInfo() const { return m_tableInfo; }
    Entry newEntry() { return Entry(m_tableInfo); }
    Entry newDeletedEntry()
    {
        auto deletedEntry = newEntry();
        deletedEntry.setStatus(Entry::DELETED);
        return deletedEntry;
    }

protected:
    StorageInterface* m_storage;
    TableInfo::ConstPtr m_tableInfo;
};

}  // namespace storage
}  // namespace bcos


/***
 * Copyright 2019 The Katla Authors
 *
 * 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 KATLA_PIPE_H
#define KATLA_PIPE_H

#include "katla/core/core.h"

#include <gsl/span>

#include <optional>

namespace outcome = OUTCOME_V2_NAMESPACE;

namespace katla {

class PosixPipe {
public:
    PosixPipe();
    ~PosixPipe();

    outcome::result<void> open();

    outcome::result<ssize_t> read(gsl::span<std::byte>& buffer);
    outcome::result<ssize_t> write(gsl::span<std::byte>& buffer);

    outcome::result<void> redirectToRead(int fd_src);
    outcome::result<void> redirectToWrite(int fd_src);

    outcome::result<void> close();
    outcome::result<void> closeRead();
    outcome::result<void> closeWrite();
private:
    int _fd[2];
};

}

#endif // KATLA_PIPE_H


#pragma once

#include <memory>
#include <gsl\gsl>
#include "RTTI.h"

namespace Library
{
	class Game;

	class AbstractContentTypeReader : public RTTI
	{
		RTTI_DECLARATIONS(AbstractContentTypeReader, RTTI)

	public:
		AbstractContentTypeReader(const AbstractContentTypeReader&) = default;
		AbstractContentTypeReader& operator=(const AbstractContentTypeReader&) = default;
		AbstractContentTypeReader(AbstractContentTypeReader&&) = default;
		AbstractContentTypeReader& operator=(AbstractContentTypeReader&&) = default;
		virtual ~AbstractContentTypeReader() = default;

		std::uint64_t TargetTypeId() const;
		virtual std::shared_ptr<RTTI> Read(const std::wstring& assetName) = 0;

	protected:
		AbstractContentTypeReader(Game& game, const std::uint64_t targetTypeId);

		gsl::not_null<Game*> mGame;
		const std::uint64_t mTargetTypeId;
	};

	template <typename T>
	class ContentTypeReader : public AbstractContentTypeReader
	{
	public:
		ContentTypeReader(const ContentTypeReader&) = default;
		ContentTypeReader& operator=(const ContentTypeReader&) = default;
		ContentTypeReader(ContentTypeReader&&) = default;
		ContentTypeReader& operator=(ContentTypeReader&&) = default;
		virtual ~ContentTypeReader() = default;

		virtual std::shared_ptr<RTTI> Read(const std::wstring& assetName) override;

	protected:
		ContentTypeReader(Game& game, const std::uint64_t targetTypeId);

		virtual std::shared_ptr<T> _Read(const std::wstring& assetName) = 0;
	};
}

#include "ContentTypeReader.inl"


#ifndef NETWORK_UDP_ASYNCRECEIVER_H
#define NETWORK_UDP_ASYNCRECEIVER_H

/* Base class for implementing an asynchronous UDP receiver. A derived class must implement
   handle_receive which gets passed a view of the received data. The function start() will
   block and should be called in its own thread. */

#include <cstdint>
#include <array>
#include <string>

#include <gsl/gsl>
#include <asio.hpp>

namespace network::udp {

class Async_receiver
{
public:
  Async_receiver() : socket_{io_service_} {}
  virtual ~Async_receiver();
  Async_receiver(const Async_receiver&) = delete;
  Async_receiver& operator=(const Async_receiver&) = delete;

  void start(const std::string& ip, std::uint16_t port);
  void stop();
  bool is_running() const { return socket_.is_open(); }

protected:
  virtual void handle_receive(gsl::span<std::uint8_t> buffer) = 0;

private:
  void start_async_receive();

  asio::io_service io_service_;
  asio::ip::udp::socket socket_;
  std::array<std::uint8_t, 128> buffer_;
};

}  // namespace network::udp

#endif  // NETWORK_UDP_ASYNCRECEIVER_H


#include "ui/detail/ui_helpers_native.h"
#include <gsl/gsl>
struct Tcl_Interp;

namespace cws80 {

class TkUI : public NativeUI {
public:
    std::string choose_file(gsl::span<const FileChooserFilter> filters, const std::string &directory, const std::string &title, FileChooserMode mode) override;
    cxx::optional<std::string> edit_line(const std::string &title, const std::string &initial_value) override;
    uint select_by_menu(gsl::span<const std::string> choices, uint initial_selection) override;

private:
    static Tcl_Interp *create_tk_interp();
    static std::string quote(gsl::cstring_span str);
};

}  // namespace cws80


/* Copyright 2019-2021 Canaan Inc.
 *
 * 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
#include <gsl/gsl-lite.hpp>
#include <type_traits>

#if defined(_MSC_VER)
#ifdef NNCASE_DLL
#define NNCASE_API __declspec(dllexport)
#elif defined(NNCASE_SHARED_LIBS)
#define NNCASE_API __declspec(dllimport)
#else
#define NNCASE_API
#endif
#else
#define NNCASE_API
#endif

#if defined(_MSC_VER)
#define NNCASE_UNREACHABLE() __assume(0)
#else
#define NNCASE_UNREACHABLE() __builtin_unreachable()
#endif

#if gsl_CPP17_OR_GREATER
#define NNCASE_INLINE_VAR inline
#define NNCASE_UNUSED [[maybe_unused]]
namespace nncase
{
template <class Callable, class... Args>
using invoke_result_t = std::invoke_result_t<Callable, Args...>;
}
#else
#define NNCASE_INLINE_VAR
#if defined(_MSC_VER)
#define NNCASE_UNUSED
#else
#define NNCASE_UNUSED __attribute__((unused))
#endif
namespace nncase
{
template <class Callable, class... Args>
using invoke_result_t = std::result_of_t<Callable(Args...)>;
}
#endif

#define NNCASE_LITTLE_ENDIAN 1

#define NNCASE_HAVE_STD_BYTE gsl_CPP17_OR_GREATER
#define NNCASE_NODISCARD gsl_NODISCARD
#define NNCASE_NORETURN gsl_NORETURN

#define BEGIN_NS_NNCASE_RUNTIME \
    namespace nncase            \
    {                           \
        namespace runtime       \
        {
#define END_NS_NNCASE_RUNTIME \
    }                         \
    }

#define BEGIN_NS_NNCASE_RT_MODULE(MODULE) \
    namespace nncase                      \
    {                                     \
        namespace runtime                 \
        {                                 \
            namespace MODULE              \
            {

#define END_NS_NNCASE_RT_MODULE \
    }                           \
    }                           \
    }

#define BEGIN_NS_NNCASE_KERNELS \
    namespace nncase            \
    {                           \
        namespace kernels       \
        {

#define END_NS_NNCASE_KERNELS \
    }                         \
    }

#ifndef DEFINE_ENUM_BITMASK_OPERATORS
#define DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE) gsl_DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE)
#endif

namespace nncase
{
struct default_init_t
{
};

NNCASE_INLINE_VAR constexpr default_init_t default_init {};
}


/*
 *     Copyright 2021-Present Couchbase, Inc.
 *
 *   Use of this software is governed by the Business Source License included
 *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified
 *   in that file, in accordance with the Business Source License, use of this
 *   software will be governed by the Apache License, Version 2.0, included in
 *   the file licenses/APL2.txt.
 */

#pragma once

#include <gsl/gsl-lite.hpp>
#include <nlohmann/json.hpp>

// Used by most unit test files.
#include <folly/portability/GTest.h>

// Used throughout the codebase
#include <folly/SharedMutex.h>
#include <folly/Synchronized.h>

// MB-46844:
// Included by collections/vbucket_manifest.h, which in turn included
// by 50+ other files.
// Consider changing collections/vbucket_manifest.h to use pimpl for
// Manifest::map which would avoid the need to include F14Map.h.
#include <folly/container/F14Map.h>

#include <map>
#include <string>


#pragma once

#include <gsl/gsl>
#include <Metal/Metal.h>

namespace Halley {
	class MetalVideo;

	class MetalBuffer {
	public:
		enum class Type
		{
			Vertex,
			Index,
			Constant
		};

		MetalBuffer(MetalVideo& video, Type type, size_t initialSize = 0);
		MetalBuffer(MetalBuffer&& other) noexcept;
		~MetalBuffer();

		MetalBuffer(const MetalBuffer& other) = delete;

		MetalBuffer& operator=(const MetalBuffer& other) = delete;
		MetalBuffer& operator=(MetalBuffer&& other) = delete;

		void setData(gsl::span<const gsl::byte> data);
		void bindVertex(id<MTLRenderCommandEncoder> encoder, int bindPoint);
		void bindFragment(id<MTLRenderCommandEncoder> encoder, int bindPoint);
		id<MTLBuffer> getBuffer();

	private:
		MetalVideo& video;
		Type type;
		id<MTLBuffer> buffer = nil;
	};
}


#pragma once
#include "Common.h"

#include <stdexcept>
#include <gsl/gsl>

namespace winlogo::utils {

/**
 * This exception is raised when failing to run VirtualProtect.
 */
class VirtualProtectFailedError : public std::runtime_error {
public:
    VirtualProtectFailedError() noexcept;
};

/**
 * This is a RAII class for temporarily changing the protection of a memory region.
 */
class MemoryProtectionGuard {
public:
    MemoryProtectionGuard(void* startAddress, size_t size, DWORD protection);

    NO_COPY(MemoryProtectionGuard);
    NO_MOVE(MemoryProtectionGuard);

    ~MemoryProtectionGuard() noexcept;

private:
    /// The start address of the memory region for which the protection should be changed.
    void* m_startAddress;
    /// The size of the memory region for which the protection should be changed.
    size_t m_size;
    /// The old protection to be restored in the end.
    DWORD m_oldProtection;

    /**
     * Run VirtualProtect for the stored address and store the previous protection in
     * m_oldProtection.
     */
    bool doVirtualProtect(DWORD protection) noexcept;
};

}  // namespace winlogo::utils


#ifndef XYCO_RUNTIME_ASYNC_H_
#define XYCO_RUNTIME_ASYNC_H_

#include <gsl/pointers>

#include "future.h"
#include "poll.h"
#include "runtime.h"

namespace xyco::runtime {
template <typename Return>
class AsyncFuture : public Future<Return> {
 public:
  [[nodiscard]] auto poll(Handle<void> self) -> Poll<Return> override {
    if (!ready_) {
      ready_ = true;
      auto res = RuntimeCtx::get_ctx()->blocking_handle()->Register(event_);
      return Pending();
    }

    gsl::owner<Return *> ret = gsl::owner<Return *>(
        std::get<AsyncFutureExtra>(event_.extra_).after_extra_);
    auto result = std::move(*ret);
    delete ret;

    return Ready<Return>{std::move(result)};
  }

  template <typename Fn>
  explicit AsyncFuture(Fn &&f) requires(std::is_invocable_r_v<Return, Fn>)
      : Future<Return>(nullptr),
        f_([&]() {
          auto extra = AsyncFutureExtra{.after_extra_ = new Return(f())};
          event_.extra_ = extra;
        }),
        ready_(false),
        event_(xyco::runtime::Event{
            .future_ = this, .extra_ = AsyncFutureExtra{.before_extra_ = f_}}) {
  }

  AsyncFuture(const AsyncFuture<Return> &) = delete;

  AsyncFuture(AsyncFuture<Return> &&) = delete;

  auto operator=(const AsyncFuture<Return> &) -> AsyncFuture<Return> & = delete;

  auto operator=(AsyncFuture<Return> &&) -> AsyncFuture<Return> & = delete;

  ~AsyncFuture() = default;

 private:
  bool ready_;
  std::function<void()> f_;
  Event event_;
};
}  // namespace xyco::runtime

#endif  // XYCO_RUNTIME_ASYNC_H_


#pragma once

#include <gsl/string_span.h>

using zstr = gsl::zstring<>;
using czstr = gsl::czstring<>;
using zwstr = gsl::wzstring<>;
using czwstr = gsl::cwzstring<>;


#include <gsl/gsl>

#include <functional>
#include <mutex>
#include <condition_variable>
#include <future>

#include <thread>

namespace lom {

using executor_t = void (*)(std::function<void()>);
auto default_executor_impl = [](std::function<void()> f) {
    std::thread(std::move(f)).detach();
};

extern executor_t g_default_executor;

//
//
/**
 * used to make the library header only. You'll need to add the following in 1 file in an app to use the continuation feature
 * ```
 * #define LOM_FUTURE_IMPLEMENT
 * #include "lom/future.h"
 * ```
 */
#ifdef LOM_FUTURE_IMPLEMENT
executor_t g_default_executor = default_executor_impl;
#endif

template<class TYPE>
class state : public std::enable_shared_from_this<state<TYPE>> {
    union {
        TYPE value_;
        std::exception_ptr exception_;
    };

    enum {
        NONE,
        HAS_VALUE,
        HAS_EXCEPTION,
    } status_{NONE};

    mutable std::mutex mutex_;
    mutable std::condition_variable cv_;
    std::function<void(std::shared_ptr<state>)> continuation_;

public:
    void reset() {
        switch (status_) {
            case NONE:
                break;
            case HAS_VALUE:
                value_.TYPE::~TYPE();
                break;
            case HAS_EXCEPTION:
                exception_.std::exception_ptr::~exception_ptr();
                break;
        }

        status_ = NONE;
    }

    // for make_ready_future
    template<class ...ARGS>
    state(ARGS &&...args) {
        status_ = HAS_VALUE;
        new(&value_) TYPE(std::forward<ARGS>(args)...);
    }

    state() {}

    ~state() {
        reset();
    }

    template<class ...ARGS>
    void set_value(ARGS &&...args) {
        if (status_ != NONE)
            throw std::future_error{std::future_errc::promise_already_satisfied};

        {
            std::lock_guard<std::mutex> lock(mutex_);
            status_ = HAS_VALUE;
            new(&value_) TYPE(std::forward<ARGS>(args)...);
        }
        cv_.notify_one();

        if (continuation_) {
            continuation_(this->shared_from_this());
        }
    }

    void set_exception(std::exception_ptr p) {
        if (status_ != NONE)
            throw std::future_error{std::future_errc::promise_already_satisfied};

        {
            std::lock_guard<std::mutex> lock(mutex_);
            status_ = HAS_EXCEPTION;
            new(&exception_) std::exception_ptr(p);
        }
        cv_.notify_one();

        if (continuation_)
            continuation_(this->shared_from_this());
    }

    TYPE get() {
        std::unique_lock<decltype(mutex_)> lock{mutex_};

        cv_.wait(lock, [this]() {
            return this->status_ != NONE;
        });

        if (status_ == HAS_EXCEPTION)
            std::rethrow_exception(exception_);

        return std::move(value_);
    }

    std::future_status wait() const {
        std::unique_lock<decltype(mutex_)> lock{mutex_};

        cv_.wait(lock, [this]() {
            return this->status_ != NONE;
        });

        return std::future_status::ready;
    }

    template<class Rep, class Period>
    std::future_status wait_for(const std::chrono::duration<Rep, Period> &rel_time) const {
        std::unique_lock<decltype(mutex_)> lock{mutex_};

        bool time_out = cv_.wait_for(lock, rel_time, [this]() {
            return this->status_ != NONE;
        });

        if (time_out)
            return std::future_status::timeout;

        return std::future_status::ready;
    }

    template<class Clock, class Duration>
    std::future_status wait_until(const std::chrono::time_point<Clock, Duration> &abs_time) const {
        std::unique_lock<decltype(mutex_)> lock{mutex_};

        bool time_out = cv_.wait_until(lock, abs_time, [this]() {
            return this->status_ != NONE;
        });

        if (time_out)
            return std::future_status::timeout;

        return std::future_status::ready;
    }

    void then(std::function<void(std::shared_ptr<state>)> &&func) {
        {
            std::lock_guard<std::mutex> lock(mutex_);
            if (status_ == NONE) {
                continuation_ = std::move(func);
                return;
            }
        }

        // don't need to lock cause the value is already set and it will through an exception if you try to set it again
        //
        func(this->shared_from_this());
    }
};

template<class TYPE>
class future;

template<class TYPE, class ...ARGS>
future<TYPE> create_ready_future(ARGS &&... args);

template<class future_t>
class future {
public:
    using type = future_t;

private:
    template<class ...ARGS>
    friend future<future_t> create_ready_future(ARGS &&... args);

    std::shared_ptr<state<future_t>> state_;

private:
    template<typename> struct is_future : std::false_type {};
    template<typename T> struct is_future<future<T>> : std::true_type {};
public:

    template<class ...ARGS>
    future(ARGS &&... args): state_(std::make_shared<future_t>(std::forward<ARGS>(args)...)) {}

    future() {}

    future(const future &) = delete;

    future &operator=(const future &) = default;

    future(future &&p) : state_(std::move(p.state_)) {
        p.state_ = nullptr;
    }

    future &operator=(future &&p) {
        this->state_ = std::move(p.state_);
        p.state_ = nullptr;
    }

    future(std::shared_ptr<state<future_t>> state) : state_(std::move(state)) {}

    future_t get() {
        if (!state_)
            throw std::future_error{std::future_errc::no_state};

        auto rm_state = gsl::finally([this]() {
            this->state_->reset();
            this->state_ = nullptr;
        });

        return state_->get();
    }

    std::future_status wait() {
        if (!state_)
            throw std::future_error{std::future_errc::no_state};

        return state_->wait();
    }

    template<class Rep, class Period>
    std::future_status wait_for(const std::chrono::duration<Rep, Period> &rel_time) const {
        if (!state_)
            throw std::future_error{std::future_errc::no_state};

        return state_->wait_for(rel_time);
    }

    template<class Clock, class Duration>
    std::future_status wait_until(const std::chrono::time_point<Clock, Duration> &abs_time) const {
        if (!state_)
            throw std::future_error{std::future_errc::no_state};

        return state_->wait_until(abs_time);
    }

    bool valid() {
        return state_ != nullptr;
    }

    //function that returns void
    template <class callback_t,
            class return_t = typename std::result_of<callback_t(future_t)>::type,
            typename  = typename std::enable_if<std::is_void<return_t>::value >::type
    >
    void then(callback_t cb_function){
        if (!state_)
            throw std::future_error{std::future_errc::no_state};

        state_->then([cb_function = std::move(cb_function)](std::shared_ptr<state<future_t>> state) mutable {
            g_default_executor([cb_function = std::move(cb_function), state = std::move(state)]() mutable {
                cb_function(future<future_t> {state});
            });
        });
    }

    //function that returns a non future value
    template <class callback_t,
            class inner_return_t = typename std::result_of<callback_t(future_t)>::type,
            class return_t = future<inner_return_t>,
            typename  = typename std::enable_if<!std::is_void<inner_return_t>::value >::type,
            typename  = typename std::enable_if<!is_future<inner_return_t>::value>::type
    >
    return_t then(callback_t cb_function) {
        if (!state_)
            throw std::future_error{std::future_errc::no_state};

        auto ret_state = std::make_shared<state<inner_return_t>>();

        state_->then([cb_function = std::move(cb_function), ret_state](std::shared_ptr<state<future_t>> state) mutable {
            g_default_executor([cb_function = std::move(cb_function), state = std::move(state), ret_state = std::move(ret_state)]() mutable {
                ret_state->set_value(cb_function(future<future_t> {state}));

            });
        });

        return return_t {ret_state};
    }

    // function that returns a lom::future
    template <class callback_t,
            class return_t = typename std::result_of<callback_t(future_t)>::type,
            class inner_return_t = typename return_t::type,
            typename  = typename std::enable_if<is_future<return_t>::value>::type
    >
    return_t then(callback_t cb_function) {
        static_assert(std::is_same<return_t, lom::future<double>>::value, "qwert");
        static_assert(std::is_same<inner_return_t,double>::value, "qewr");

        if (!state_)
            throw std::future_error{std::future_errc::no_state};

        auto ret_state = std::make_shared<state<inner_return_t>>();

        state_->then([cb_function = std::move(cb_function), ret_state](std::shared_ptr<state<future_t>> state) mutable {
            g_default_executor([cb_function = std::move(cb_function), state = std::move(state), ret_state = std::move(ret_state)]() mutable {
                return_t rt = cb_function(future<future_t> {state});
                rt.then([ret_state = std::move(ret_state)](return_t r){
                    ret_state->set_value(r.get());
                });
                //ret_state->set_value

            });
        });

        return return_t {ret_state};
    }
};

template<class TYPE, class ...ARGS>
future<TYPE> create_ready_future(ARGS &&... args) {
    return {std::forward<ARGS>(args)...};
}

template<class TYPE>
class promise {
    std::shared_ptr<state<TYPE>> state_;
    bool has_future = false;

public:
    promise() : state_(std::make_shared<state<TYPE>>()) {}

    promise(const promise &) = delete;

    promise &operator=(const promise &) = delete;

    promise(promise &&p) : state_(std::move(p.state_)) {}

    promise &operator=(promise &&p) noexcept {
        this->state_ = std::move(p.state_);
    }

    future<TYPE> get_future() {
        if(has_future)
            throw std::future_error{std::future_errc::future_already_retrieved};

        has_future = true;

        return {state_};
    }

    template<class ...ARGS>
    void set_value(ARGS &&...args) {
        if (!state_)
            throw std::future_error{std::future_errc::no_state};

        state_->set_value(std::forward<ARGS>(args)...);
    }

    void set_exception(std::exception_ptr p) {
        if (!state_)
            throw std::future_error{std::future_errc::no_state};

        state_->set_exception(std::move(p));
    }

};

/*
template<class future_t>
template<class callback_t, class return_t>
auto future<future_t>::then(callback_t cb_function) -> return_t {
    static_assert(!std::is_same<return_t, void>::value, "is null");

    if (!state_)
        throw std::future_error{std::future_errc::no_state};

    state_->then([cb_function = std::move(cb_function)](std::shared_ptr<state<future_t>> state) mutable {
        g_default_executor([cb_function = std::move(cb_function), state = std::move(state)]() mutable {
            cb_function(future<future_t> {state});
        });
    });
}
*/

}


#pragma once
#include "parser.h"
#include "format.h"
#include "nameutils.h"
#include "utils.h"
#include <sfun/string_utils.h>
#include <cmdlime/errors.h>
#include <gsl/gsl>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <functional>
#include <cassert>

namespace cmdlime::detail{
namespace str = sfun::string_utils;

template <FormatType formatType>
class PosixParser : public Parser<formatType>
{
    using Parser<formatType>::Parser;

    void processCommand(std::string command)
    {
        auto possibleNumberArg = command;
        command = str::after(command, "-");
        if (isParamOrFlag(command)){
            if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands){
                if (!foundParam_.empty())
                    throw ParsingError{"Parameter '-" + foundParam_ + "' value can't be empty"};
                if (argumentEncountered_)
                    throw ParsingError{"Flags and parameters must precede arguments"};
            }
            parseCommand(command);
        }
        else if (isNumber(possibleNumberArg)){
            this->readArg(possibleNumberArg);
            argumentEncountered_ = true;
        }
        else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)
            throw ParsingError{"Encountered unknown parameter or flag '-" + command + "'"};
    }

    void preProcess() override
    {
        checkNames();
        argumentEncountered_ = false;
        foundParam_.clear();
    }

    void process(const std::string& token) override
    {
        if (str::startsWith(token, "-") && token.size() > 1)
           processCommand(token);
        else if (!foundParam_.empty()){
            this->readParam(foundParam_, token);
            foundParam_.clear();
        }
        else{
            this->readArg(token);
            argumentEncountered_ = true;
        }
    }

    void postProcess() override
    {
        if (!foundParam_.empty())
            throw ParsingError{"Parameter '-" + foundParam_ + "' value can't be empty"};
    }

    void parseCommand(const std::string& command)
    {
        if (command.empty())
            throw ParsingError{"Flags and parameters must have a name"};
        auto paramValue = std::string{};
        for(auto ch : command){
            auto opt = std::string{ch};
            if (!foundParam_.empty())
                paramValue += opt;
            else if (this->findFlag(opt))
                this->readFlag(opt);
            else if (this->findParam(opt) || this->findParamList(opt))
                foundParam_ = opt;
            else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)
                throw ParsingError{"Unknown option '" + opt + "' in command '-" + command + "'"};
        }
        if (!foundParam_.empty() && !paramValue.empty()){
            this->readParam(foundParam_, paramValue);
            foundParam_.clear();
        }
    }

    void checkNames()
    {
        auto check = [](const OptionInfo& var, const std::string& varType){
            if (var.name().size() != 1)
                throw ConfigError{varType + "'s name '" + var.name() + "' can't have more than one symbol"};
            if (!std::isalnum(var.name().front()))
                throw ConfigError{varType + "'s name '" + var.name() + "' must be an alphanumeric character"};
        };
        this->forEachParamInfo([check](const OptionInfo& var){
            check(var, "Parameter");
        });
        this->forEachParamListInfo([check](const OptionInfo& var){
            check(var, "Parameter");
        });
        this->forEachFlagInfo([check](const OptionInfo& var){
            check(var, "Flag");
        });
    }

    bool isParamOrFlag(const std::string& str)
    {
        if (str.empty())
            return false;
        auto opt = str.substr(0,1);
        return this->findFlag(opt) ||
               this->findParam(opt) ||
               this->findParamList(opt);
    }

private:
    bool argumentEncountered_ = false;
    std::string foundParam_;
};

class PosixNameProvider{
public:
    static std::string name(const std::string& optionName)
    {
        Expects(!optionName.empty());
        return std::string{static_cast<char>(std::tolower(optionName.front()))};
    }

    static std::string shortName(const std::string& optionName)
    {
        Expects(!optionName.empty());
        return {};
    }

    static std::string fullName(const std::string& optionName)
    {
        Expects(!optionName.empty());
        return toKebabCase(optionName);
    }

    static std::string valueName(const std::string& typeName)
    {
        Expects(!typeName.empty());
        return toCamelCase(templateType(typeNameWithoutNamespace(typeName)));
    }
};

class PosixOutputFormatter{
public:
    static std::string paramUsageName(const IParam& param)
    {
        auto stream = std::stringstream{};
        if (param.isOptional())
            stream << "[" << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">]";
        else
            stream << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">";
        return stream.str();
    }

    static std::string paramListUsageName(const IParamList& param)
    {
        auto stream = std::stringstream{};
        if (param.isOptional())
            stream << "[" << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">...]";
        else
            stream << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">...";
        return stream.str();
    }

    static std::string paramDescriptionName(const IParam& param, int indent = 0)
    {
        auto stream = std::stringstream{};
        stream << std::setw(indent) << paramPrefix()
               << param.info().name() << " <" << param.info().valueName() << ">";
        return stream.str();
    }

    static std::string paramListDescriptionName(const IParamList& param, int indent = 0)
    {
        auto stream = std::stringstream{};
        stream << std::setw(indent) << paramPrefix()
               << param.info().name() << " <" << param.info().valueName() << ">";
        return stream.str();
    }

    static std::string paramPrefix()
    {
        return "-";
    }

    static std::string flagUsageName(const IFlag& flag)
    {
        auto stream = std::stringstream{};
        stream << "[" << flagPrefix() << flag.info().name() << "]";
        return stream.str();
    }

    static std::string flagDescriptionName(const IFlag& flag, int indent = 0)
    {
        auto stream = std::stringstream{};
        stream << std::setw(indent) << flagPrefix() << flag.info().name();
        return stream.str();
    }

    static std::string flagPrefix()
    {
        return "-";
    }

    static std::string argUsageName(const IArg& arg)
    {
        auto stream = std::stringstream{};
        stream << "<" << arg.info().name() << ">";
        return stream.str();
    }

    static std::string argDescriptionName(const IArg& arg, int indent = 0)
    {
        auto stream = std::stringstream{};
        if (indent)
            stream << std::setw(indent) << " ";
        stream << "<" << arg.info().name() << "> (" << arg.info().valueName() << ")";
        return stream.str();
    }

    static std::string argListUsageName(const IArgList& argList)
    {
        auto stream = std::stringstream{};
        if (argList.isOptional())
            stream << "[" << argList.info().name() << "...]";
        else
            stream << "<" << argList.info().name() << "...>";
        return stream.str();
    }

    static std::string argListDescriptionName(const IArgList& argList, int indent = 0)
    {
        auto stream = std::stringstream{};
        if (indent)
            stream << std::setw(indent) << " ";
        stream << "<" << argList.info().name() << "> (" << argList.info().valueName() << ")";
        return stream.str();
    }

};

template<>
struct Format<FormatType::POSIX>
{
    using parser = PosixParser<FormatType::POSIX>;
    using nameProvider = PosixNameProvider;
    using outputFormatter = PosixOutputFormatter;
    static constexpr bool shortNamesEnabled = false;
};

}


// MIT License Copyright (c) 2020 Jarrett Wendt

#pragma once

#include <gsl/gsl>

#include "Macros.h"
#include "SharedPtr.h"
#include "Entity.h"

namespace Library
{
	class Engine final
	{
		friend Entity;

		/** the parentmost Entity */
		static inline SharedPtr<Entity> world{ nullptr };

		static inline std::string programName{};
		static inline std::string pythonSourceDirectory{};
		static inline const std::string initFileName{ "init.py" };
		static inline const std::string shutdownFileName{ "del.py" };

		static inline FILE* initFilePtr{ nullptr };

	public:
		STATIC_CLASS(Engine)
		using Args = gsl::span<const char*>;

		/**
		 * O(1)
		 *
		 * @returns		the parentmost Entity
		 */
		static Entity& World() noexcept;

		/**
		 * to be called by WinMain()
		 */
		static void Main(const Args& args);

		/**
		 * setting this to false will terminate the simulation
		 *
		 * @returns		whether or not the simulation is active
		 */
		static bool& IsActive() noexcept;

		/**
		 * runs before the first Update()
		 */
		static void Init();

		/**
		 * the main engine loop
		 */
		static void Update();

		/**
		 * runs after the last Update()
		 */
		static void Terminate();

	private:
		/**
		 * wraps all of the logic for parsing the command line args.
		 */
		static void ParseArgs(const Args& args);

		/**
		 * Invoked by WinMain's WndProc.
		 *
		 * @param hWnd		HWND
		 * @param uMsg		UINT
		 * @param wParam	WPARAM
		 * @param lParam	LPARAM
		 */
#ifdef _WIN64
		static long long __stdcall WndProc(void* hWnd, unsigned int uMsg, unsigned long long wParam, long long lParam);
#else
		static long __stdcall WndProc(void* hWnd, unsigned int uMsg, unsigned wParam, long lParam);
#endif
	};
}


/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2018 Couchbase, Inc.
 *
 *   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

#include <nlohmann/json_fwd.hpp>
#include <gsl/gsl>
#include <list>
#include <string>

class Module;
class Event;

/**
 * Is this build for enterprise edition?
 *
 * @return true when building EE, false for CE
 */
bool is_enterprise_edition();

/**
 * In order to allow making unit tests we want to be able to mock the
 * enterprise edition settings dynamically
 */
void set_enterprise_edition(bool enable);

/**
 * Load the requested file and parse it as JSON
 *
 * @param fname the name of the file
 * @return the json representation of the file
 * @throws std::system_error if we fail to read the file
 *         std::runtime_error if we fail to parse the content of the file
 */
nlohmann::json load_file(const std::string& fname);

/**
 * Iterate over the module descriptor json and populate each entry
 * in the modules array into the provided modules list.
 *
 * @param ptr The JSON representation of the module description. See
 *            ../README.md for a description of the syntax
 * @param modules Where to store the list of all of the entries found
 * @param srcroot The source root to prepend to all of the paths in the spec
 * @param objroot The object root to prepend to all of the paths in the spec
 * @throws std::invalid_argument if the provided JSON is of an unexpected format
 */
void parse_module_descriptors(const nlohmann::json&,
                              std::list<std::unique_ptr<Module>>& modules,
                              const std::string& srcroot,
                              const std::string& objroot);

/**
 * Build the master event file
 *
 * @param modules The modules to include
 * @param output_file Where to store the result
 * @throws std::system_error if we fail to write the file
 */
void create_master_file(const std::list<std::unique_ptr<Module>>& modules,
                        const std::string& output_file);


#ifndef ADD_TO_CONFIG_INCLUDE
#define ADD_TO_CONFIG_INCLUDE

#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

#include <gsl/pointers>

#include "config/variablesMap.h"

#include "base-utils/nonEmptyString.h"

namespace execHelper::test {
inline void
addToConfig(const execHelper::config::SettingsKeys& key,
            const std::string& value,
            gsl::not_null<execHelper::config::VariablesMap*> config) {
    if(!config->add(key, value)) {
        throw std::runtime_error("Failed to add key " + key.back() +
                                 " with value '" + value + "' to config");
    }
}

inline void
addToConfig(const execHelper::config::SettingsKeys& key,
            const NonEmptyString& value,
            gsl::not_null<execHelper::config::VariablesMap*> config) {
    if(!config->add(key, *value)) {
        throw std::runtime_error("Failed to add key " + key.back() +
                                 " with value '" + *value + "' to config");
    }
}

template <typename T>
inline void
addToConfig(const execHelper::config::SettingsKeys& key,
            const std::vector<T>& value,
            gsl::not_null<execHelper::config::VariablesMap*> config) {
    if(!config->add(key, value)) {
        throw std::runtime_error("Failed to add key " + key.back() +
                                 " with first value '" + value.front() +
                                 "' to config");
    }
}

inline void
addToConfig(const execHelper::config::SettingsKeys& key, bool value,
            gsl::not_null<execHelper::config::VariablesMap*> config) {
    if(value) {
        if(!config->add(key, "yes")) {
            throw std::runtime_error("Failed to add key " + key.back() +
                                     " with value 'true' to config");
        }
    }
    if(!config->add(key, "no")) {
        throw std::runtime_error("Failed to add key " + key.back() +
                                 " with value 'false' to config");
    }
}

inline void
addToConfig(execHelper::config::SettingsKeys key,
            const std::pair<std::string, std::string>& value,
            gsl::not_null<execHelper::config::VariablesMap*> config) {
    key.push_back(value.first);
    if(!config->add(key, value.second)) {
        throw std::runtime_error("Failed to add key " + value.first +
                                 " with first value '" + value.second +
                                 "' to config");
    }
}

template <typename T>
inline void
addToConfig(const execHelper::config::SettingsKeys& key,
            const std::optional<T>& value,
            gsl::not_null<execHelper::config::VariablesMap*> config) {
    if(value) {
        addToConfig(key, *value, config);
    }
}

template <typename T>
inline void
addToConfig(const execHelper::config::SettingsKey& key, const T& value,
            gsl::not_null<execHelper::config::VariablesMap*> config) {
    addToConfig(execHelper::config::SettingsKeys({key}), value, config);
}
} // namespace execHelper::test

#endif /* ADD_TO_CONFIG_INCLUDE */


#pragma once
#include "nkw_common.h"
#include "utility/types.h"
#include <gsl/gsl>

namespace cws80 {

class NativeUI;

//
bool im_select(nk_context *ctx, NativeUI &nat,
               gsl::span<const std::string> choices, uint *value);

}  // namespace cws80


#pragma once

#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include <gsl/gsl>
#include "RTTI.h"

namespace Library
{
	class Shader : public RTTI
	{
		RTTI_DECLARATIONS(Shader, RTTI)

	public:
		Shader(const Shader&) = default;
		Shader& operator=(const Shader&) = default;
		Shader(Shader&&) = default;
		Shader& operator=(Shader&&) = default;
		virtual ~Shader() = default;

		static winrt::com_ptr<ID3D11ClassLinkage> CreateClassLinkage(gsl::not_null<ID3D11Device*> device);

	protected:
		Shader() = default;
	};
}


#ifndef CONTROLLERS_UPDATERECTIFICATIONCONTROLLER_H
#define CONTROLLERS_UPDATERECTIFICATIONCONTROLLER_H

#include "imageoperationactioncontroller.h"

#include "s3d/cv/image_operation/image_operation.h"

#include <QAction>

#include <gsl/gsl>

class ImageOperationTriggerController : public ImageOperationActionController {
Q_OBJECT

public:
  ImageOperationTriggerController(gsl::not_null<QAction*> action,
                                  gsl::not_null<s3d::image_operation::ImageOperation*> imageOperation);

  void onActionTriggered() override;
};

#endif //CONTROLLERS_UPDATERECTIFICATIONCONTROLLER_H


#pragma once
//=============================================================================
// EXTERNAL DECLARATIONS
//=============================================================================
#include "Core/Game/IManagerComponent.h"
#include "Core/Game/IManager.h"
#include "Core/Game/IGameEngine.h"
#include "Core/Components/ComponentBase.h"
#include <gsl/span>

namespace engine {

//=============================================================================
// CLASS GameManager
//=============================================================================
template<class TDerived>
class GameManager
	: virtual public IManagerComponent
	, virtual public IManager
{
public:
	virtual void onAttached(const GameEngineRef &iGameEngine) override {}
	virtual void onDetached(const GameEngineRef &iGameEngine) override {}

	virtual gsl::span<IdType> interfaces() override
	{
		return TDerived::Interfaces;
	}
};
} // namespace engine


#ifndef COMMAND_UTILS_INCLUDE
#define COMMAND_UTILS_INCLUDE

#include <limits>
#include <string>
#include <vector>

#include <gsl/string_span>

#include "tmpFile.h"

namespace execHelper {
namespace test {
namespace baseUtils {
using ConfigFile = TmpFile;

const gsl::czstring<> EXEC_HELPER_BINARY = "exec-helper";
const gsl::czstring<> COMMAND_KEY = "commands";
const gsl::czstring<> COMMAND_LINE_COMMAND_KEY = "command-line-command";
const gsl::czstring<> COMMAND_LINE_COMMAND_LINE_KEY = "command-line";

using ReturnCode = int32_t;
static const ReturnCode SUCCESS = EXIT_SUCCESS;
static const ReturnCode RUNTIME_ERROR = std::numeric_limits<ReturnCode>::max();
} // namespace baseUtils
} // namespace test
} // namespace execHelper

#endif /* COMMAND_UTILS_INCLUDE */


/***
 * Copyright 2019 The Katla Authors
 *
 * 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 KATLA_POSIX_FILE_H
#define KATLA_POSIX_FILE_H

#include "katla/core/core.h"

#include <optional>
#include <gsl/span>

#include <fcntl.h>

namespace katla {

    class PosixFile {
    public:
        enum class OpenFlags : int {
            ReadOnly    = O_RDONLY,
            WriteOnly   = O_WRONLY,
            ReadWrite   = O_RDWR,
            Create      = O_CREAT,
            Exclusive   = O_EXCL,
            Truncate    = O_TRUNC,
            Append      = O_APPEND,
            NonBlocking = O_NONBLOCK,
            Sync        = O_SYNC,
            Async       = O_ASYNC,

#if defined(O_TMPFILE)
            TmpFile     = O_TMPFILE
#endif
        };

        PosixFile();
        ~PosixFile();

        outcome::result<void> create(std::string_view filePath, OpenFlags flags);
        outcome::result<void> open(std::string_view filePath, OpenFlags flags);
        outcome::result<void> close();

        outcome::result<ssize_t> read(gsl::span<std::byte> &buffer);
        outcome::result<ssize_t> write(gsl::span<std::byte> &buffer);

        static outcome::result<std::string> absolutePath(std::string path);

        outcome::result<size_t> size();

    private:
        int m_fd;
    };

    inline PosixFile::OpenFlags operator|(PosixFile::OpenFlags lhs, PosixFile::OpenFlags rhs) {
        using T = std::underlying_type_t<PosixFile::OpenFlags>;
        return static_cast<PosixFile::OpenFlags>(static_cast<T>(lhs) | static_cast<T>(rhs));
    }

    inline PosixFile::OpenFlags &operator|=(PosixFile::OpenFlags &lhs, PosixFile::OpenFlags rhs) {
        lhs = lhs | rhs;
        return lhs;
    }

}

#endif // KATLA_POSIX_FILE_H


#ifndef STDAFX__H
#define STDAFX__H

#if defined(_WIN32)

#include <SDKDDKVer.h>

#if !defined(_STL_EXTRA_DISABLED_WARNINGS)
#define _STL_EXTRA_DISABLED_WARNINGS 4061 4324 4365 4514 4571 4582 4583 4623 4625 4626 4710 4774 4800 4820 4987 5026 5027 5039
#endif

#if !defined(_SCL_SECURE_NO_WARNINGS)
#define _SCL_SECURE_NO_WARNINGS 1
#endif

#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS 1
#endif

#if !defined(_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING)
#define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING 1
#endif

#if !defined(_SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING)
#define _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING 1
#endif

#if !defined(_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING)
#define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING 1
#endif

#define STRICT
#define NOMINMAX

#pragma warning(disable: 4571) // warning C4571: Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught
#pragma warning(disable: 4668) // warning C4668: '%s' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'
#pragma warning(disable: 4710) // warning C4710: '%s': function not inlined
#pragma warning(disable: 4711) // warning C4711: function '%s' selected for automatic inline expansion
#pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s'
#pragma warning(disable: 5045) // warning C5045: Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified

#include <Windows.h>

#pragma warning(push)
#pragma warning(disable: 4005) // warning C4005: '%s': macro redefinition
#include <Winternl.h>
#include <ntstatus.h>
#pragma warning(pop)

#else // defined(_WIN32)

#include <cpuid.h>

#endif

#if defined(_MSC_VER)

// currently broken (triggers on iterators and other objects that are usually unnamed)
#pragma warning(disable: 26444) // warning C26444: Avoid unnamed objects with custom construction and destruction (es.84: http://go.microsoft.com/fwlink/?linkid=862923).

// disable for everything
#pragma warning(disable: 4061) // warning C4061: enumerator '%s' in switch of enum '%s' is not explicitly handled by a case label
#pragma warning(disable: 4324) // warning C4234: structure was padded due to alignment specifier
#pragma warning(disable: 4514) // warning C4514: '%s': unreferenced inline function has been removed
#pragma warning(disable: 4623) // warning C4623: '%s': default constructor was implicitly defined as deleted
#pragma warning(disable: 4625) // warning C4625: '%s': copy constructor was implicitly defined as deleted
#pragma warning(disable: 4626) // warning C4626: '%s': assignment operator was implicitly defined as deleted
#pragma warning(disable: 4710) // warning C4710: '%s': function not inlined
#pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s'
#pragma warning(disable: 5026) // warning C5026: '%s': move constructor was implicitly defined as deleted
#pragma warning(disable: 5027) // warning C5027: '%s': move assignment operator was implicitly defined as deleted

#pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'no initialization'.
#pragma warning(disable: 26426) // warning C26426: Global initializer calls a non-constexpr function '%s' (i.22: http://go.microsoft.com/fwlink/?linkid=853919).
#pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413)
#pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414).
#pragma warning(disable: 26485) // warning C26485: Expression '%s::`vbtable'': No array to pointer decay. (bounds.3: http://go.microsoft.com/fwlink/p/?LinkID=620415)
#pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417)
#pragma warning(disable: 26499) // warning C26499: Could not find any lifetime tracking information for '%s'

// disable for standard headers
#pragma warning(push)
#pragma warning(disable: 26400) // warning C26400: Do not assign the result of an allocation or a function call with an owner<T> return value to a raw pointer, use owner<T> instead. (i.11 http://go.microsoft.com/fwlink/?linkid=845474)
#pragma warning(disable: 26401) // warning C26401: Do not delete a raw pointer that is not an owner<T>. (i.11: http://go.microsoft.com/fwlink/?linkid=845474)
#pragma warning(disable: 26408) // warning C26408: Avoid malloc() and free(), prefer the nothrow version of new with delete. (r.10 http://go.microsoft.com/fwlink/?linkid=845483)
#pragma warning(disable: 26409) // warning C26409: Avoid calling new and delete explicitly, use std::make_unique<T> instead. (r.11 http://go.microsoft.com/fwlink/?linkid=845485)
#pragma warning(disable: 26411) // warning C26411: The parameter '%s' is a reference to unique pointer and it is never reassigned or reset, use T* or T& instead. (r.33 http://go.microsoft.com/fwlink/?linkid=845479)
#pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'end of function scope (local lifetimes end)'.
#pragma warning(disable: 26413) // warning C26413: Do not dereference nullptr (lifetimes rule 2). 'nullptr' was pointed to nullptr at line %d.
#pragma warning(disable: 26423) // warning C26423: The allocation was not directly assigned to an owner.
#pragma warning(disable: 26424) // warning C26424: Failing to delete or assign ownership of allocation at line %d.
#pragma warning(disable: 26425) // warning C26425: Assigning '%s' to a static variable.
#pragma warning(disable: 26444) // warning C26444: Avoid unnamed objects with custom construction and destruction (es.84: http://go.microsoft.com/fwlink/?linkid=862923).
#pragma warning(disable: 26461) // warning C26461: The reference argument '%s' for function %s can be marked as const. (con.3: https://go.microsoft.com/fwlink/p/?LinkID=786684)
#pragma warning(disable: 26471) // warning C26471: Don't use reinterpret_cast. A cast from void* can use static_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417).
#pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413)
#pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions. (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414)
#pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417)
#pragma warning(disable: 26493) // warning C26493: Don't use C-style casts that would perform a static_cast downcast, const_cast, or reinterpret_cast. (type.4: http://go.microsoft.com/fwlink/p/?LinkID=620420)
#pragma warning(disable: 26494) // warning C26494: Variable '%s' is uninitialized. Always initialize an object. (type.5: http://go.microsoft.com/fwlink/p/?LinkID=620421)
#pragma warning(disable: 26495) // warning C26495: Variable '%s' is uninitialized. Always initialize a member variable. (type.6: http://go.microsoft.com/fwlink/p/?LinkID=620422)
#pragma warning(disable: 26496) // warning C26496: Variable '%s' is assigned only once, mark it as const. (con.4: https://go.microsoft.com/fwlink/p/?LinkID=784969)
#pragma warning(disable: 26497) // warning C26497: This function %s could be marked constexpr if compile-time evaluation is desired. (f.4: https://go.microsoft.com/fwlink/p/?LinkID=784970)

#else

// linux warnings go here

#endif

#include <cstddef>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <type_traits>
#include <utility>
#include <memory>
#include <tuple>
#include <thread>
#include <cstdlib>
#include <codecvt>

#if defined(_MSC_VER)

// disable additionally for third-party libraries
#pragma warning(push)
#pragma warning(disable: 4456) // warning C4456: declaration of '%s' hides previous local declaration
#pragma warning(disable: 4458) // warning C4458: declaration of '%s' hides class member
#pragma warning(disable: 4459) // warning C4459: declaration of '%s' hides global declaration
#pragma warning(disable: 4702) // warning C4702: unreacha3eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeble code

#include <CppCoreCheck\Warnings.h>
#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)

#endif

#ifndef BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE
#define BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE
#endif

#include <boost/algorithm/string.hpp>
#include <boost/xpressive/xpressive.hpp>

#include <gsl/gsl>

#include <fmt/format.h>

#if defined(_MSC_VER)

#pragma warning(pop)
#pragma warning(pop)

#else

// linux warning restoration goes here

#endif

#endif


/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2018 Couchbase, Inc.
 *
 *   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

#include "engine_error.h"
#include "types.h"

#include <gsl/gsl>

namespace cb {
namespace audit {
namespace document {
enum class Operation;
}
} // namespace audit
} // namespace cb

struct ServerDocumentIface {
    virtual ~ServerDocumentIface() = default;

    /**
     * This callback is called from the underlying engine right before
     * it is linked into the list of available documents (it is currently
     * not visible to anyone). The engine should have validated all
     * properties set in the document by the client and the core, and
     * assigned a new CAS number for the document (and sequence number if
     * the underlying engine use those).
     *
     * The callback may at this time do post processing of the document
     * content (it is allowed to modify the content data, but not
     * reallocate or change the size of the data in any way).
     *
     * Given that the engine MAY HOLD LOCKS when calling this function
     * the core is *NOT* allowed to acquire *ANY* locks (except for doing
     * some sort of memory allocation for a temporary buffer).
     *
     * @param cookie The cookie provided to the engine for the storage
     *               command which may (which may hold more context)
     * @param info the items underlying data
     * @return ENGINE_SUCCESS means that the underlying engine should
     *                        proceed to link the item. All other
     *                        error codes means that the engine should
     *                        *NOT* link the item
     */
    virtual ENGINE_ERROR_CODE pre_link(gsl::not_null<const void*> cookie,
                                       item_info& info) = 0;

    /**
     * This callback is called from the underlying engine right before
     * a particular document expires. The callback is responsible examining
     * the value and possibly returning a new and modified value.
     *
     * @param itm_info info pertaining to the item that is to be expired.
     * @return std::string empty if the value required no modification, not
     *         empty then the string contains the modified value. When not empty
     *         the datatype of the new value is datatype xattr only.
     *
     * @throws std::bad_alloc in case of memory allocation failure
     */
    virtual std::string pre_expiry(const item_info& itm_info) = 0;

    /**
     * Add an entry to the audit trail for access to the document specified
     * in the key for this cookie.
     *
     * @param cookie The cookie representing the operation
     * @param operation The type of access for the operation
     */
    virtual void audit_document_access(
            gsl::not_null<const void*> cookie,
            cb::audit::document::Operation operation) = 0;
};