• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The Dawn Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "dawn_wire/WireDeserializeAllocator.h"
16 
17 #include <algorithm>
18 
19 namespace dawn_wire {
WireDeserializeAllocator()20     WireDeserializeAllocator::WireDeserializeAllocator() {
21         Reset();
22     }
23 
~WireDeserializeAllocator()24     WireDeserializeAllocator::~WireDeserializeAllocator() {
25         Reset();
26     }
27 
GetSpace(size_t size)28     void* WireDeserializeAllocator::GetSpace(size_t size) {
29         // Return space in the current buffer if possible first.
30         if (mRemainingSize >= size) {
31             char* buffer = mCurrentBuffer;
32             mCurrentBuffer += size;
33             mRemainingSize -= size;
34             return buffer;
35         }
36 
37         // Otherwise allocate a new buffer and try again.
38         size_t allocationSize = std::max(size, size_t(2048));
39         char* allocation = static_cast<char*>(malloc(allocationSize));
40         if (allocation == nullptr) {
41             return nullptr;
42         }
43 
44         mAllocations.push_back(allocation);
45         mCurrentBuffer = allocation;
46         mRemainingSize = allocationSize;
47         return GetSpace(size);
48     }
49 
Reset()50     void WireDeserializeAllocator::Reset() {
51         for (auto allocation : mAllocations) {
52             free(allocation);
53         }
54         mAllocations.clear();
55 
56         // The initial buffer is the inline buffer so that some allocations can be skipped
57         mCurrentBuffer = mStaticBuffer;
58         mRemainingSize = sizeof(mStaticBuffer);
59     }
60 }  // namespace dawn_wire
61