Initial commit

This commit is contained in:
matthias@arch 2022-09-04 23:09:54 +02:00
commit 97c3f65b80
14 changed files with 4568 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
build
docs
libgzutil.a

24
PKGBUILD Normal file
View File

@ -0,0 +1,24 @@
# Maintainer: Matthias Quintern <matthiasqui@protonmail.com>
pkgname=gz-cpp-util
pkgver=1.0
pkgrel=1
pkgdesc="Utility library for c++"
arch=('any')
url="https://github.com/MatthiasQuintern/gz-cpp-util"
license=('GPL3')
makedepends=('git')
source=("git+${url}#branch=main")
md5sums=('SKIP')
build() {
mkdir -p pkg
cd "${pkgname}/src"
make release
make DESTDIR="${srcdir}/pkg_tmp" install
}
package() {
mv ${srcdir}/pkg_tmp/* ${pkgdir}
rm -d ${srcdir}/pkg_tmp
}

31
README.md Normal file
View File

@ -0,0 +1,31 @@
# gz-cpp-util
## Features
- Extensive logger using variadic templates to log almost anything
- VecX classes
- Some containers like a thread safe queue and a ringbuffer
- Regex that works with std::string_view
- Type conversion utility (from string to int/float/uint/bool)
## Installation
### Arch Linux (ABS)
- Download PKGBUILD: `wget https://raw.github.com/MatthiasQuintern/gz-cpp-util/main/PKGBUILD`
- Build and install with the Arch Build System: `makepkg -si`
### Linux
- Make a clone of this repo: `git clone https://github.com/MatthiasQuintern/gz-cpp-util`
- Build and install: `cd src && make && make install`
## Usage
- Add `-lgzutil` to your linker flags
- Include the wanted header: `#include <gz-util/*dir*/*header.hpp*>`
### Documentation
The documentation for this library can be generated using **doxygen**.
Install doxygen and run `make docs`.
## Changelog
### 2022-09-05
- initial version

2572
src/.doxygen_config Normal file

File diff suppressed because it is too large Load Diff

213
src/Container/queue.hpp Normal file
View File

@ -0,0 +1,213 @@
/* #include "util.hpp" */
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <concepts>
#include <thread>
namespace gz::util {
// from util.hpp
template<std::unsigned_integral I, std::unsigned_integral S>
inline void incrementIndex(I& i, const S containerSize) {
if (i < containerSize - 1) { i++; }
else { i = 0; }
}
template<std::unsigned_integral I, std::unsigned_integral S>
inline void decrementIndex(I& i, const S containerSize) {
if (i > 0) { i--; }
else { i = containerSize - 1; }
}
template<std::unsigned_integral I, std::unsigned_integral S>
inline I getIncrementedIndex(const I i, const S containerSize) {
if (i < containerSize - 1) { return i + 1; }
else { return 0; }
}
template<std::unsigned_integral I, std::unsigned_integral S>
inline I getDecrementedIndex(const I i, const S containerSize) {
if (i > 0) { return i - 1; }
else { return containerSize - 1; }
}
/// Make wrap incices around: i = size + 2 -> i = 2, i = -2 -> i = size - 2
template<std::integral I, std::unsigned_integral S>
size_t getValidIndex(const I i, const S containerSize) {
if (i < 0) {
return containerSize - (-i) % containerSize - 1;
}
else if (i >= static_cast<int>(containerSize)) {
return i % containerSize;
}
return i;
}
/**
* @brief A thread-safe queue with a dynamic size up until a maximum size
* @details
* Elements are ordered by the time they were put in the queue: You can only insert an element at the front and you can only get the element from the end.
*
* The queue uses a ringbuffer (which itself uses a vector) for data storage. Reallocations happen when an element is inserted into a queue with n < maxSize elements and the size of the ringbuffer is n.
* The queue will then increase the size of the ringbuffer by 10% (at least 3 elements, but the size will never be greater than maxSize).
*
* Note that "n elements" means n elements that were inserted and not accessed through get(). Elements might still by in memory after they have been get().
*
* The queue is thread safe, IF: the end of the queue is only processed by a single thread. Data races can occur when multiple threads try to retrieve elements (or clear() the queue),
* since the information from hasElement() might not be valid anymore until getCopy() gets called. Putting elements into the queue can be done by multiple threads.
*/
template<std::swappable T>
class Queue {
public:
/**
* @brief Create a new queue
* @param size The size the queue can grow to without reallocating memory.
* @param maxSize The maximum size of the queue. If more than maxSize elements are inserted, the oldest elements are discarded until size == maxSize.
*/
Queue(size_t size=10, size_t maxSize=-1);
void push_back(T& t);
void push_back(T&& t) { push_back(t); };
void emplace_back(T&& t);
/**
* @brief Check if the contains has an element that can be retrieved by get()
*/
bool hasElement();
/**
* @brief Get a reference to the oldest element
* @returns Reference to the oldest element.
* @note The reference is at least valid until the next call to push_back/emplace_back. If you are in a multithreaded environment, it is probably better to use getCopy().
* @warning Leads to undefined behavior when there is no element to get. Always check hasElement() first.
*/
T& getRef();
/**
* @brief Get a copy of the oldest element
* @returns Copy of the oldest element.
* @warning Leads to undefined behavior when there is no element to get. Always check hasElement() first.
*/
T getCopy();
/**
* @brief Remove all elements
*/
void clear();
std::vector<T>& getInternalBuffer() { return buffer; }
private:
/**
* @brief Resize the queue (if possible)
* @details
* After calling this, readIndex and writeIndex will be valid so that a push_back or emplace_back can be performed.
*/
void resize();
size_t writeIndex; ///< Points to the element that was last written
size_t readIndex; ///< Points to the element that was last read
std::vector<T> buffer;
size_t vectorCapacity;
size_t maxSize;
std::mutex mtx;
};
template<std::swappable T>
Queue<T>::Queue(size_t capacity, size_t maxSize)
: vectorCapacity(capacity), maxSize(maxSize) {
buffer.reserve(capacity);
/* buffer.resize(2); */
writeIndex = capacity - 1;
readIndex = capacity - 1;
}
template<std::swappable T>
void Queue<T>::resize() {
// if vector is at maxSize, "loose" the oldest element
if (buffer.size() == maxSize) {
incrementIndex(readIndex, buffer.size());
return;
}
// if not at end of vector rotate so that oldest element is first
if (writeIndex != vectorCapacity - 1) {
// if not at end, reserve more space and move elements
std::rotate(buffer.begin(), buffer.begin() + readIndex, buffer.end());
readIndex = 0;
writeIndex = vectorCapacity - 1;
}
// reserve 10% more space (at least space for 3 more elements).
buffer.reserve(std::min(std::max(static_cast<size_t>(1.1 * vectorCapacity), vectorCapacity + 3), maxSize));
vectorCapacity = buffer.capacity();
}
template<std::swappable T>
void Queue<T>::push_back(T& t) {
mtx.lock();
// check if this would write into oldest element
if (readIndex == getIncrementedIndex(writeIndex, vectorCapacity)) { resize(); }
util::incrementIndex(writeIndex, vectorCapacity);
if (buffer.size() < vectorCapacity) {
buffer.push_back(t);
}
else {
buffer[writeIndex] = t;
}
mtx.unlock();
/* std::cout << "queue after pushback. ri: " << readIndex << " - wi: " << writeIndex << " - size: " << buffer.size() << " - cap: " << vectorCapacity << "\n"; */
}
template<std::swappable T>
void Queue<T>::emplace_back(T&& t) {
mtx.lock();
if (readIndex == getIncrementedIndex(writeIndex, vectorCapacity)) { resize(); }
util::incrementIndex(writeIndex, vectorCapacity);
if (buffer.size() < vectorCapacity) {
buffer.emplace_back(std::move(t));
}
else {
buffer[writeIndex] = std::move(t);
}
mtx.unlock();
}
template<std::swappable T>
bool Queue<T>::hasElement() {
mtx.lock();
bool hasElement = writeIndex != readIndex;
mtx.unlock();
return hasElement;
}
template<std::swappable T>
T& Queue<T>::getRef() {
mtx.lock();
incrementIndex(readIndex, vectorCapacity);
size_t i = readIndex;
T& element = buffer[i];
mtx.unlock();
return buffer[i];
}
template<std::swappable T>
T Queue<T>::getCopy() {
mtx.lock();
incrementIndex(readIndex, vectorCapacity);
size_t i = readIndex;
mtx.unlock();
return std::move(buffer[i]); /// @todo could this in some stupid edge case lead to a data race?
}
template<std::swappable T>
void Queue<T>::clear() {
mtx.lock();
writeIndex = 0;
readIndex = 0;
mtx.unlock();
}
}

View File

@ -0,0 +1,222 @@
#pragma once
/* #include "log.hpp" */
#include "util.hpp"
#include <vector>
#include <iterator>
#include <algorithm>
#include <concepts>
namespace gz {
/**
* @brief A fixed size buffer that can store data continuously without needing to move data or reallocate memory
* @details
* A buffer with size n will store the n newest elements that were inserted. If the number of inserted elements is < n, the buffers size will also be < n.
*
* The buffer can be @ref RingBuffer::resize() "resized", which potentially leads to a reallocation of memory.
*
* @subsection ringbuffer_iteration Iteration
* The RingBuffer has its own bidirectional iterator. The normal direction is from newest to oldest element.
* @code
* RingBuffer<int> rb(4);
* for (int i = 0; i < 7; i++) { rb.push_back(i); }
* for (auto it = rb.begin(); it != rb.end(); it++) {
* std::cout << *it << " ";
* }
* @endcode
* will produce @code 6 5 4 3 @endcode
*
* If the buffer is empty, all iterators point to the separator element (end() == rend() == begin() == rbegin()).
*
* @subsection ringbuffer_technical_details Technical Details
* A buffer with size n will store its objects in a std::vector with size n+1, where the additional element serves as a separator between the newest and the oldest element.
* It is technically the real oldest element and could be accessed using end() or rend(), which will always point to this element (meaning end() == rend()), giving you a n+1 sized buffer.
* However, this element will be default initialized until n+1 elements have been inserted into the buffer, so it is not advisable to use this extra element.
*
* The RingBuffer satisfies concept std::ranges::bidirectional_range and RingBuffer::Iterator satisfies std::bidirectional_iterator
*
* The writeIndex will always point to the element that was last written.
*
*/
template<std::swappable T>
class RingBuffer {
public:
RingBuffer(size_t size=10);
/**
* @brief Bidirectonal iterator for the RingBuffer
* @todo make a const and non-const version, since const here is all over the place
*/
struct Iterator {
public:
Iterator(const RingBuffer<T>& b, size_t index) : b(b), ptr(const_cast<T*>(&b.buffer.at(index))) {}
Iterator(const Iterator& other) : b(other.b), ptr(other.ptr) {}
// Needed for std::input_iterator
using value_type = T;
T& operator*() const { return *ptr; }
Iterator& operator=(const Iterator& other) {
b = other.b;
ptr = other.ptr;
return this;
}
Iterator& operator++() {
if (ptr == &*b.buffer.begin()) { ptr = const_cast<T*>(&*b.buffer.rbegin()); }
else { ptr--; }
return *this;
}
Iterator operator++(int) {
auto copy = *this;
if (ptr == &*b.buffer.begin()) { ptr = const_cast<T*>(&*b.buffer.rbegin()); }
else { ptr--; }
return copy;
}
friend int operator-(Iterator lhs, Iterator rhs) {
return lhs.getCurrentIndex() - rhs.getCurrentIndex();
}
// Needed for std::forward_iterator
/// @warning Default constructor has to be defined for std::forward_iterator but can not be used, since reference to RingBuffer<T> can not be initialized! Your compiler should (hopefully) not allow it.
Iterator() : ptr(nullptr) {};
bool operator==(const Iterator& other) const {
return this->ptr == other.ptr;
}
// Needed for std::bidirectional_iterator
Iterator& operator--() {
if (ptr == &*b.buffer.rbegin()) { ptr = const_cast<T*>(&*b.buffer.begin()); }
else { ptr++; }
return *this;
}
Iterator operator--(int) {
auto copy = *this;
if (ptr == &*b.buffer.rbegin()) { ptr = const_cast<T*>(&*b.buffer.begin()); }
else { ptr++; }
return copy;
}
// Not needed )
/* friend Iterator operator+(Iterator lhs, int i) { */
/* return Iterator(lhs.b, &lhs.b.buffer[lhs.getValidIndex(lhs.getCurrentIndex() + i)]); */
/* } */
/* friend Iterator operator-(Iterator lhs, int i) { */
/* return Iterator(lhs.b, &lhs.b.buffer[lhs.getValidIndex(lhs.getCurrentIndex() - i)]); */
/* } */
/* friend Iterator operator+(int i, Iterator rhs) { */
/* return Iterator(rhs.b, &rhs.b.buffer[rhs.getValidIndex(rhs.getCurrentIndex() + i)]); */
/* } */
/* Iterator& operator+=(int i) { */
/* ptr = &b.buffer[getValidIndex(getCurrentIndex() + i)]; */
/* return this; */
/* } */
/* Iterator& operator-=(int i) { */
/* ptr = &b.buffer[getValidIndex(getCurrentIndex() - i)]; */
/* return this; */
/* } */
/* bool operator!=(const Iterator& other) const { */
/* return this->ptr != other.ptr; */
/* } */
/// Get the index of the vector that ptr points to
std::string to_string() const {
return "Element: " + std::to_string(*ptr) + ", Index: " + std::to_string(getCurrentIndex()) + ", Pointer: " + std::to_string(reinterpret_cast<long>(ptr));
}
private:
size_t getCurrentIndex() const {
return reinterpret_cast<long>(ptr - &*b.buffer.begin());
}
T* ptr;
const RingBuffer<T>& b;
};
void push_back(T& t);
void push_back(T&& t) { push_back(t); };
void emplace_back(T&& t);
/**
* @brief Return an iterator pointing to the newest object
*/
const Iterator cbegin() const { return Iterator(*this, writeIndex); }
/**
* @brief Return an iterator poiting to the element preceeding the oldest element
*/
const Iterator cend() const { return Iterator(*this, util::getIncrementedIndex(writeIndex, buffer.size())); }
/**
* @brief Return an iterator pointing to the oldest object
*/
const Iterator crbegin() const { return Iterator(*this, util::getIncrementedIndex(writeIndex + 1, buffer.size())); }
/**
* @brief Return an iterator pointing to the element following the newest element
*/
const Iterator crend() const { return Iterator(*this, util::getIncrementedIndex(writeIndex, buffer.size())); }
const Iterator begin() { return Iterator(*this, writeIndex); }
const Iterator end() { return Iterator(*this, util::getIncrementedIndex(writeIndex, buffer.size())); }
const Iterator rbegin() { return Iterator(*this, util::getIncrementedIndex(writeIndex + 1, buffer.size())); }
const Iterator rend() { return Iterator(*this, util::getIncrementedIndex(writeIndex, buffer.size())); }
/**
* @brief Resize the buffer to contain max size elements
* @details
* If the current size is greater than size, the buffer is reduced to the newest elements that fit size. \n
* If the current size is smaller than size, the buffer size remains but it will be able to grow during element insertion until size is reached.
*/
void resize(const size_t size);
size_t capacity() const { return vectorCapacity - 1; }
size_t size() const { return buffer.size() - 1; }
private:
size_t writeIndex; ///< Points to the element that was last written
std::vector<T> buffer;
size_t vectorCapacity;
};
template<std::swappable T>
RingBuffer<T>::RingBuffer(size_t capacity) {
buffer.reserve(capacity + 1);
buffer.resize(1);
vectorCapacity = capacity + 1;
writeIndex = 0;
}
template<std::swappable T>
void RingBuffer<T>::resize(size_t size) {
if (size + 1 > buffer.capacity()) { // when growing
// point writeIndex to separator
util::incrementIndex(writeIndex, buffer.size());
// separator element becomes first element -> vector grows while inserting elements
std::rotate(buffer.begin(), buffer.begin() + writeIndex, buffer.end());
buffer.reserve(size + 1);
writeIndex = buffer.size() - 1;
}
else if (size + 1 < buffer.size()) { // when shrinking
// point writeIndex to separator
util::incrementIndex(writeIndex, buffer.size());
// separator becomes last element in smaller vector -> resize cuts oldest elements
std::rotate(buffer.begin(), buffer.begin() + util::getValidIndex(static_cast<int>(writeIndex - size), buffer.size()), buffer.end());
buffer.resize(size + 1);
writeIndex = util::getValidIndex(static_cast<int>(buffer.size() - 2), buffer.size());
}
vectorCapacity = size + 1;
}
template<std::swappable T>
void RingBuffer<T>::push_back(T& t) {
util::incrementIndex(writeIndex, vectorCapacity);
if (buffer.size() < vectorCapacity) {
buffer.push_back(t);
}
else {
buffer[writeIndex] = t;
}
}
template<std::swappable T>
void RingBuffer<T>::emplace_back(T&& t) {
util::incrementIndex(writeIndex, vectorCapacity);
if (buffer.size() < vectorCapacity) {
buffer.emplace_back(std::move(t));
}
else {
buffer[writeIndex] = std::move(t);
}
}
}

61
src/Makefile Executable file
View File

@ -0,0 +1,61 @@
CXX = /usr/bin/g++
CXXFLAGS = -std=c++20 -MMD -MP -O3
SRCDIRS = $(wildcard */)
IFLAGS = $(foreach dir,$(SRCDIRS), -I$(dir))
IFLAGS += $(foreach dir,$(SRCDIRS), -I../$(dir))
OBJECT_DIR = ../build
LIB = ../libgzutil.a
HEADER = $(wildcard *.hpp) $(wildcard */*.hpp)
HEADER_INST = $($(notdir HEADER):%.hpp=$(OBJECT_DIR)/%.stamp)
SRC = $(wildcard *.cpp) $(wildcard */*.cpp)
# OBJECTS = $(SRC:%.cpp=$(OBJECT_DIR)/%.o)
OBJECTS = $($(notdir SRC):%.cpp=$(OBJECT_DIR)/%.o)
OBJECT_DIRS = $(OBJECT_DIR) $(foreach dir,$(SRCDIRS), $(OBJECT_DIR)/$(dir))
DEPENDS = ${OBJECTS:.o=.d}
CXXFLAGS += $(IFLAGS)
.PHONY: install debug run clean docs
#
# BUILDING
#
default: $(LIB)
echo $(OBJECTS)
# with debug flags
debug: CXXFLAGS += -g +Wextra # -DDEBUG
debug: default
$(LIB): $(OBJECT_DIRS) $(OBJECTS)
ar -cq $(LIB) $(OBJECTS)
# include the makefiles generated by the -M flag
-include $(DEPENDS)
# rule for all ../build/*.o files
$(OBJECT_DIR)/%.o: %.cpp
$(CXX) -c $< -o $@ $(CXXFLAGS) $(LDFLAGS) $(LDLIBS)
$(OBJECT_DIRS):
mkdir -p $@
#
# INSTALLATION
#
install: $(LIB) $(HEADER_INST)
$(OBJECT_DIR)/%.stamp: %.hpp $(OBJECT_DIR)
install -D -m 644 $< $(DESTDIR)/usr/include/gz-util/$<
touch $@
#
# EXTRAS
#
# remove all object and dependecy files
clean:
-rm -r $(OBJECT_DIR)
-rm $(LIB)
docs:
doxygen .doxygen_config

715
src/Math/vec.hpp Normal file
View File

@ -0,0 +1,715 @@
#pragma once
#include<string>
#include <cmath>
#include <algorithm>
namespace gz {
/**
* @brief Class containing 2 numbers
*/
template<typename T>
class vec2 {
public:
// Constructors
/// Default constructor
vec2() : x(0), y(0) {};
/// Create a vec2 from n n
template<typename N0, typename N1>
vec2(N0 n0, N1 n1) : x(static_cast<T>(n0)), y(static_cast<T>(n1)) {};
/// Create a vec2 from vec2
template<typename V0>
vec2(const vec2<V0>& v0) : x(static_cast<T>(v0.x)), y(static_cast<T>(v0.y)) {};
// Values
T x;
T y;
// Assignment
/// component-wise assignment
template<typename V>
void operator=(const vec2<V>& other) {
x = static_cast<T>(other.x);
y = static_cast<T>(other.y);
};
template<typename N>
void operator=(const N& other) {
x = static_cast<T>(other);
y = static_cast<T>(other);
};
// Arithmetic
// Vectorial
/// component-wise +
template<typename V>
vec2<T> operator+(const vec2<V>& other) const { return vec2<T>(x + static_cast<T>(other.x), y + static_cast<T>(other.y)); };
/// component-wise -
template<typename V>
vec2<T> operator-(const vec2<V>& other) const { return vec2<T>(x - static_cast<T>(other.x), y - static_cast<T>(other.y)); };
/// component-wise *
template<typename V>
vec2<T> operator*(const vec2<V>& other) const { return vec2<T>(x * static_cast<T>(other.x), y * static_cast<T>(other.y)); };
/// component-wise /
template<typename V>
vec2<T> operator/(const vec2<V>& other) const { return vec2<T>(x / static_cast<T>(other.x), y / static_cast<T>(other.y)); };
/// component-wise %
template<typename V>
vec2<T> operator%(const vec2<V>& other) const { return vec2<T>(x % static_cast<T>(other.x), y % static_cast<T>(other.y)); };
/// component-wise assignment+=
template<typename V>
void operator+=(const vec2<V>& other) {
x += static_cast<T>(other.x);
y += static_cast<T>(other.y);
};
/// component-wise assignment-=
template<typename V>
void operator-=(const vec2<V>& other) {
x -= static_cast<T>(other.x);
y -= static_cast<T>(other.y);
};
/// component-wise assignment*=
template<typename V>
void operator*=(const vec2<V>& other) {
x *= static_cast<T>(other.x);
y *= static_cast<T>(other.y);
};
/// component-wise assignment/=
template<typename V>
void operator/=(const vec2<V>& other) {
x /= static_cast<T>(other.x);
y /= static_cast<T>(other.y);
};
/// component-wise assignment%=
template<typename V>
void operator%=(const vec2<V>& other) {
x %= static_cast<T>(other.x);
y %= static_cast<T>(other.y);
};
// Scalar
/// component-wise +
template<typename N>
vec2<T> operator+(const N& other) const { return vec2<T>(x + static_cast<T>(other.x), y + static_cast<T>(other.y)); };
/// component-wise -
template<typename N>
vec2<T> operator-(const N& other) const { return vec2<T>(x - static_cast<T>(other.x), y - static_cast<T>(other.y)); };
/// component-wise *
template<typename N>
vec2<T> operator*(const N& other) const { return vec2<T>(x * static_cast<T>(other.x), y * static_cast<T>(other.y)); };
/// component-wise /
template<typename N>
vec2<T> operator/(const N& other) const { return vec2<T>(x / static_cast<T>(other.x), y / static_cast<T>(other.y)); };
/// component-wise %
template<typename N>
vec2<T> operator%(const N& other) const { return vec2<T>(x % static_cast<T>(other.x), y % static_cast<T>(other.y)); };
/// component-wise assignment+=
template<typename N>
void operator+=(const N& other) {
x += static_cast<T>(other.x);
y += static_cast<T>(other.y);
};
/// component-wise assignment-=
template<typename N>
void operator-=(const N& other) {
x -= static_cast<T>(other.x);
y -= static_cast<T>(other.y);
};
/// component-wise assignment*=
template<typename N>
void operator*=(const N& other) {
x *= static_cast<T>(other.x);
y *= static_cast<T>(other.y);
};
/// component-wise assignment/=
template<typename N>
void operator/=(const N& other) {
x /= static_cast<T>(other.x);
y /= static_cast<T>(other.y);
};
/// component-wise assignment%=
template<typename N>
void operator%=(const N& other) {
x %= static_cast<T>(other.x);
y %= static_cast<T>(other.y);
};
// Comparison
// Vectorial
/// component-wise comparison == (and)
template<typename N>
bool operator==(const vec2<N>& other) const { return x == other.x and y == other.y; };
/// component-wise comparison < (and)
template<typename N>
bool operator<(const vec2<N>& other) const { return x < other.x and y < other.y; };
/// component-wise comparison > (and)
template<typename N>
bool operator>(const vec2<N>& other) const { return x > other.x and y > other.y; };
/// component-wise comparison != (and)
template<typename N>
bool operator!=(const vec2<N>& other) const { return x == other.x and y == other.y; };
/// component-wise comparison <= (and)
template<typename N>
bool operator<=(const vec2<N>& other) const { return x > other.x and y > other.y; };
/// component-wise comparison >= (and)
template<typename N>
bool operator>=(const vec2<N>& other) const { return x < other.x and y < other.y; };
// Scalar
/// component-wise comparison == (and)
template<typename N>
bool operator==(const N& other) const { return x == other.x and y == other.y; };
/// component-wise comparison < (and)
template<typename N>
bool operator<(const N& other) const { return x < other.x and y < other.y; };
/// component-wise comparison > (and)
template<typename N>
bool operator>(const N& other) const { return x > other.x and y > other.y; };
/// component-wise comparison != (and)
template<typename N>
bool operator!=(const N& other) const { return x == other.x and y == other.y; };
/// component-wise comparison <= (and)
template<typename N>
bool operator<=(const N& other) const { return x > other.x and y > other.y; };
/// component-wise comparison >= (and)
template<typename N>
bool operator>=(const N& other) const { return x < other.x and y < other.y; };
// Functional
/// Returns the absolute value of the vector
inline float abs() const { return std::sqrt(static_cast<float>(x * x) + static_cast<float>(y * y)); };/// Returns x/y
inline float ratio() const { return static_cast<float>(x) / y; };/// Returns y/x
inline float inverseRatio() const { return static_cast<float>(y) / x; };/// Returns the min of the components
inline T min() const { return std::min_element(cbegin(), cend()); };
/// Returns the max of the components
inline T max() const { return std::max_element(cbegin(), cend()); };
/// Scalar product
template<typename V>
inline vec2<T> dot(const vec2<V>& other) { return vec2<T>(x * static_cast<T>(other.x) + y * static_cast<T>(other.y)); };
// Utility
std::string to_string() const { return "(" + std::to_string(x) + ", " + std::to_string(y) + ")"; };
struct Iterator {
public:
using value_type = T;
Iterator() : ptr(nullptr) {};
Iterator(T* ptr) : ptr(ptr) {};
T& operator*() { return *ptr; };
Iterator& operator=(const Iterator& other) {
ptr = other.ptr;
return *this;
};
Iterator& operator++() { ptr += sizeof(T); return *this; };
Iterator operator++(int) { auto copy = *this; ptr += sizeof(T); return copy; };
friend int operator-(Iterator lhs, Iterator rhs) {
return lhs.ptr - rhs.ptr;
};
bool operator==(const Iterator& other) const { return ptr == other.ptr; };
// bool operator!=(const Iterator& other) const { return ptr != other.ptr; };
private:
T* ptr;
};
const Iterator cbegin() const { return Iterator(&x); };
const Iterator cend() const { return Iterator(&y); };
const Iterator begin() const { return Iterator(&x); };
const Iterator end() const { return Iterator(&y); };
}; // vec2
/**
* @brief Class containing 3 numbers
*/
template<typename T>
class vec3 {
public:
// Constructors
/// Default constructor
vec3() : x(0), y(0), z(0) {};
/// Create a vec3 from n n n
template<typename N0, typename N1, typename N2>
vec3(N0 n0, N1 n1, N2 n2) : x(static_cast<T>(n0)), y(static_cast<T>(n1)), z(static_cast<T>(n2)) {};
/// Create a vec3 from n vec2
template<typename N0, typename V0>
vec3(N0 n0, const vec2<V0>& v0) : x(static_cast<T>(n0)), y(static_cast<T>(v0.x)), z(static_cast<T>(v0.y)) {};
/// Create a vec3 from vec2 n
template<typename V0, typename N0>
vec3(const vec2<V0>& v0, N0 n0) : x(static_cast<T>(v0.x)), y(static_cast<T>(v0.y)), z(static_cast<T>(n0)) {};
/// Create a vec3 from vec3
template<typename V0>
vec3(const vec3<V0>& v0) : x(static_cast<T>(v0.x)), y(static_cast<T>(v0.y)), z(static_cast<T>(v0.z)) {};
// Values
T x;
T y;
T z;
// Assignment
/// component-wise assignment
template<typename V>
void operator=(const vec3<V>& other) {
x = static_cast<T>(other.x);
y = static_cast<T>(other.y);
z = static_cast<T>(other.z);
};
template<typename N>
void operator=(const N& other) {
x = static_cast<T>(other);
y = static_cast<T>(other);
z = static_cast<T>(other);
};
// Arithmetic
// Vectorial
/// component-wise +
template<typename V>
vec3<T> operator+(const vec3<V>& other) const { return vec3<T>(x + static_cast<T>(other.x), y + static_cast<T>(other.y), z + static_cast<T>(other.z)); };
/// component-wise -
template<typename V>
vec3<T> operator-(const vec3<V>& other) const { return vec3<T>(x - static_cast<T>(other.x), y - static_cast<T>(other.y), z - static_cast<T>(other.z)); };
/// component-wise *
template<typename V>
vec3<T> operator*(const vec3<V>& other) const { return vec3<T>(x * static_cast<T>(other.x), y * static_cast<T>(other.y), z * static_cast<T>(other.z)); };
/// component-wise /
template<typename V>
vec3<T> operator/(const vec3<V>& other) const { return vec3<T>(x / static_cast<T>(other.x), y / static_cast<T>(other.y), z / static_cast<T>(other.z)); };
/// component-wise %
template<typename V>
vec3<T> operator%(const vec3<V>& other) const { return vec3<T>(x % static_cast<T>(other.x), y % static_cast<T>(other.y), z % static_cast<T>(other.z)); };
/// component-wise assignment+=
template<typename V>
void operator+=(const vec3<V>& other) {
x += static_cast<T>(other.x);
y += static_cast<T>(other.y);
z += static_cast<T>(other.z);
};
/// component-wise assignment-=
template<typename V>
void operator-=(const vec3<V>& other) {
x -= static_cast<T>(other.x);
y -= static_cast<T>(other.y);
z -= static_cast<T>(other.z);
};
/// component-wise assignment*=
template<typename V>
void operator*=(const vec3<V>& other) {
x *= static_cast<T>(other.x);
y *= static_cast<T>(other.y);
z *= static_cast<T>(other.z);
};
/// component-wise assignment/=
template<typename V>
void operator/=(const vec3<V>& other) {
x /= static_cast<T>(other.x);
y /= static_cast<T>(other.y);
z /= static_cast<T>(other.z);
};
/// component-wise assignment%=
template<typename V>
void operator%=(const vec3<V>& other) {
x %= static_cast<T>(other.x);
y %= static_cast<T>(other.y);
z %= static_cast<T>(other.z);
};
// Scalar
/// component-wise +
template<typename N>
vec3<T> operator+(const N& other) const { return vec3<T>(x + static_cast<T>(other.x), y + static_cast<T>(other.y), z + static_cast<T>(other.z)); };
/// component-wise -
template<typename N>
vec3<T> operator-(const N& other) const { return vec3<T>(x - static_cast<T>(other.x), y - static_cast<T>(other.y), z - static_cast<T>(other.z)); };
/// component-wise *
template<typename N>
vec3<T> operator*(const N& other) const { return vec3<T>(x * static_cast<T>(other.x), y * static_cast<T>(other.y), z * static_cast<T>(other.z)); };
/// component-wise /
template<typename N>
vec3<T> operator/(const N& other) const { return vec3<T>(x / static_cast<T>(other.x), y / static_cast<T>(other.y), z / static_cast<T>(other.z)); };
/// component-wise %
template<typename N>
vec3<T> operator%(const N& other) const { return vec3<T>(x % static_cast<T>(other.x), y % static_cast<T>(other.y), z % static_cast<T>(other.z)); };
/// component-wise assignment+=
template<typename N>
void operator+=(const N& other) {
x += static_cast<T>(other.x);
y += static_cast<T>(other.y);
z += static_cast<T>(other.z);
};
/// component-wise assignment-=
template<typename N>
void operator-=(const N& other) {
x -= static_cast<T>(other.x);
y -= static_cast<T>(other.y);
z -= static_cast<T>(other.z);
};
/// component-wise assignment*=
template<typename N>
void operator*=(const N& other) {
x *= static_cast<T>(other.x);
y *= static_cast<T>(other.y);
z *= static_cast<T>(other.z);
};
/// component-wise assignment/=
template<typename N>
void operator/=(const N& other) {
x /= static_cast<T>(other.x);
y /= static_cast<T>(other.y);
z /= static_cast<T>(other.z);
};
/// component-wise assignment%=
template<typename N>
void operator%=(const N& other) {
x %= static_cast<T>(other.x);
y %= static_cast<T>(other.y);
z %= static_cast<T>(other.z);
};
// Comparison
// Vectorial
/// component-wise comparison == (and)
template<typename N>
bool operator==(const vec3<N>& other) const { return x == other.x and y == other.y and z == other.z; };
/// component-wise comparison < (and)
template<typename N>
bool operator<(const vec3<N>& other) const { return x < other.x and y < other.y and z < other.z; };
/// component-wise comparison > (and)
template<typename N>
bool operator>(const vec3<N>& other) const { return x > other.x and y > other.y and z > other.z; };
/// component-wise comparison != (and)
template<typename N>
bool operator!=(const vec3<N>& other) const { return x == other.x and y == other.y and z == other.z; };
/// component-wise comparison <= (and)
template<typename N>
bool operator<=(const vec3<N>& other) const { return x > other.x and y > other.y and z > other.z; };
/// component-wise comparison >= (and)
template<typename N>
bool operator>=(const vec3<N>& other) const { return x < other.x and y < other.y and z < other.z; };
// Scalar
/// component-wise comparison == (and)
template<typename N>
bool operator==(const N& other) const { return x == other.x and y == other.y and z == other.z; };
/// component-wise comparison < (and)
template<typename N>
bool operator<(const N& other) const { return x < other.x and y < other.y and z < other.z; };
/// component-wise comparison > (and)
template<typename N>
bool operator>(const N& other) const { return x > other.x and y > other.y and z > other.z; };
/// component-wise comparison != (and)
template<typename N>
bool operator!=(const N& other) const { return x == other.x and y == other.y and z == other.z; };
/// component-wise comparison <= (and)
template<typename N>
bool operator<=(const N& other) const { return x > other.x and y > other.y and z > other.z; };
/// component-wise comparison >= (and)
template<typename N>
bool operator>=(const N& other) const { return x < other.x and y < other.y and z < other.z; };
// Functional
/// Returns the absolute value of the vector
inline float abs() const { return std::sqrt(static_cast<float>(x * x) + static_cast<float>(y * y) + static_cast<float>(z * z)); };/// Returns the min of the components
inline T min() const { return std::min_element(cbegin(), cend()); };
/// Returns the max of the components
inline T max() const { return std::max_element(cbegin(), cend()); };
/// Scalar product
template<typename V>
inline vec3<T> dot(const vec3<V>& other) { return vec3<T>(x * static_cast<T>(other.x) + y * static_cast<T>(other.y) + z * static_cast<T>(other.z)); };
// Utility
std::string to_string() const { return "(" + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z) + ")"; };
struct Iterator {
public:
using value_type = T;
Iterator() : ptr(nullptr) {};
Iterator(T* ptr) : ptr(ptr) {};
T& operator*() { return *ptr; };
Iterator& operator=(const Iterator& other) {
ptr = other.ptr;
return *this;
};
Iterator& operator++() { ptr += sizeof(T); return *this; };
Iterator operator++(int) { auto copy = *this; ptr += sizeof(T); return copy; };
friend int operator-(Iterator lhs, Iterator rhs) {
return lhs.ptr - rhs.ptr;
};
bool operator==(const Iterator& other) const { return ptr == other.ptr; };
// bool operator!=(const Iterator& other) const { return ptr != other.ptr; };
private:
T* ptr;
};
const Iterator cbegin() const { return Iterator(&x); };
const Iterator cend() const { return Iterator(&z); };
const Iterator begin() const { return Iterator(&x); };
const Iterator end() const { return Iterator(&z); };
}; // vec3
/**
* @brief Class containing 4 numbers
*/
template<typename T>
class vec4 {
public:
// Constructors
/// Default constructor
vec4() : x(0), y(0), z(0), w(0) {};
/// Create a vec4 from n n n n
template<typename N0, typename N1, typename N2, typename N3>
vec4(N0 n0, N1 n1, N2 n2, N3 n3) : x(static_cast<T>(n0)), y(static_cast<T>(n1)), z(static_cast<T>(n2)), w(static_cast<T>(n3)) {};
/// Create a vec4 from n n vec2
template<typename N0, typename N1, typename V0>
vec4(N0 n0, N1 n1, const vec2<V0>& v0) : x(static_cast<T>(n0)), y(static_cast<T>(n1)), z(static_cast<T>(v0.x)), w(static_cast<T>(v0.y)) {};
/// Create a vec4 from n vec2 n
template<typename N0, typename V0, typename N1>
vec4(N0 n0, const vec2<V0>& v0, N1 n1) : x(static_cast<T>(n0)), y(static_cast<T>(v0.x)), z(static_cast<T>(v0.y)), w(static_cast<T>(n1)) {};
/// Create a vec4 from n vec3
template<typename N0, typename V0>
vec4(N0 n0, const vec3<V0>& v0) : x(static_cast<T>(n0)), y(static_cast<T>(v0.x)), z(static_cast<T>(v0.y)), w(static_cast<T>(v0.z)) {};
/// Create a vec4 from vec2 n n
template<typename V0, typename N0, typename N1>
vec4(const vec2<V0>& v0, N0 n0, N1 n1) : x(static_cast<T>(v0.x)), y(static_cast<T>(v0.y)), z(static_cast<T>(n0)), w(static_cast<T>(n1)) {};
/// Create a vec4 from vec2 vec2
template<typename V0, typename V1>
vec4(const vec2<V0>& v0, const vec2<V1>& v1) : x(static_cast<T>(v0.x)), y(static_cast<T>(v0.y)), z(static_cast<T>(v1.x)), w(static_cast<T>(v1.y)) {};
/// Create a vec4 from vec3 n
template<typename V0, typename N0>
vec4(const vec3<V0>& v0, N0 n0) : x(static_cast<T>(v0.x)), y(static_cast<T>(v0.y)), z(static_cast<T>(v0.z)), w(static_cast<T>(n0)) {};
/// Create a vec4 from vec4
template<typename V0>
vec4(const vec4<V0>& v0) : x(static_cast<T>(v0.x)), y(static_cast<T>(v0.y)), z(static_cast<T>(v0.z)), w(static_cast<T>(v0.w)) {};
// Values
T x;
T y;
T z;
T w;
// Assignment
/// component-wise assignment
template<typename V>
void operator=(const vec4<V>& other) {
x = static_cast<T>(other.x);
y = static_cast<T>(other.y);
z = static_cast<T>(other.z);
w = static_cast<T>(other.w);
};
template<typename N>
void operator=(const N& other) {
x = static_cast<T>(other);
y = static_cast<T>(other);
z = static_cast<T>(other);
w = static_cast<T>(other);
};
// Arithmetic
// Vectorial
/// component-wise +
template<typename V>
vec4<T> operator+(const vec4<V>& other) const { return vec4<T>(x + static_cast<T>(other.x), y + static_cast<T>(other.y), z + static_cast<T>(other.z), w + static_cast<T>(other.w)); };
/// component-wise -
template<typename V>
vec4<T> operator-(const vec4<V>& other) const { return vec4<T>(x - static_cast<T>(other.x), y - static_cast<T>(other.y), z - static_cast<T>(other.z), w - static_cast<T>(other.w)); };
/// component-wise *
template<typename V>
vec4<T> operator*(const vec4<V>& other) const { return vec4<T>(x * static_cast<T>(other.x), y * static_cast<T>(other.y), z * static_cast<T>(other.z), w * static_cast<T>(other.w)); };
/// component-wise /
template<typename V>
vec4<T> operator/(const vec4<V>& other) const { return vec4<T>(x / static_cast<T>(other.x), y / static_cast<T>(other.y), z / static_cast<T>(other.z), w / static_cast<T>(other.w)); };
/// component-wise %
template<typename V>
vec4<T> operator%(const vec4<V>& other) const { return vec4<T>(x % static_cast<T>(other.x), y % static_cast<T>(other.y), z % static_cast<T>(other.z), w % static_cast<T>(other.w)); };
/// component-wise assignment+=
template<typename V>
void operator+=(const vec4<V>& other) {
x += static_cast<T>(other.x);
y += static_cast<T>(other.y);
z += static_cast<T>(other.z);
w += static_cast<T>(other.w);
};
/// component-wise assignment-=
template<typename V>
void operator-=(const vec4<V>& other) {
x -= static_cast<T>(other.x);
y -= static_cast<T>(other.y);
z -= static_cast<T>(other.z);
w -= static_cast<T>(other.w);
};
/// component-wise assignment*=
template<typename V>
void operator*=(const vec4<V>& other) {
x *= static_cast<T>(other.x);
y *= static_cast<T>(other.y);
z *= static_cast<T>(other.z);
w *= static_cast<T>(other.w);
};
/// component-wise assignment/=
template<typename V>
void operator/=(const vec4<V>& other) {
x /= static_cast<T>(other.x);
y /= static_cast<T>(other.y);
z /= static_cast<T>(other.z);
w /= static_cast<T>(other.w);
};
/// component-wise assignment%=
template<typename V>
void operator%=(const vec4<V>& other) {
x %= static_cast<T>(other.x);
y %= static_cast<T>(other.y);
z %= static_cast<T>(other.z);
w %= static_cast<T>(other.w);
};
// Scalar
/// component-wise +
template<typename N>
vec4<T> operator+(const N& other) const { return vec4<T>(x + static_cast<T>(other.x), y + static_cast<T>(other.y), z + static_cast<T>(other.z), w + static_cast<T>(other.w)); };
/// component-wise -
template<typename N>
vec4<T> operator-(const N& other) const { return vec4<T>(x - static_cast<T>(other.x), y - static_cast<T>(other.y), z - static_cast<T>(other.z), w - static_cast<T>(other.w)); };
/// component-wise *
template<typename N>
vec4<T> operator*(const N& other) const { return vec4<T>(x * static_cast<T>(other.x), y * static_cast<T>(other.y), z * static_cast<T>(other.z), w * static_cast<T>(other.w)); };
/// component-wise /
template<typename N>
vec4<T> operator/(const N& other) const { return vec4<T>(x / static_cast<T>(other.x), y / static_cast<T>(other.y), z / static_cast<T>(other.z), w / static_cast<T>(other.w)); };
/// component-wise %
template<typename N>
vec4<T> operator%(const N& other) const { return vec4<T>(x % static_cast<T>(other.x), y % static_cast<T>(other.y), z % static_cast<T>(other.z), w % static_cast<T>(other.w)); };
/// component-wise assignment+=
template<typename N>
void operator+=(const N& other) {
x += static_cast<T>(other.x);
y += static_cast<T>(other.y);
z += static_cast<T>(other.z);
w += static_cast<T>(other.w);
};
/// component-wise assignment-=
template<typename N>
void operator-=(const N& other) {
x -= static_cast<T>(other.x);
y -= static_cast<T>(other.y);
z -= static_cast<T>(other.z);
w -= static_cast<T>(other.w);
};
/// component-wise assignment*=
template<typename N>
void operator*=(const N& other) {
x *= static_cast<T>(other.x);
y *= static_cast<T>(other.y);
z *= static_cast<T>(other.z);
w *= static_cast<T>(other.w);
};
/// component-wise assignment/=
template<typename N>
void operator/=(const N& other) {
x /= static_cast<T>(other.x);
y /= static_cast<T>(other.y);
z /= static_cast<T>(other.z);
w /= static_cast<T>(other.w);
};
/// component-wise assignment%=
template<typename N>
void operator%=(const N& other) {
x %= static_cast<T>(other.x);
y %= static_cast<T>(other.y);
z %= static_cast<T>(other.z);
w %= static_cast<T>(other.w);
};
// Comparison
// Vectorial
/// component-wise comparison == (and)
template<typename N>
bool operator==(const vec4<N>& other) const { return x == other.x and y == other.y and z == other.z and w == other.w; };
/// component-wise comparison < (and)
template<typename N>
bool operator<(const vec4<N>& other) const { return x < other.x and y < other.y and z < other.z and w < other.w; };
/// component-wise comparison > (and)
template<typename N>
bool operator>(const vec4<N>& other) const { return x > other.x and y > other.y and z > other.z and w > other.w; };
/// component-wise comparison != (and)
template<typename N>
bool operator!=(const vec4<N>& other) const { return x == other.x and y == other.y and z == other.z and w == other.w; };
/// component-wise comparison <= (and)
template<typename N>
bool operator<=(const vec4<N>& other) const { return x > other.x and y > other.y and z > other.z and w > other.w; };
/// component-wise comparison >= (and)
template<typename N>
bool operator>=(const vec4<N>& other) const { return x < other.x and y < other.y and z < other.z and w < other.w; };
// Scalar
/// component-wise comparison == (and)
template<typename N>
bool operator==(const N& other) const { return x == other.x and y == other.y and z == other.z and w == other.w; };
/// component-wise comparison < (and)
template<typename N>
bool operator<(const N& other) const { return x < other.x and y < other.y and z < other.z and w < other.w; };
/// component-wise comparison > (and)
template<typename N>
bool operator>(const N& other) const { return x > other.x and y > other.y and z > other.z and w > other.w; };
/// component-wise comparison != (and)
template<typename N>
bool operator!=(const N& other) const { return x == other.x and y == other.y and z == other.z and w == other.w; };
/// component-wise comparison <= (and)
template<typename N>
bool operator<=(const N& other) const { return x > other.x and y > other.y and z > other.z and w > other.w; };
/// component-wise comparison >= (and)
template<typename N>
bool operator>=(const N& other) const { return x < other.x and y < other.y and z < other.z and w < other.w; };
// Functional
/// Returns the absolute value of the vector
inline float abs() const { return std::sqrt(static_cast<float>(x * x) + static_cast<float>(y * y) + static_cast<float>(z * z) + static_cast<float>(w * w)); };/// Returns the min of the components
inline T min() const { return std::min_element(cbegin(), cend()); };
/// Returns the max of the components
inline T max() const { return std::max_element(cbegin(), cend()); };
/// Scalar product
template<typename V>
inline vec4<T> dot(const vec4<V>& other) { return vec4<T>(x * static_cast<T>(other.x) + y * static_cast<T>(other.y) + z * static_cast<T>(other.z) + w * static_cast<T>(other.w)); };
// Utility
std::string to_string() const { return "(" + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z) + ", " + std::to_string(w) + ")"; };
struct Iterator {
public:
using value_type = T;
Iterator() : ptr(nullptr) {};
Iterator(T* ptr) : ptr(ptr) {};
T& operator*() { return *ptr; };
Iterator& operator=(const Iterator& other) {
ptr = other.ptr;
return *this;
};
Iterator& operator++() { ptr += sizeof(T); return *this; };
Iterator operator++(int) { auto copy = *this; ptr += sizeof(T); return copy; };
friend int operator-(Iterator lhs, Iterator rhs) {
return lhs.ptr - rhs.ptr;
};
bool operator==(const Iterator& other) const { return ptr == other.ptr; };
// bool operator!=(const Iterator& other) const { return ptr != other.ptr; };
private:
T* ptr;
};
const Iterator cbegin() const { return Iterator(&x); };
const Iterator cend() const { return Iterator(&w); };
const Iterator begin() const { return Iterator(&x); };
const Iterator end() const { return Iterator(&w); };
}; // vec4
using vec2f = vec2<float>;
using vec2d = vec2<double>;
using vec2i = vec2<int>;
using vec2u = vec2<unsigned int>;
using vec3f = vec3<float>;
using vec3d = vec3<double>;
using vec3i = vec3<int>;
using vec3u = vec3<unsigned int>;
using vec4f = vec4<float>;
using vec4d = vec4<double>;
using vec4i = vec4<int>;
using vec4u = vec4<unsigned int>;
} // namespace gz

7
src/Util/gz_regex.cpp Normal file
View File

@ -0,0 +1,7 @@
#include "gz_regex.hpp"
namespace gz::re {
const std::regex types::intT(R"([+\-]?(0x|0X)?\d+)");
const std::regex types::uintT(R"(\+?(0x|0X)?\d+)");
const std::regex types::floatT(R"([+\-]?(((\d+\.?\d*)|(\d*\.?\d+))(e[+\-]?\d+)?)|(inf(inity)?)|(nan\w*)|((0x|0X)((\d+\.?\d*)|(\d*\.?\d+))(p[+\-]?\d+)?))", std::regex::icase);
}

49
src/Util/gz_regex.hpp Normal file
View File

@ -0,0 +1,49 @@
#pragma once
#include <regex>
#include <string_view>
namespace gz::re {
struct types {
/// convertible with std::stoi
static const std::regex intT;
/// convertible with std::stoul
static const std::regex uintT;
/// convertible with std::stof
static const std::regex floatT;
};
/**
* @name Regex compability with std::string_view
*/
/// @{
using svmatch = std::match_results<std::string_view::const_iterator>;
using svsub_match = std::sub_match<std::string_view::const_iterator>;
inline std::string_view get_sv(const svsub_match& m) {
return std::string_view(m.first, m.length());
}
/// @details Code taken from u/deleted :) https://www.reddit.com/r/cpp/comments/aqt7a0/status_of_string_view_and_regex/
inline bool regex_match(std::string_view sv, svmatch& m, const std::regex& e, std::regex_constants::match_flag_type flags=std::regex_constants::match_default) {
return std::regex_match(sv.begin(), sv.end(), m, e, flags);
}
/// @details Code taken from u/deleted :) https://www.reddit.com/r/cpp/comments/aqt7a0/status_of_string_view_and_regex/
inline bool regex_match(std::string_view sv, const std::regex& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default) {
return std::regex_match(sv.begin(), sv.end(), e, flags);
}
inline bool regex_search(std::string_view sv, svmatch& m, const std::regex& e, std::regex_constants::match_flag_type flags=std::regex_constants::match_default) {
return std::regex_search(sv.begin(), sv.end(), m, e, flags);
}
inline bool regex_search(std::string_view sv, const std::regex& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default) {
return std::regex_search(sv.begin(), sv.end(), e, flags);
}
/// @}
}
/**
* @file
* @brief Utility for using regex with std::string_view and some regular expressions
*/

125
src/Util/util.cpp Normal file
View File

@ -0,0 +1,125 @@
#include "util.hpp"
#include "gz_regex.hpp"
namespace gz::util {
//
// Type Conversion
//
bool isInt(std::string& s) {
return std::regex_match(s, re::types::intT);
}
bool isInt(std::string_view& s) {
return re::regex_match(s, re::types::intT);
}
int getInt(std::string& s, int fallback) {
try {
fallback = std::stoi(s);
}
catch (std::invalid_argument& e) {}
return fallback;
}
bool isUInt(std::string& s) {
return std::regex_match(s, re::types::uintT);
}
bool isUInt(std::string_view& s) {
return re::regex_match(s, re::types::uintT);
}
unsigned int getUnsignedInt(std::string& s, unsigned int fallback) {
try {
fallback = std::stoul(s);
}
catch (std::invalid_argument& e) {}
return fallback;
}
double getDouble(std::string& s, double fallback) {
try {
fallback = std::stod(s);
}
catch (std::invalid_argument& e) {}
return fallback;
}
bool isFloal(std::string& s) {
return std::regex_match(s, re::types::floatT);
}
bool isFloat(std::string_view& s) {
return re::regex_match(s, re::types::floatT);
}
float getFloat(std::string& s, float fallback) {
try {
fallback = std::stof(s);
}
catch (std::invalid_argument& e) {}
return fallback;
}
bool getBool(std::string& s, bool fallback) {
if (s == "true" or s == "True" or s == "1") {
fallback = true;
}
return fallback;
}
std::string getString(std::string s, std::string fallback) {
if (s == "") { return fallback; }
else { return s; }
}
// int = 0, double = 1, string = 2
std::variant<std::string, int, double, bool> getVariant(std::string value, Type type, bool bFallback, int iFallback, double dFallback, const char* sFallback) {
std::variant<std::string, int, double, bool> val = value;
/* cout << "id-attr" << id << attr << "val: " << std::get<string>(val); */
switch (type) {
// to integer
case INT:
val = getInt(value, iFallback);
break;
case DOUBLE:
val = getDouble(value, dFallback);
break;
case BOOL:
val = getBool(value, bFallback);
break;
default:
val = getString(value, sFallback);
break;
}
return val;
}
std::vector<std::string> splitStringInVector(std::string& s, char separator) {
// remove linebreaks from the end
if (*(s.end()) == '\n') { s.erase(s.end()); }
/* std::unique_ptr<std::unordered_map<Entity, std::string>> params (new std::unordered_map<Entity, std::string>); */
std::vector<std::string> v;
std::stringstream ss(s);
std::string temp;
while (std::getline(ss, temp, separator)) {
// if has "=": store latter part in vector
if (temp.find("=") != std::string::npos) {
int eqPos = temp.find("=");
v.emplace_back(temp.substr(eqPos + 1, temp.length()));
}
else {
v.emplace_back(temp);
}
}
return v;
}
} // namespace gz::util

129
src/Util/util.hpp Normal file
View File

@ -0,0 +1,129 @@
#pragma once
#include <string>
#include <vector>
#include <unordered_map>
#include <variant>
namespace gz::util {
//
// Type conversion
//
enum Type {
UINT, INT, DOUBLE, FLOAT, STRING, BOOL,
};
bool isInt(std::string& s);
bool isInt(std::string_view& s);
int getInt(std::string& s, int fallback=0);
inline int getInt(std::string&& s, int fallback=0) { return getInt(s, fallback); }
/**
* @todo Find a way to convert string_view to int without creating a string from it
*/
inline int getInt(std::string_view s, int fallback=0) { return getInt(std::string(s), fallback); }
bool isUInt(std::string& s);
bool isUInt(std::string_view& s);
unsigned int getUnsignedInt(std::string& s, unsigned int fallback=0);
inline unsigned int getUnsignedInt(std::string&& s, unsigned int fallback=0) { return getUnsignedInt(s, fallback); }
inline unsigned int getUnsignedInt(std::string_view s, unsigned int fallback=0) { return getUnsignedInt(std::string(s), fallback); }
double getDouble(std::string& s, double fallback=0);
inline double getDouble(std::string&& s, double fallback=0) { return getDouble(s, fallback); }
inline double getDouble(std::string_view s, double fallback=0) { return getDouble(std::string(s), fallback); }
bool isFloat(std::string& s);
bool isFloat(std::string_view& s);
float getFloat(std::string& s, float fallback=0);
inline float getFloat(std::string&& s, float fallback=0) { return getDouble(s, fallback); }
inline float getFloat(std::string_view s, float fallback=0) { return getDouble(std::string(s), fallback); }
bool getBool(std::string& s, bool fallback=false);
inline bool getBool(std::string&& s, bool fallback=false) { return getBool(s, fallback); }
inline bool getBool(std::string_view s, bool fallback=false) { return getBool(std::string(s), fallback); }
/**
* @brief Returns the string or fallback if string is empty.
*/
std::string getString(std::string s, std::string fallback="none");
/**
* @brief Converts the given string to the requested type and puts returns it in a variant
* @details
* Tries to convert the string to the specified type.
* If that fails a default value is returned.
* This is either 1 for int or double or "none" for strings.
*
* @param value String which should be converted
* @param type Datatype: 0 = int, 1 = double, 2 = string (default when wrong numer is given)
*
* @returns Variant containing the value in the given datatype.
* @warning Make sure to use the correct type when extracting the value from the returned variant!
*/
std::variant<std::string, int, double, bool> getVariant(std::string value, Type type=STRING, bool bFallback=false, int iFallback=0, double dFallback=0, const char* sFallback="none");
//
// INDEX UTILITY
//
template<std::unsigned_integral I, std::unsigned_integral S>
inline void incrementIndex(I& i, const S containerSize) {
if (i < containerSize - 1) { i++; }
else { i = 0; }
}
template<std::unsigned_integral I, std::unsigned_integral S>
inline void decrementIndex(I& i, const S containerSize) {
if (i > 0) { i--; }
else { i = containerSize - 1; }
}
template<std::unsigned_integral I, std::unsigned_integral S>
inline I getIncrementedIndex(const I i, const S containerSize) {
if (i < containerSize - 1) { return i + 1; }
else { return 0; }
}
template<std::unsigned_integral I, std::unsigned_integral S>
inline I getDecrementedIndex(const I i, const S containerSize) {
if (i > 0) { return i - 1; }
else { return containerSize - 1; }
}
/// Make wrap incices around: i = size + 2 -> i = 2, i = -2 -> i = size - 2
template<std::integral I, std::unsigned_integral S>
size_t getValidIndex(const I i, const S containerSize) {
if (i < 0) {
return containerSize - (-i) % containerSize - 1;
}
else if (i >= static_cast<int>(containerSize)) {
return i % containerSize;
}
return i;
}
//
// STRING
//
std::vector<std::string> splitStringInVector(std::string& s, char separator = '|');
/**
* @name Map with string type as key, works with strings, string_view and char*
* @{
*/
struct string_hash
{
using hash_type = std::hash<std::string_view>;
using is_transparent = void;
size_t operator()(const char* str) const { return hash_type{}(str); }
size_t operator()(std::string_view str) const { return hash_type{}(str); }
size_t operator()(std::string const& str) const { return hash_type{}(str); }
};
template<typename T>
using string_map = std::unordered_map<std::string, T, util::string_hash, std::equal_to<>>;
} // namespace gz::util
#undef umap
/**
* @file
* @brief Various utilites
*/

72
src/log.cpp Normal file
View File

@ -0,0 +1,72 @@
#include "log.hpp"
#include <filesystem>
#include <fstream>
#include <ctime>
#include <SFML/System/Vector2.hpp>
namespace gz {
const char* COLORS[] = {
"\033[0m", // RESET
"\033[30m", // BLACK
"\033[31m", // RED
"\033[32m", // GREEN
"\033[33m", // YELLOW
"\033[34m", // BLUE
"\033[35m", // MAGENTA
"\033[36m", // CYAN
"\033[37m", // WHITE
"\033[1;30m", // BBLACK
"\033[1;31m", // BRED
"\033[1;32m", // BGREEN
"\033[1;33m", // BYELLOW
"\033[1;34m", // BBLUE
"\033[1;35m", // BMAGENTA
"\033[1;36m", // BCYAN
"\033[1;37m", // BWHITE
};
#ifdef LOG_MULTITHREAD
std::mutex Log::mtx;
#endif
Log::Log(std::string logfile, bool showLog, bool storeLog, std::string&& prefix_, Color prefixColor)
: showLog(showLog), storeLog(storeLog), prefixColor(prefixColor), prefix(prefix_ + ": "), prefixLength(prefix.size() + TIMESTAMP_CHAR_COUNT - 1) {
// store the absolute path to the logfile
logFile = std::string(std::filesystem::current_path().parent_path()) + "/logs/" + logfile;
log("Initialising log with settings: logFile: " + logFile +
", showLog - " + boolToString(showLog) + ", storeLog - " + boolToString(storeLog));
}
Log::~Log() {
if (storeLog) { writeLog(); }
}
char* Log::getTime() {
std::time_t t = std::time(0);
struct std::tm *tmp;
tmp = std::localtime(&t);
//returs the date and time: yyyy-mm-dd hh:mm:ss:
std::strftime(time, sizeof(time), "%F %T: ", tmp);
return time;
}
void Log::writeLog() {
std::ofstream file(logFile);
if (file.is_open()) {
for (std::string message : logArray) {
file << message;
}
std::string message = getTime();
message += "Written log to file: " + logFile + "\n";
file << message;
std::cout << message;
}
else {
std::cout << COLORS[RED] << "LOG ERROR: " << COLORS[RESET] << "Could not open file '" << logFile << "'." << '\n';
}
file.close();
}
} // namespace gz

345
src/log.hpp Normal file
View File

@ -0,0 +1,345 @@
#pragma once
#define LOG_MULTITHREAD
#include <iostream>
#include <string>
#include <concepts>
#include <ranges>
#include <unordered_map>
#ifdef LOG_MULTITHREAD
#include <mutex>
#endif
namespace gz {
inline const char* boolToString(bool b) {
return b ? "true" : "false";
}
const int logLength = 100;
constexpr unsigned int TIMESTAMP_CHAR_COUNT = 22;
constexpr unsigned int POSTPREFIX_CHAR_COUNT = 2;
//
// CONCEPTS
//
/// is std::string or convertible to std::string
template<typename T>
concept Stringy = std::same_as<T, std::string> || std::convertible_to<T, std::string_view>;
/// has .to_string() member
template<typename T>
concept HasToString = !Stringy<T> && requires(T t) { { t.to_string() }-> Stringy; };
/// works with std::to_string(), except bool
template<typename T>
concept WorksToString = !std::same_as<T, bool> && !Stringy<T> && !HasToString<T> && requires(T t) { { std::to_string(t) } -> Stringy; };
/// string-like, has .to_string() member, works with std::to_string() or bool
template<typename T>
concept PrintableNoPtr = Stringy<T> || HasToString<T> || WorksToString<T> || std::same_as<T, bool>;
template<typename T>
concept Printable = PrintableNoPtr<T> || requires(T t) { { *(t.get()) } -> PrintableNoPtr; };
/// Type having printable .x and .y members
template<typename T>
concept Vector2Printable = !Printable<T> &&
requires(T t) { { t.x } -> Printable; { t.y } -> Printable; };
/// Pair having printable elements
template<typename T>
concept PairPrintable = !Vector2Printable<T> && !Printable<T> &&
requires(T p) { { p.first } -> Printable; } && (requires(T p){ { p.second } -> Printable; } || requires(T p){ { p.second } -> Vector2Printable; });
/// Container having printable elements
template<typename T>
concept ContainerPrintable = !Printable<T> && !Vector2Printable<T> && !PairPrintable<T> &&
std::ranges::forward_range<T> && (Printable<std::ranges::range_reference_t<T>> || Vector2Printable<std::ranges::range_reference_t<T>>);
/// Container having printable pairs
template<typename T>
concept MapPrintable = !Printable<T> && !Vector2Printable<T> && !ContainerPrintable<T> &&
std::ranges::forward_range<T> && PairPrintable<std::ranges::range_reference_t<T>>;
template<typename T>
concept LogableNotPointer = Printable<T> || Vector2Printable<T> || PairPrintable<T> || ContainerPrintable<T> || MapPrintable<T>;
template<typename T>
concept LogableSmartPointer = requires(T t) { { *(t.get()) } -> LogableNotPointer; };
//
// COLORS
//
/// Colors to be used in Log::clog
enum Color {
RESET, BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, BBLACK, BRED, BGREEN, BYELLOW, BBLUE, BMAGENTA, BCYAN, BWHITE
};
extern const char* COLORS[];
//
// LOG
//
/**
* @brief Define types that can be logged with Log
* @details
* As of now you can log type T with instance t:
* -# Any string-like type
* -# Any type that works with std::to_string()
* -# Any type that has a to_string() member that returns a string
* -# Any type with t.x and t.y, provided t.x and t.y satisfy one of 1-3
* -# Any type with t.first, t.second provided t.first satisfies one of 1-3 and t.second satisfies 1-4
* -# Any type that has a forward_iterator which references any one of 1-5
*
* 1-6 include for example:
* - int, float, bool...
* - std::vector<std::string>, std::list<unsigned int>
* - std::map<A, vec2<float>> if A.to_string() returns a string
* - ...
*/
template<typename T>
concept Logable = LogableNotPointer<T> || LogableSmartPointer<T>;
template<typename T>
class vec2; // defined in gz_math.hpp
/**
* @brief Manages printing messages to stdout and to logfiles.
* @details
* @subsection log_threads Thread safety
* Log can use a static mutex for thread safety. To use this feature, you have to #define LOG_MULTITHREAD at the top of log.hpp.
* Note that log uses the default std::cout buffer, so you should make sure it is not being used while logging something.
*/
class Log {
public:
/**
* @brief Creates a log object, which can print messages to stdout and/or write them to a log file
* @details By creating multiple instances with different parameters, logs can be easily turned on/off for different usages.
*
* @param logfile: Name of the file in the logs folder
* @param showLog: Wether to print the messages to stdout
* @param storeLog: Wether to save the messages to the logfile
* @param prefix: A prefix that comes between the timestamp and the message. ": " is automatically appended to the prefix
* @param prefixColor: The color of the prefix
*
* @note Colors will only be shown when written to stdout, not in the logfile.
*/
Log(std::string logfile="log.log", bool showLog=true, bool storeLog=true, std::string&& prefix="", Color prefixColor=RESET);
~Log();
/**
* @brief Logs a message
* @details Depending on the settings of the log instance, the message will be printed to stdout and/or written to the logfile.
* The current date and time is placed before the message.
* The message will look like this:
* <time>: <prefix>: <message>
* where time will be white, prefix in prefixColor and message white.
* @param args Any number of arguments that satisfy concept Logable
*
*/
template<Logable... Args>
void log(Args&&... args) {
#ifdef LOG_MULTITHREAD
mtx.lock();
#endif
logArray[iter] = getTime();
logArray[iter] += prefix;
vlog(" ", std::forward<Args>(args)...);
logArray[iter] += "\n";
std::cout << std::string_view(logArray[iter].c_str(), TIMESTAMP_CHAR_COUNT - 1) <<
COLORS[prefixColor] << prefix << COLORS[RESET] <<
std::string_view(logArray[iter].begin() + prefixLength, logArray[iter].end());
if (++iter >= logLength) {
iter = 0;
writeLog();
}
#ifdef LOG_MULTITHREAD
mtx.unlock();
#endif
}
/**
* @brief Logs a message. Overload for convenience, same behavior as log()
*/
template<Logable... Args>
void operator() (Args&&... args) {
log(std::forward<Args>(args)...);
}
/**
* @brief Log an error
* @details Prints the message with a red "Error: " prefix.
* The message will look like this:
* <time>: <prefix>: Error: <message>
* where time will be white, prefix in prefixColor, Error in red and message white.
* @param args Any number of arguments that satisfy concept Logable
*/
template<Logable... Args>
void error(Args&&... args) {
clog(RED, "Error", WHITE, std::forward<Args>(args)...);
}
/**
* @brief Log a warnign
* @details Prints the message with a yellow "Warning: " prefix.
* The message will look like this:
* <time>: <prefix>: Warning: <message>
* where time will be white, prefix in prefixColor, Warning in yellow and message white.
* @param args Any number of arguments that satisfy concept Logable
*/
template<Logable... Args>
void warning(Args&&... args) {
clog(YELLOW, "Warning", WHITE, std::forward<Args>(args)...);
}
/**
* @brief Log a message in a certain color and with a colored type
* @details
* The message will look like this:
* <time>: <prefix>: <type>: <message>
* where time will be white, prefix in prefixColor, type in typeColor and message in messageColor
* @param args Any number of arguments that satisfy concept Logable
*/
template<Logable... Args>
void clog(Color typeColor, std::string&& type, Color messageColor, Args&&... args) {
#ifdef LOG_MULTITHREAD
mtx.lock();
#endif
logArray[iter] = getTime();
logArray[iter] += prefix + ": " + type + ": ";
vlog(" ", std::forward<Args>(args)...);
logArray[iter] += "\n";
std::cout << std::string_view(logArray[iter].c_str(), TIMESTAMP_CHAR_COUNT - 1) <<
COLORS[prefixColor] << prefix << COLORS[typeColor] <<
std::string_view(logArray[iter].begin() + prefixLength + POSTPREFIX_CHAR_COUNT, logArray[iter].begin() + prefixLength + type.size() + 2 * POSTPREFIX_CHAR_COUNT) <<
COLORS[messageColor] << std::string_view(logArray[iter].begin() + prefixLength + type.size() + 2 * POSTPREFIX_CHAR_COUNT, logArray[iter].end()) << COLORS[RESET];
if (++iter >= logLength) {
iter = 0;
writeLog();
}
#ifdef LOG_MULTITHREAD
mtx.unlock();
#endif
}
private:
template<Stringy T, Logable... Args>
void vlog(const char* appendChars, T&& t, Args&&... args) {
logArray[iter] += t;
logArray[iter] += appendChars;
vlog(" ", std::forward< Args>(args)...);
}
template<HasToString T, Logable... Args>
void vlog(const char* appendChars, T&& t, Args&&... args) {
logArray[iter] += t.to_string();
logArray[iter] += appendChars;
vlog(" ", std::forward< Args>(args)...);
}
template<WorksToString T, Logable... Args>
void vlog(const char* appendChars, T&& t, Args&&... args) {
logArray[iter] += std::to_string(t);
logArray[iter] += appendChars;
vlog(" ", std::forward< Args>(args)...);
}
template<typename T, Logable... Args>
requires(std::same_as<T, bool>)
void vlog(const char* appendChars, T&& b, Args&&... args) {
logArray[iter] += boolToString(b);
logArray[iter] += appendChars;
vlog(" ", std::forward< Args>(args)...);
}
template<Vector2Printable V, Logable... Args>
void vlog(const char* appendChars, V&& v, Args&&... args) {
logArray[iter] += "(";
vlog("", v.x);
logArray[iter] += ", ";
vlog("", v.y);
logArray[iter] += ")";
logArray[iter] += appendChars;
vlog(" ", std::forward< Args>(args)...);
}
template<PairPrintable P, Logable... Args>
void vlog(const char* appendChars, P&& p, Args&&... args) {
logArray[iter] += "(";
vlog("", p.first);
logArray[iter] += ", ";
vlog("" ,p.second);
logArray[iter] += ")";
logArray[iter] += appendChars;
vlog(" ", std::forward< Args>(args)...);
}
template<ContainerPrintable T, Logable... Args>
void vlog(const char* appendChars, T&& t, Args&&... args) {;
logArray[iter] += "[";
for (auto it = t.begin(); it != t.end(); it++) {
vlog(", ", *it);
}
logArray[iter] += "]";
logArray[iter] += appendChars;
vlog(" ", std::forward< Args>(args)...);
}
template<MapPrintable T, Logable... Args>
void vlog(const char* appendChars, T&& t, Args&&... args) {
logArray[iter] += "{";
for (const auto& [k, v] : t) {
vlog(": ", k);
vlog(", ", v);
}
logArray[iter] += "}";
logArray[iter] += appendChars;
vlog(" ", std::forward<Args>(args)...);
}
/// Log any logable element that is stored in a pointer
template<LogableSmartPointer T, Logable... Args>
void vlog(const char* appendChars, T&& t, Args&&... args) {
vlog("", *t);
vlog(" ", std::forward<Args>(args)...);
}
void vlog(const char* appendChars) {};
private:
std::array<std::string, logLength> logArray;
size_t iter;
std::string logFile;
bool showLog;
bool storeLog;
void writeLog();
Color prefixColor;
std::string prefix;
std::string::size_type prefixLength;
char time[TIMESTAMP_CHAR_COUNT];
char* getTime();
#ifdef LOG_MULTITHREAD
static std::mutex mtx;
#endif
};
extern Log genLog;
extern Log gameLog;
extern Log engLog;
}
/**
* @file
* @brief A logger capable of logging lots of different types and containers to stdout and/or a logfile.
*/