Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
buffer.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017 Roc Streaming authors
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7  */
8 
9 //! @file roc_core/buffer.h
10 //! @brief Buffer.
11 
12 #ifndef ROC_CORE_BUFFER_H_
13 #define ROC_CORE_BUFFER_H_
14 
15 #include "roc_core/align_ops.h"
16 #include "roc_core/macro_helpers.h"
17 #include "roc_core/ref_counted.h"
18 #include "roc_core/slab_pool.h"
19 #include "roc_core/stddefs.h"
20 
21 namespace roc {
22 namespace core {
23 
24 //! Fixed-size dynamically-allocated buffer.
25 //!
26 //! @tparam T defines element type.
27 //!
28 //! @remarks
29 //! Buffer size is fixed, but determined at runtime, not compile time.
30 //! It is defined by the pool that allocates the buffer.
31 //! User typically works with buffers via Slice, which holds a reference
32 //! to buffer and points to a variable-size subset of its memory.
33 //!
34 //! @see BufferFactory, Slice.
35 template <class T> class Buffer : public RefCounted<Buffer<T>, PoolAllocation> {
36 public:
37  //! Initialize empty buffer.
38  Buffer(IPool& buffer_pool, size_t buffer_size)
39  : RefCounted<Buffer<T>, PoolAllocation>(buffer_pool)
40  , size_(buffer_size) {
41  new (data()) T[size()];
42  }
43 
44  //! Get number of elements in buffer.
45  size_t size() const {
46  return size_;
47  }
48 
49  //! Get buffer data.
50  T* data() {
51  return (T*)data_;
52  }
53 
54  //! Get pointer to buffer from the pointer to its data.
55  static Buffer* container_of(void* data) {
56  return ROC_CONTAINER_OF(data, Buffer, data_);
57  }
58 
59 private:
60  const size_t size_;
61  AlignMax data_[];
62 };
63 
64 } // namespace core
65 } // namespace roc
66 
67 #endif // ROC_CORE_BUFFER_H_
Alignment operations.
Fixed-size dynamically-allocated buffer.
Definition: buffer.h:35
static Buffer * container_of(void *data)
Get pointer to buffer from the pointer to its data.
Definition: buffer.h:55
Buffer(IPool &buffer_pool, size_t buffer_size)
Initialize empty buffer.
Definition: buffer.h:38
T * data()
Get buffer data.
Definition: buffer.h:50
size_t size() const
Get number of elements in buffer.
Definition: buffer.h:45
Memory pool interface.
Definition: ipool.h:23
Allocation policy for objects allocated using IPool.
Base class for object with reference counter.
Definition: ref_counted.h:40
Helper macros.
#define ROC_CONTAINER_OF(ptr, type, member)
Cast a member of a structure out to the containing structure.
Definition: macro_helpers.h:37
Root namespace.
Base class for object with reference counter.
Memory pool.
Commonly used types and functions.
Maximum aligned data unit.
Definition: align_ops.h:21