summaryrefslogtreecommitdiffstats
path: root/xbmc/utils/auto_buffer.cpp
blob: e88a960c5ab5e1ab143a0cb771924fdae89c9315 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 *  Copyright (C) 2013-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include "auto_buffer.h"

#include <new> // for std::bad_alloc
#include <stdlib.h> // for malloc(), realloc() and free()

using namespace XUTILS;

auto_buffer::auto_buffer(size_t size)
{
  if (!size)
    return;

  p = malloc(size); // "malloc()" instead of "new" allow to use "realloc()"
  if (!p)
    throw std::bad_alloc();
  s = size;
}

auto_buffer::~auto_buffer()
{
  free(p);
}

auto_buffer& auto_buffer::allocate(size_t size)
{
  clear();
  if (size)
  {
    p = malloc(size);
    if (!p)
      throw std::bad_alloc();
    s = size;
  }
  return *this;
}

auto_buffer& auto_buffer::resize(size_t newSize)
{
  if (!newSize)
    return clear();

  void* newPtr = realloc(p, newSize);
  if (!newPtr)
    throw std::bad_alloc();
  p = newPtr;
  s = newSize;
  return *this;
}

auto_buffer& auto_buffer::clear(void)
{
  free(p);
  p = 0;
  s = 0;
  return *this;
}

auto_buffer& auto_buffer::attach(void* pointer, size_t size)
{
  clear();
  if ((pointer && size) || (!pointer && !size))
  {
    p = pointer;
    s = size;
  }
  return *this;
}

void* auto_buffer::detach(void)
{
  void* returnPtr = p;
  p = 0;
  s = 0;
  return returnPtr;
}