libostd/octa/array.hh

80 lines
1.9 KiB
C++
Raw Normal View History

2015-04-21 18:57:20 +02:00
/* Static array implementation for OctaSTD.
*
* This file is part of OctaSTD. See COPYING.md for futher information.
*/
2015-06-28 17:04:49 +02:00
#ifndef OCTA_ARRAY_HH
#define OCTA_ARRAY_HH
2015-04-21 18:57:20 +02:00
#include <stddef.h>
#include "octa/algorithm.hh"
#include "octa/range.hh"
#include "octa/string.hh"
2015-04-21 18:57:20 +02:00
namespace octa {
2015-06-04 00:10:10 +02:00
template<typename T, octa::Size N>
2015-06-04 00:10:10 +02:00
struct Array {
using Size = octa::Size;
using Difference = octa::Ptrdiff;
2015-06-08 01:55:08 +02:00
using Value = T;
using Reference = T &;
using ConstReference = const T &;
using Pointer = T *;
using ConstPointer = const T *;
using Range = octa::PointerRange<T>;
using ConstRange = octa::PointerRange<const T>;
2015-06-04 00:10:10 +02:00
T &operator[](Size i) { return p_buf[i]; }
const T &operator[](Size i) const { return p_buf[i]; }
2015-06-04 00:10:10 +02:00
T *at(Size i) {
if (!in_range(i)) return nullptr;
return &p_buf[i];
}
const T *at(Size i) const {
if (!in_range(i)) return nullptr;
return &p_buf[i];
}
2015-06-04 00:10:10 +02:00
2015-06-04 23:57:06 +02:00
T &front() { return p_buf[0]; }
const T &front() const { return p_buf[0]; }
2015-06-04 00:10:10 +02:00
2015-06-04 23:57:06 +02:00
T &back() { return p_buf[(N > 0) ? (N - 1) : 0]; }
const T &back() const { return p_buf[(N > 0) ? (N - 1) : 0]; }
2015-06-04 00:10:10 +02:00
Size size() const { return N; }
2015-06-14 04:38:08 +02:00
Size max_size() const { return Size(~0) / sizeof(T); }
2015-06-04 00:10:10 +02:00
2015-06-04 23:57:06 +02:00
bool empty() const { return N == 0; }
2015-06-04 00:10:10 +02:00
bool in_range(Size idx) { return idx < N; }
bool in_range(int idx) { return idx >= 0 && Size(idx) < N; }
bool in_range(ConstPointer ptr) {
2015-06-04 23:57:06 +02:00
return ptr >= &p_buf[0] && ptr < &p_buf[N];
2015-06-04 00:10:10 +02:00
}
Pointer data() { return p_buf; }
ConstPointer data() const { return p_buf; }
2015-06-04 00:10:10 +02:00
2015-06-26 22:01:16 +02:00
Range iter() {
return Range(p_buf, p_buf + N);
2015-06-04 00:10:10 +02:00
}
2015-06-26 22:01:16 +02:00
ConstRange iter() const {
return ConstRange(p_buf, p_buf + N);
2015-06-04 00:10:10 +02:00
}
2015-06-26 22:01:16 +02:00
ConstRange citer() const {
2015-06-09 22:18:43 +02:00
return ConstRange(p_buf, p_buf + N);
}
2015-06-04 00:10:10 +02:00
void swap(Array &v) {
2015-06-26 22:01:16 +02:00
octa::swap_ranges(iter(), v.iter());
2015-06-04 00:10:10 +02:00
}
2015-06-04 23:57:06 +02:00
T p_buf[(N > 0) ? N : 1];
2015-06-04 00:10:10 +02:00
};
} /* namespace octa */
2015-04-21 18:57:20 +02:00
#endif