From 733a9f0a4ecc80a0e0efca0b4eb7824f0aeced3a Mon Sep 17 00:00:00 2001 From: vng Date: Sun, 13 Feb 2011 13:59:32 +0200 Subject: [PATCH] Add C-style array adapters for reading and writing. --- base/array_adapters.h | 68 +++++++++++++++++++++++++++++++++++++++++++ base/base.pro | 3 +- 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 base/array_adapters.h diff --git a/base/array_adapters.h b/base/array_adapters.h new file mode 100644 index 0000000000..4e1d36c11f --- /dev/null +++ b/base/array_adapters.h @@ -0,0 +1,68 @@ +#pragma once +#include "assert.hpp" + + +namespace detail +{ + template class array_impl + { + protected: + TPtr m_p; + size_t m_size; + + public: + typedef T value_type; + typedef T const & const_reference; + typedef T & reference; + + array_impl(TPtr p, size_t sz) : m_p(p), m_size(sz) {} + + T const & operator[](size_t i) const + { + ASSERT_LESS ( i, m_size, () ); + return m_p[i]; + } + + T const & back() const + { + ASSERT_GREATER ( m_size, 0, () ); + return m_p[m_size-1]; + } + + size_t size() const { return m_size; } + + bool empty() const { return (m_size == 0); } + }; +} + +template class array_read : public detail::array_impl +{ +public: + array_read(T const * p, size_t sz) + : detail::array_impl(p, sz) + { + } +}; + +template +array_read make_read_adapter(TCont const & cont) +{ + return array_read(cont.empty() ? 0 : &cont[0], cont.size()); +} + +template class array_write : public detail::array_impl +{ + size_t m_capacity; + +public: + template explicit array_write(TCont & cont) + : detail::array_impl(cont.empty() ? 0 : &cont[0], 0), m_capacity(cont.size()) + { + } + + void push_back(T const & t) + { + ASSERT_LESS ( m_size, m_capacity, () ); + m_p[m_size++] = t; + } +}; diff --git a/base/base.pro b/base/base.pro index fb368dc151..3001471f36 100644 --- a/base/base.pro +++ b/base/base.pro @@ -59,4 +59,5 @@ HEADERS += \ shared_buffer_manager.hpp \ memory_mapped_file.hpp \ buffer_vector.hpp \ - path_utils.hpp + path_utils.hpp \ + array_adapters.hpp \