Skip to content

Commit

Permalink
Add utilities (#8)
Browse files Browse the repository at this point in the history
* algorithms

* scope exit

* tests

* oh yeah, 'unordered' map

* move curly
  • Loading branch information
McCallisterRomer authored Feb 27, 2023
1 parent f30ac63 commit 75e063c
Show file tree
Hide file tree
Showing 6 changed files with 666 additions and 0 deletions.
24 changes: 24 additions & 0 deletions include/ncutility/Algorithm.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#pragma once

#include "detail/EnumerateDetail.h"

#include <algorithm>
#include <type_traits>
#include <vector>

namespace nc::algo
{
/** @brief Wrapper around std::transform that returns transformed data in a new vector. */
template<class T, std::invocable<const T&> UnaryOperation>
auto Transform(const std::vector<T>& container, UnaryOperation op)
{
using transformed_t = std::remove_cvref_t<std::invoke_result_t<UnaryOperation, const T&>>;
auto out = std::vector<transformed_t>{};
out.reserve(container.size());
std::transform(std::cbegin(container), std::cend(container), std::back_inserter(out), op);
return out;
}

/** @brief Implementation of std::enumerate. Obtain a view of [index, value] pairs from a range. */
inline detail::enumerate_view_fn Enumerate;
} // namespace nc::algo
38 changes: 38 additions & 0 deletions include/ncutility/ScopeExit.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#pragma once

namespace nc::detail
{
template <class F>
class ScopeExit
{
public:
explicit ScopeExit(const F& onExit) noexcept
: m_func{onExit}
{
}

explicit ScopeExit(F&& onExit) noexcept
: m_func{std::move(onExit)}
{
}

~ScopeExit() noexcept
{
m_func();
}

ScopeExit(ScopeExit&&) = delete;
ScopeExit(const ScopeExit&) = delete;
void operator=(const ScopeExit&) = delete;
void operator=(ScopeExit&&) = delete;

private:
F m_func;
};
} // namespace nc::detail

#define UNIQUE_NAME_HELPER(name, lineNumber) name ## lineNumber
#define UNIQUE_NAME(name, lineNumber) UNIQUE_NAME_HELPER(name, lineNumber)

/** @brief Create an RAII object in the current stack scope that executes 'body' on destruction. */
#define SCOPE_EXIT(body) auto UNIQUE_NAME(localScopeExitFunc, __LINE__) = nc::detail::ScopeExit([&](){body;});
Loading

0 comments on commit 75e063c

Please sign in to comment.