2 * Copyright 2009, Haiku, Inc. All Rights Reserved.
3 * Distributed under the terms of the MIT License.
6 * Bruno Albuquerque, bga@bug-br.org.br
9 #include "DynamicBuffer.h"
17 #include <SupportDefs.h>
21 DynamicBuffer::DynamicBuffer(size_t initialSize
) :
28 fBuffer
= new (std::nothrow
) unsigned char[initialSize
];
29 if (fBuffer
!= NULL
) {
30 fBufferSize
= initialSize
;
36 DynamicBuffer::~DynamicBuffer()
45 DynamicBuffer::DynamicBuffer(const DynamicBuffer
& buffer
) :
54 status_t result
= _GrowToFit(buffer
.fBufferSize
, true);
56 memcpy(fBuffer
, buffer
.fBuffer
, fBufferSize
);
57 fDataStart
= buffer
.fDataStart
;
58 fDataEnd
= buffer
.fDataEnd
;
66 DynamicBuffer::InitCheck() const
73 DynamicBuffer::Write(const void* data
, size_t size
)
78 status_t result
= _GrowToFit(size
);
82 memcpy(fBuffer
+ fDataEnd
, data
, size
);
90 DynamicBuffer::Read(void* data
, size_t size
)
95 size
= std::min(size
, Size());
99 memcpy(data
, fBuffer
+ fDataStart
, size
);
102 if (fDataStart
== fDataEnd
)
103 fDataStart
= fDataEnd
= 0;
110 DynamicBuffer::Data() const
112 return fBuffer
+ fDataStart
;
117 DynamicBuffer::Size() const
119 return fDataEnd
- fDataStart
;
124 DynamicBuffer::BytesRemaining() const
126 return fBufferSize
- fDataEnd
;
131 DynamicBuffer::PrintToStream()
133 printf("Current buffer size : %ld\n", fBufferSize
);
134 printf("Data start position : %ld\n", fDataStart
);
135 printf("Data end position : %ld\n", fDataEnd
);
136 printf("Bytes wasted : %ld\n", fDataStart
);
137 printf("Bytes available : %ld\n", fBufferSize
- fDataEnd
);
142 DynamicBuffer::_GrowToFit(size_t size
, bool exact
)
144 if (size
<= fBufferSize
- fDataEnd
)
149 newSize
= (fBufferSize
+ size
) * 2;
153 unsigned char* newBuffer
= new (std::nothrow
) unsigned char[newSize
];
154 if (newBuffer
== NULL
)
157 if (fDataStart
!= fDataEnd
)
158 memcpy(newBuffer
, fBuffer
+ fDataStart
, fDataEnd
- fDataStart
);
162 fDataEnd
-= fDataStart
;
164 fBufferSize
= newSize
;