ZeroBuf  0.1.0
ZeroBuf is a replacement for FlatBuffers
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
BaseVector.h
1 
2 /* Copyright (c) 2015, Human Brain Project
3  * Stefan.Eilemann@epfl.ch
4  */
5 
6 #ifndef ZEROBUF_BASEVECTOR_H
7 #define ZEROBUF_BASEVECTOR_H
8 
9 #include <zerobuf/Types.h>
10 
11 #include <cstring> // memcmp
12 #include <stdexcept> // std::runtime_error
13 #include <typeinfo> // typeid
14 #include <ostream>
15 
16 namespace zerobuf
17 {
18 /*
19  * Base class for const and non-const vectors.
20  *
21  * @param A allocator type (needed for constness)
22  * @param T element type
23  */
24 template< class A, class T >
26 {
27 public:
32  BaseVector( A* alloc, size_t index );
33  virtual ~BaseVector() {}
34 
35  const T& operator[] ( size_t index ) const;
36 
37  bool empty() const { return _getSize() == 0; }
38  uint64_t size() const { return _getSize() / sizeof(T); }
39  const T* data() const
40  { return _parent->template getDynamic< const T >( _index ); }
41 
42  bool operator == ( const BaseVector& rhs ) const;
43  bool operator != ( const BaseVector& rhs ) const;
44 
45 protected:
46  A* _parent;
47  const size_t _index;
48 
49  BaseVector();
50  size_t _getSize() const { return _parent->getDynamicSize( _index ); }
51 };
52 
53 // Implementation
54 template< class A, class T > inline
55 BaseVector< A, T >::BaseVector( A* alloc, const size_t index )
56  : _parent( alloc )
57  , _index( index )
58 {}
59 
60 template< class A, class T > inline
61 const T& BaseVector< A, T >::operator[] ( const size_t index ) const
62 {
63  if( index >= size( ))
64  throw std::runtime_error( "Vector out of bounds read" );
65 
66  return data()[ index ];
67 }
68 
69 template< class A, class T > inline
70 bool BaseVector< A, T >::operator == ( const BaseVector& rhs ) const
71 {
72  if( this == &rhs )
73  return true;
74  const size_t size_ = _getSize();
75  if( size_ == 0 || size_ != rhs._getSize( ))
76  return false;
77  return ::memcmp( data(), rhs.data(), size_ ) == 0;
78 }
79 
80 template< class A, class T > inline
81 bool BaseVector< A, T >::operator != ( const BaseVector& rhs ) const
82 {
83  return !(operator == ( rhs ));
84 }
85 
86 template< class A, class T > inline
87 std::ostream& operator << ( std::ostream& os,
88  const BaseVector< A, T >& vector )
89 {
90  return os << typeid( vector ).name() << " of size " << vector.size();
91 }
92 
93 }
94 
95 #endif