1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "SimpleBuffer.h"
13 nsresult
SimpleBuffer::Write(char* src
, size_t len
) {
14 NS_ASSERT_OWNINGTHREAD(SimpleBuffer
);
15 if (NS_FAILED(mStatus
)) {
20 SimpleBufferPage
* p
= mBufferList
.getLast();
21 if (p
&& (p
->mWriteOffset
== SimpleBufferPage::kSimpleBufferPageSize
)) {
22 // no room.. make a new page
26 p
= new (fallible
) SimpleBufferPage();
28 mStatus
= NS_ERROR_OUT_OF_MEMORY
;
31 mBufferList
.insertBack(p
);
34 SimpleBufferPage::kSimpleBufferPageSize
- p
->mWriteOffset
;
35 size_t toWrite
= std::min(roomOnPage
, len
);
36 memcpy(p
->mBuffer
+ p
->mWriteOffset
, src
, toWrite
);
39 p
->mWriteOffset
+= toWrite
;
40 mAvailable
+= toWrite
;
45 size_t SimpleBuffer::Read(char* dest
, size_t maxLen
) {
46 NS_ASSERT_OWNINGTHREAD(SimpleBuffer
);
47 if (NS_FAILED(mStatus
)) {
52 for (SimpleBufferPage
* p
= mBufferList
.getFirst(); p
&& (rv
< maxLen
);
53 p
= mBufferList
.getFirst()) {
54 size_t avail
= p
->mWriteOffset
- p
->mReadOffset
;
55 size_t toRead
= std::min(avail
, (maxLen
- rv
));
56 memcpy(dest
+ rv
, p
->mBuffer
+ p
->mReadOffset
, toRead
);
58 p
->mReadOffset
+= toRead
;
59 if (p
->mReadOffset
== p
->mWriteOffset
) {
65 MOZ_ASSERT(mAvailable
>= rv
);
70 size_t SimpleBuffer::Available() {
71 NS_ASSERT_OWNINGTHREAD(SimpleBuffer
);
72 return NS_SUCCEEDED(mStatus
) ? mAvailable
: 0;
75 void SimpleBuffer::Clear() {
76 NS_ASSERT_OWNINGTHREAD(SimpleBuffer
);
78 while ((p
= mBufferList
.popFirst())) {
85 } // namespace mozilla