|
| 1 | +/*************************************************************************** |
| 2 | + * Copyright (C) 2020 PCSX-Redux authors * |
| 3 | + * * |
| 4 | + * This program is free software; you can redistribute it and/or modify * |
| 5 | + * it under the terms of the GNU General Public License as published by * |
| 6 | + * the Free Software Foundation; either version 2 of the License, or * |
| 7 | + * (at your option) any later version. * |
| 8 | + * * |
| 9 | + * This program is distributed in the hope that it will be useful, * |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of * |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * |
| 12 | + * GNU General Public License for more details. * |
| 13 | + * * |
| 14 | + * You should have received a copy of the GNU General Public License * |
| 15 | + * along with this program; if not, write to the * |
| 16 | + * Free Software Foundation, Inc., * |
| 17 | + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * |
| 18 | + ***************************************************************************/ |
| 19 | + |
| 20 | +#pragma once |
| 21 | + |
| 22 | +#include <assert.h> |
| 23 | +#include <stdint.h> |
| 24 | + |
| 25 | +namespace PCSX { |
| 26 | + |
| 27 | +class Slice { |
| 28 | + public: |
| 29 | + Slice() : m_isInlined(false), m_isOwned(false), m_size(0) { |
| 30 | + m_data.ptr = nullptr; |
| 31 | + } |
| 32 | + ~Slice() { maybeFree(); } |
| 33 | + void copy(const void * data, uint32_t size) { |
| 34 | + assert(size < (1 << 30)); |
| 35 | + maybeFree(); |
| 36 | + m_size = size; |
| 37 | + m_isOwned = true; |
| 38 | + if (size > sizeof(m_data.inlined)) { |
| 39 | + m_isInlined = false; |
| 40 | + m_data.ptr = (uint8_t *) malloc(size); |
| 41 | + memcpy(m_data.ptr, data, size); |
| 42 | + } else { |
| 43 | + m_isInlined = true; |
| 44 | + memcpy(m_data.inlined, data, size); |
| 45 | + } |
| 46 | + } |
| 47 | + void acquire(void * data, uint32_t size) { |
| 48 | + assert(size < (1 << 30)); |
| 49 | + maybeFree(); |
| 50 | + m_size = size; |
| 51 | + m_isOwned = true; |
| 52 | + m_isInlined = false; |
| 53 | + m_data.ptr = data; |
| 54 | + } |
| 55 | + void borrow(const void * data, uint32_t size) { |
| 56 | + assert(size < (1 << 30)); |
| 57 | + maybeFree(); |
| 58 | + m_size = size; |
| 59 | + m_isOwned = false; |
| 60 | + m_isInlined = false; |
| 61 | + m_data.ptr = const_cast<void*>(data); |
| 62 | + } |
| 63 | + const void * data() { return m_isInlined ? m_data.inlined : m_data.ptr; } |
| 64 | + const uint32_t size() { return m_size; } |
| 65 | + private: |
| 66 | + void maybeFree() { if (m_isOwned && !m_isInlined) free(m_data.ptr); } |
| 67 | + union { |
| 68 | + uint8_t inlined[24]; |
| 69 | + void * ptr; |
| 70 | + } m_data; |
| 71 | + bool m_isInlined : 1; |
| 72 | + bool m_isOwned : 1; |
| 73 | + uint32_t m_size : 30; |
| 74 | +}; |
| 75 | + |
| 76 | +} // namespace PCSX |
0 commit comments