Skip to content

Commit

Permalink
Add SetChar to emulate std::set<std::string> API
Browse files Browse the repository at this point in the history
  • Loading branch information
czgdp1807 committed Apr 12, 2023
1 parent d377bf9 commit 43bfbae
Showing 1 changed file with 92 additions and 0 deletions.
92 changes: 92 additions & 0 deletions src/libasr/containers.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,49 @@ struct Vec {
#endif
}

template <class Q = T>
typename std::enable_if<std::is_same<Q, char*>::value, bool>::type present(Q x, size_t& index) {
for( size_t i = 0; i < n; i++ ) {
if( strcmp(p[i], x) == 0 ) {
index = i;
return true;
}
}
return false;
}

template <class Q = T>
typename std::enable_if<!std::is_same<Q, char*>::value, bool>::type present(Q x, size_t& index) {
for( size_t i = 0; i < n; i++ ) {
if( p[i] == x ) {
index = i;
return true;
}
}
return false;
}

void erase(T x) {
size_t delete_index;
if( !present(x, delete_index) ) {
return ;
}

for( int64_t i = delete_index; i < (int64_t) n - 1; i++ ) {
p[i] = p[i + 1];
}
if( n >= 1 ) {
n = n - 1;
}
}

void push_back_unique(Allocator &al, T x) {
size_t index;
if( !Vec<T>::present(x, index) ) {
Vec<T>::push_back(al, x);
}
}

void push_back(Allocator &al, T x) {
// This can pass by accident even if reserve() is not called (if
// reserve_called happens to be equal to vec_called_const when Vec is
Expand Down Expand Up @@ -135,6 +178,55 @@ struct Vec {
static_assert(std::is_standard_layout<Vec<int>>::value);
static_assert(std::is_trivial<Vec<int>>::value);

/*
SetChar emulates the std::set<std::string> API
so that it acts as a drop in replacement.
*/
struct SetChar: Vec<char*> {

bool reserved;

SetChar():
reserved(false) {
clear();
}

void clear() {
n = 0;
p = nullptr;
max = 0;
}

void clear(Allocator& al) {
reserve(al, 0);
}

void reserve(Allocator& al, size_t max) {
Vec<char*>::reserve(al, max);
reserved = true;
}

void from_pointer_n_copy(Allocator &al, char** p, size_t n) {
reserve(al, n);
for (size_t i = 0; i < n; i++) {
push_back(al, p[i]);
}
}

void from_pointer_n(char** p, size_t n) {
Vec<char*>::from_pointer_n(p, n);
reserved = true;
}

void push_back(Allocator &al, char* x) {
if( !reserved ) {
reserve(al, 0);
}

Vec<char*>::push_back_unique(al, x);
}
};

// String implementation (not null-terminated)
struct Str {
size_t n;
Expand Down

0 comments on commit 43bfbae

Please sign in to comment.