1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/libmem/lib/src/memory_preallocated.cc Thu Apr 15 23:15:17 2021 +0200
1.3 @@ -0,0 +1,80 @@
1.4 +/*
1.5 + * A memory pool providing regions from a preallocated amount of memory.
1.6 + *
1.7 + * Copyright (C) 2021 Paul Boddie <paul@boddie.org.uk>
1.8 + *
1.9 + * This program is free software; you can redistribute it and/or
1.10 + * modify it under the terms of the GNU General Public License as
1.11 + * published by the Free Software Foundation; either version 2 of
1.12 + * the License, or (at your option) any later version.
1.13 + *
1.14 + * This program is distributed in the hope that it will be useful,
1.15 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
1.16 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1.17 + * GNU General Public License for more details.
1.18 + *
1.19 + * You should have received a copy of the GNU General Public License
1.20 + * along with this program; if not, write to the Free Software
1.21 + * Foundation, Inc., 51 Franklin Street, Fifth Floor,
1.22 + * Boston, MA 02110-1301, USA
1.23 + */
1.24 +
1.25 +#include "memory_preallocated.h"
1.26 +
1.27 +
1.28 +
1.29 +/* Initialise the memory pool with the given amount in bytes. */
1.30 +
1.31 +MemoryPreallocated::MemoryPreallocated(Memory *memory, offset_t amount)
1.32 +: _memory(memory), _amount(amount)
1.33 +{
1.34 + // NOTE: Handle allocation failure.
1.35 +
1.36 + offset_t remaining = amount;
1.37 +
1.38 + while (remaining)
1.39 + {
1.40 + _regions.push_back(memory->region());
1.41 +
1.42 + if (memory->region_size() >= remaining)
1.43 + break;
1.44 +
1.45 + remaining -= memory->region_size();
1.46 + }
1.47 +}
1.48 +
1.49 +/* Discard all unused regions. */
1.50 +
1.51 +MemoryPreallocated::~MemoryPreallocated()
1.52 +{
1.53 + while (!_regions.empty())
1.54 + {
1.55 + Region *region = _regions.front();
1.56 +
1.57 + _regions.pop_front();
1.58 + _memory->release(region);
1.59 + }
1.60 +}
1.61 +
1.62 +/* Obtain an allocated region. */
1.63 +
1.64 +Region *MemoryPreallocated::region()
1.65 +{
1.66 + std::lock_guard<std::mutex> guard(_lock);
1.67 +
1.68 + Region *region = _regions.front();
1.69 +
1.70 + _regions.pop_front();
1.71 + return region;
1.72 +}
1.73 +
1.74 +/* Release the allocated 'region'. */
1.75 +
1.76 +void MemoryPreallocated::release(Region *region)
1.77 +{
1.78 + std::lock_guard<std::mutex> guard(_lock);
1.79 +
1.80 + _regions.push_back(region);
1.81 +}
1.82 +
1.83 +// vim: tabstop=4 expandtab shiftwidth=4