2 * Copyright 2006-2010, Haiku, Inc. All Rights Reserved.
3 * Distributed under the terms of the MIT License.
5 #ifndef NET_BUFFER_UTILITIES_H
6 #define NET_BUFFER_UTILITIES_H
9 #include <net_buffer.h>
12 extern net_buffer_module_info
* gBufferModule
;
15 class NetBufferModuleGetter
{
17 static net_buffer_module_info
*Get() { return gBufferModule
; }
21 //! A class to access a field safely across node boundaries
22 template<typename Type
, int Offset
, typename Module
= NetBufferModuleGetter
>
23 class NetBufferFieldReader
{
25 NetBufferFieldReader(net_buffer
* buffer
)
29 fStatus
= Module::Get()->direct_access(fBuffer
, Offset
, sizeof(Type
),
31 if (fStatus
!= B_OK
) {
32 fStatus
= Module::Get()->read(fBuffer
, Offset
, &fDataBuffer
,
38 status_t
Status() const
48 Type
* operator->() const
53 Type
& operator*() const
60 if (fBuffer
== NULL
|| fStatus
< B_OK
)
63 if (fData
== &fDataBuffer
)
64 Module::Get()->write(fBuffer
, Offset
, fData
, sizeof(Type
));
70 NetBufferFieldReader()
81 //! Writes back any changed data on destruction
82 template<typename Type
, int Offset
, typename Module
= NetBufferModuleGetter
>
83 class NetBufferField
: public NetBufferFieldReader
<Type
, Offset
, Module
> {
85 NetBufferField(net_buffer
* buffer
)
87 NetBufferFieldReader
<Type
, Offset
, Module
>(buffer
)
93 // Note, "this->" is needed here for GCC4
99 //! Can remove the header from the buffer
100 template<typename Type
, typename Module
= NetBufferModuleGetter
>
101 class NetBufferHeaderReader
: public NetBufferFieldReader
<Type
, 0, Module
> {
103 NetBufferHeaderReader(net_buffer
* buffer
)
105 NetBufferFieldReader
<Type
, 0, Module
>(buffer
)
111 Remove(sizeof(Type
));
114 void Remove(size_t bytes
)
116 if (this->fBuffer
!= NULL
) {
117 Module::Get()->remove_header(this->fBuffer
, bytes
);
118 this->fBuffer
= NULL
;
124 //! Removes the header on destruction
125 template<typename Type
, typename Module
= NetBufferModuleGetter
>
126 class NetBufferHeaderRemover
: public NetBufferHeaderReader
<Type
, Module
> {
128 NetBufferHeaderRemover(net_buffer
* buffer
)
130 NetBufferHeaderReader
<Type
, Module
>(buffer
)
134 ~NetBufferHeaderRemover()
141 //! A class to add a header to a buffer, syncs itself on destruction
142 template<typename Type
, typename Module
= NetBufferModuleGetter
>
143 class NetBufferPrepend
: public NetBufferFieldReader
<Type
, 0, Module
> {
145 NetBufferPrepend(net_buffer
* buffer
, size_t size
= sizeof(Type
))
147 this->fBuffer
= buffer
;
149 this->fStatus
= Module::Get()->prepend_size(buffer
, size
,
150 (void**)&this->fData
);
151 if (this->fStatus
== B_OK
&& this->fData
== NULL
)
152 this->fData
= &this->fDataBuffer
;
162 #endif // NET_BUFFER_UTILITIES_H