Modernize code base

This commit is contained in:
topjohnwu
2018-11-07 02:10:38 -05:00
parent ca35a9681f
commit 7c12bf7fa1
21 changed files with 421 additions and 287 deletions

View File

@@ -0,0 +1,39 @@
#pragma once
#include <string.h>
/* A wrapper around char array */
class CharArray {
public:
CharArray();
CharArray(const char *s);
CharArray(const CharArray &s);
CharArray(size_t i);
~CharArray();
CharArray &operator=(const CharArray &s);
CharArray &operator=(CharArray &&s);
CharArray &operator=(const char *s);
operator char *();
operator const char *() const;
bool operator==(char *s) const;
bool operator==(const char *s) const;
bool operator!=(const char *s) const;
int compare(const char *s) const;
int compare(const char *s, size_t len) const;
bool starts_with(const char *s) const;
bool contains(const char *s) const;
bool empty() const;
const char *c_str() const;
size_t length() const;
size_t size() const;
/* These 2 ops are incompatible with implicit char* conversion */
// char &operator[](size_t i);
// const char &operator[](size_t i) const;
private:
char *_buf;
size_t _size;
};

View File

@@ -1,6 +1,7 @@
#pragma once
#include <stdlib.h>
#include "cpputils.h"
template <class T>
class Array {
@@ -72,7 +73,7 @@ public:
if (_capacity) {
_data = new T[_capacity];
for(int i = 0; i < _size; ++i)
_data[i] = (T&&) a[i];
_data[i] = utils::move(a[i]);
}
return *this;
}
@@ -101,7 +102,7 @@ public:
void push_back(T&& x) {
if(_size == _capacity)
expand();
_data[_size] = (T&&) x;
_data[_size] = utils::move(x);
++_size;
}
@@ -114,7 +115,7 @@ public:
if (_size == 0 || d < _data || d >= _data + _size)
return false;
for (; d < _data + _size - 1; ++d)
*d = (T&&) *(d + 1);
*d = utils::move(*(d + 1));
--_size;
return true;
@@ -130,9 +131,16 @@ public:
return false;
}
void clear() { _size = 0; }
void clear(bool dealloc = false) {
_size = 0;
if (dealloc) {
_capacity = 0;
delete [] _data;
_data = nullptr;
}
}
void sort() const {
void sort() {
qsort(_data, _size, sizeof(T), compare);
}
@@ -161,7 +169,7 @@ private:
T* temp = _data;
_data = new T[_capacity];
for(int i = 0; i < _size; ++i)
_data[i] = (T&&) temp[i];
_data[i] = utils::move(temp[i]);
delete [] temp;
}
};

View File

@@ -0,0 +1,12 @@
#pragma once
namespace utils {
template< class T > struct remove_reference {typedef T type;};
template< class T > struct remove_reference<T&> {typedef T type;};
template< class T > struct remove_reference<T&&> {typedef T type;};
template< class T >
constexpr typename remove_reference<T>::type&& move( T&& t ) noexcept {
return static_cast<typename remove_reference<T>::type&&>(t);
}
}

View File

@@ -12,9 +12,15 @@
#include <sys/stat.h>
#ifdef __cplusplus
// C++ only
#include "array.h"
int file_to_array(const char* filename, Array<char *> &arr);
#include "CharArray.h"
#include "cpputils.h"
int file_to_array(const char *filename, Array<CharArray> &arr);
char *strdup2(const char *s, size_t *size = nullptr);
extern "C" {
#endif