Bug 1837643 [wpt PR 40475] - [RemoveLegacy] GridTrackList::legacy_track_list_, a...
[gecko.git] / netwerk / base / SimpleBuffer.cpp
blob46b8654efa179575144317901ac834eb326b7987
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"
8 #include <algorithm>
10 namespace mozilla {
11 namespace net {
13 nsresult SimpleBuffer::Write(char* src, size_t len) {
14 NS_ASSERT_OWNINGTHREAD(SimpleBuffer);
15 if (NS_FAILED(mStatus)) {
16 return mStatus;
19 while (len > 0) {
20 SimpleBufferPage* p = mBufferList.getLast();
21 if (p && (p->mWriteOffset == SimpleBufferPage::kSimpleBufferPageSize)) {
22 // no room.. make a new page
23 p = nullptr;
25 if (!p) {
26 p = new (fallible) SimpleBufferPage();
27 if (!p) {
28 mStatus = NS_ERROR_OUT_OF_MEMORY;
29 return mStatus;
31 mBufferList.insertBack(p);
33 size_t roomOnPage =
34 SimpleBufferPage::kSimpleBufferPageSize - p->mWriteOffset;
35 size_t toWrite = std::min(roomOnPage, len);
36 memcpy(p->mBuffer + p->mWriteOffset, src, toWrite);
37 src += toWrite;
38 len -= toWrite;
39 p->mWriteOffset += toWrite;
40 mAvailable += toWrite;
42 return NS_OK;
45 size_t SimpleBuffer::Read(char* dest, size_t maxLen) {
46 NS_ASSERT_OWNINGTHREAD(SimpleBuffer);
47 if (NS_FAILED(mStatus)) {
48 return 0;
51 size_t rv = 0;
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);
57 rv += toRead;
58 p->mReadOffset += toRead;
59 if (p->mReadOffset == p->mWriteOffset) {
60 p->remove();
61 delete p;
65 MOZ_ASSERT(mAvailable >= rv);
66 mAvailable -= rv;
67 return 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);
77 SimpleBufferPage* p;
78 while ((p = mBufferList.popFirst())) {
79 delete p;
81 mAvailable = 0;
84 } // namespace net
85 } // namespace mozilla