tstrbuild.c 2.4 KB
Newer Older
S
slguan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
H
hjxilinx 已提交
15
#include "os.h"
S
slguan 已提交
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
#include "tstrbuild.h"

void taosStringBuilderEnsureCapacity(SStringBuilder* sb, size_t size) {
  size += sb->pos;
  if (size > sb->size) {
    size *= 2;
    void* tmp = realloc(sb->buf, size);
    if (tmp == NULL) {
      longjmp(sb->jb, 1);
    }
    sb->buf = (char*)tmp;
    sb->size = size;
  }
}

char* taosStringBuilderGetResult(SStringBuilder* sb, size_t* len) {
  taosStringBuilderEnsureCapacity(sb, 1);
  sb->buf[sb->pos] = 0;
  if (len != NULL) {
    *len = sb->pos;
  }
  return sb->buf;
}

void taosStringBuilderDestroy(SStringBuilder* sb) {
  free(sb->buf);
  sb->buf = NULL;
  sb->pos = 0;
  sb->size = 0;
}

void taosStringBuilderAppend(SStringBuilder* sb, const void* data, size_t len) {
  taosStringBuilderEnsureCapacity(sb, len);
  memcpy(sb->buf + sb->pos, data, len);
  sb->pos += len;
}

void taosStringBuilderAppendChar(SStringBuilder* sb, char c) {
  taosStringBuilderEnsureCapacity(sb, 1);
  sb->buf[sb->pos++] = c;
}

void taosStringBuilderAppendStringLen(SStringBuilder* sb, const char* str, size_t len) {
  taosStringBuilderEnsureCapacity(sb, len);
  memcpy(sb->buf + sb->pos, str, len);
  sb->pos += len;
}

void taosStringBuilderAppendString(SStringBuilder* sb, const char* str) {
  taosStringBuilderAppendStringLen(sb, str, strlen(str));
}

void taosStringBuilderAppendNull(SStringBuilder* sb) { taosStringBuilderAppendStringLen(sb, "null", 4); }

void taosStringBuilderAppendInteger(SStringBuilder* sb, int64_t v) {
  char   buf[64];
72 73
  size_t len = snprintf(buf, sizeof(buf), "%" PRId64, v);
  taosStringBuilderAppendStringLen(sb, buf, MIN(len, sizeof(buf)));
S
slguan 已提交
74 75 76
}

void taosStringBuilderAppendDouble(SStringBuilder* sb, double v) {
77 78 79
  char   buf[512];
  size_t len = snprintf(buf, sizeof(buf), "%.9lf", v);
  taosStringBuilderAppendStringLen(sb, buf, MIN(len, sizeof(buf)));
S
slguan 已提交
80
}