aboutsummaryrefslogtreecommitdiffstats
path: root/com32/menu/refstr.c
blob: 8b4c7183be838a22d044ad4b7b84d9ffcaba0739 (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* ----------------------------------------------------------------------- *
 *   
 *   Copyright 2008 H. Peter Anvin - All Rights Reserved
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 *   Boston MA 02110-1301, USA; either version 2 of the License, or
 *   (at your option) any later version; incorporated herein by reference.
 *
 * ----------------------------------------------------------------------- */

/*
 * refstr.c
 *
 * Simple reference-counted strings
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "refstr.h"

const char *refstrndup(const char *str, size_t len)
{
  char *r;

  if (!str)
    return NULL;

  len = strnlen(str, len);
  r = malloc(sizeof(unsigned int)+len+1);
  *(unsigned int *)r = 1;
  r += sizeof(unsigned int);
  memcpy(r, str, len);
  r[len] = '\0';
  return r;
}

const char *refstrdup(const char *str)
{
  char *r;
  size_t len;

  if (!str)
    return NULL;

  len = strlen(str);
  r = malloc(sizeof(unsigned int)+len+1);
  *(unsigned int *)r = 1;
  r += sizeof(unsigned int);
  memcpy(r, str, len);
  r[len] = '\0';
  return r;
}

int vrsprintf(const char **bufp, const char *fmt, va_list ap)
{
  va_list ap1;
  int bytes;
  char *p;

  va_copy(ap1, ap);
  bytes = vsnprintf(NULL, 0, fmt, ap1)+1;
  va_end(ap1);

  p = malloc(bytes+sizeof(unsigned int));
  if ( !p ) {
    *bufp = NULL;
    return -1;
  }

  *(unsigned int *)p = 1;
  p += sizeof(unsigned int);
  *bufp = p;

  return vsnprintf(p, bytes, fmt, ap);
}

int rsprintf(const char **bufp, const char *fmt, ...)
{
  int rv;
  va_list ap;

  va_start(ap, fmt);
  rv = vrsprintf(bufp, fmt, ap);
  va_end(ap);

  return rv;
}

void refstr_put(const char *r)
{
  unsigned int *ref;

  if (r) {
    ref = (unsigned int *)r - 1;
    
    if (!--*ref)
      free(ref);
  }
}