refbuf.c 1.87 KB
Newer Older
1 2 3 4 5
/* Icecast
 *
 * This program is distributed under the GNU General Public License, version 2.
 * A copy of this license is included with this source.
 *
6
 * Copyright 2000-2004, Jack Moffitt <jack@xiph.org,
7 8 9 10
 *                      Michael Smith <msmith@xiph.org>,
 *                      oddsock <oddsock@xiph.org>,
 *                      Karl Heyes <karl@xiph.org>
 *                      and others (see AUTHORS for details).
11
 * Copyright 2014-2015, Philipp "ph3-der-loewe" Schafft <lion@lion.leolix.org>,
12 13
 */

Jack Moffitt's avatar
Jack Moffitt committed
14
/* refbuf.c
15 16 17 18
 **
 ** reference counting buffer implementation
 **
 */
Jack Moffitt's avatar
Jack Moffitt committed
19

20 21 22 23
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

Jack Moffitt's avatar
Jack Moffitt committed
24 25 26 27 28
#include <stdlib.h>
#include <string.h>

#include "refbuf.h"

29 30 31 32 33
#define CATMODULE "refbuf"

#include "logging.h"


Jack Moffitt's avatar
Jack Moffitt committed
34 35 36 37 38 39 40 41
void refbuf_initialize(void)
{
}

void refbuf_shutdown(void)
{
}

42
refbuf_t *refbuf_new (unsigned int size)
Jack Moffitt's avatar
Jack Moffitt committed
43
{
44
    refbuf_t *refbuf;
Jack Moffitt's avatar
Jack Moffitt committed
45

46
    refbuf = (refbuf_t *)malloc(sizeof(refbuf_t));
Karl Heyes's avatar
Karl Heyes committed
47
    if (refbuf == NULL)
48
        abort();
Karl Heyes's avatar
Karl Heyes committed
49 50 51 52 53
    refbuf->data = NULL;
    if (size)
    {
        refbuf->data = malloc (size);
        if (refbuf->data == NULL)
54
            abort();
Karl Heyes's avatar
Karl Heyes committed
55
    }
56
    refbuf->len = size;
57
    refbuf->sync_point = 0;
58
    refbuf->_count = 1;
Karl Heyes's avatar
Karl Heyes committed
59 60
    refbuf->next = NULL;
    refbuf->associated = NULL;
Jack Moffitt's avatar
Jack Moffitt committed
61

62
    return refbuf;
Jack Moffitt's avatar
Jack Moffitt committed
63 64 65 66
}

void refbuf_addref(refbuf_t *self)
{
67
    self->_count++;
Jack Moffitt's avatar
Jack Moffitt committed
68 69
}

70 71 72 73
static void refbuf_release_associated (refbuf_t *ref)
{
    if (ref == NULL)
        return;
74
    while (ref)
75 76 77
    {
        refbuf_t *to_go = ref;
        ref = to_go->next;
78
        if ( to_go->_count == 1 )
79
            to_go->next = NULL;
80 81 82 83
        refbuf_release (to_go);
    }
}

Jack Moffitt's avatar
Jack Moffitt committed
84 85
void refbuf_release(refbuf_t *self)
{
86 87
    if (self == NULL)
        return;
88
    self->_count--;
89 90 91 92
    if (self->_count == 0)
    {
        refbuf_release_associated (self->associated);
        if (self->next)
93
            ICECAST_LOG_ERROR("next not null");
94 95 96
        free(self->data);
        free(self);
    }
Jack Moffitt's avatar
Jack Moffitt committed
97 98
}