File: refstr.c

package info (click to toggle)
syslinux 2%3A3.71%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 18,336 kB
  • ctags: 49,435
  • sloc: ansic: 188,623; asm: 12,943; pascal: 7,861; perl: 3,446; makefile: 1,968; sh: 771; python: 470; java: 324; xml: 14; php: 4
file content (105 lines) | stat: -rw-r--r-- 2,033 bytes parent folder | download
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
103
104
105
/* ----------------------------------------------------------------------- *
 *
 *   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"

/* Allocate space for a refstring of len bytes, plus final null */
/* The final null is inserted in the string; the rest is uninitialized. */
char *refstr_alloc(size_t len)
{
  char *r = malloc(sizeof(unsigned int)+len+1);
  if (!r)
    return NULL;
  *(unsigned int *)r = 1;
  r += sizeof(unsigned int);
  r[len] = '\0';
  return r;
}

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

  if (!str)
    return NULL;

  len = strnlen(str, len);
  r = refstr_alloc(len);
  if (r)
    memcpy(r, str, len);
  return r;
}

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

  if (!str)
    return NULL;

  len = strlen(str);
  r = refstr_alloc(len);
  if (r)
    memcpy(r, str, len);
  return r;
}

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

  va_copy(ap1, ap);
  len = vsnprintf(NULL, 0, fmt, ap1);
  va_end(ap1);

  *bufp = p = refstr_alloc(len);
  if ( !p )
    return -1;

  return vsnprintf(p, len+1, 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);
  }
}