glusterfs
93 строки · 2.1 Кб
1/*
2Copyright (c) 2014 Red Hat, Inc. <http://www.redhat.com>
3This file is part of GlusterFS.
4
5This file is licensed to you under your choice of the GNU Lesser
6General Public License, version 3 or any later version (LGPLv3 or
7later), or the GNU General Public License, version 2 (GPLv2), in all
8cases as published by the Free Software Foundation.
9*/
10
11#include <stdarg.h>12
13#include "glusterfs/mem-types.h"14#include "glusterfs/mem-pool.h"15#include "glusterfs/strfd.h"16#include "glusterfs/common-utils.h"17
18strfd_t *19strfd_open(void)20{
21strfd_t *strfd = NULL;22
23strfd = GF_CALLOC(1, sizeof(*strfd), gf_common_mt_strfd_t);24
25return strfd;26}
27
28int
29strvprintf(strfd_t *strfd, const char *fmt, va_list ap)30{
31char *str = NULL;32int size = 0;33
34size = vasprintf(&str, fmt, ap);35
36if (size < 0)37return size;38
39if (!strfd->alloc_size) {40strfd->data = GF_CALLOC(max(size + 1, 4096), 1,41gf_common_mt_strfd_data_t);42if (!strfd->data) {43free(str); /* NOT GF_FREE */44return -1;45}46strfd->alloc_size = max(size + 1, 4096);47}48
49if (strfd->alloc_size <= (strfd->size + size)) {50char *tmp_ptr = NULL;51int new_size = max(52(strfd->alloc_size * 2),53gf_roundup_next_power_of_two(strfd->size + size + 1));54tmp_ptr = GF_REALLOC(strfd->data, new_size);55if (!tmp_ptr) {56free(str); /* NOT GF_FREE */57return -1;58}59strfd->alloc_size = new_size;60strfd->data = tmp_ptr;61}62
63/* Copy the trailing '\0', but do not account for it in ->size.64This allows safe use of strfd->data as a string. */
65memcpy(strfd->data + strfd->size, str, size + 1);66strfd->size += size;67
68free(str); /* NOT GF_FREE */69
70return size;71}
72
73int
74strprintf(strfd_t *strfd, const char *fmt, ...)75{
76int ret = 0;77va_list ap;78
79va_start(ap, fmt);80ret = strvprintf(strfd, fmt, ap);81va_end(ap);82
83return ret;84}
85
86int
87strfd_close(strfd_t *strfd)88{
89GF_FREE(strfd->data);90GF_FREE(strfd);91
92return 0;93}
94