tRealloc.h 1.5 KB
Newer Older
H
Hongze Cheng 已提交
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
/*
 * 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/>.
 */

#ifndef _TD_UTIL_TREALLOC_H_
#define _TD_UTIL_TREALLOC_H_

#include "os.h"

#ifdef __cplusplus
extern "C" {
#endif

static FORCE_INLINE int32_t tRealloc(uint8_t **ppBuf, int64_t size) {
  int32_t  code = 0;
  int64_t  bsize = 0;
H
more  
Hongze Cheng 已提交
28
  uint8_t *pBuf = NULL;
H
Hongze Cheng 已提交
29 30

  if (*ppBuf) {
H
more  
Hongze Cheng 已提交
31 32
    pBuf = (*ppBuf) - sizeof(int64_t);
    bsize = *(int64_t *)pBuf;
H
Hongze Cheng 已提交
33 34 35 36 37 38 39 40 41
  }

  if (bsize >= size) goto _exit;

  if (bsize == 0) bsize = 64;
  while (bsize < size) {
    bsize *= 2;
  }

H
more  
Hongze Cheng 已提交
42
  pBuf = (uint8_t *)taosMemoryRealloc(pBuf, bsize + sizeof(int64_t));
H
Hongze Cheng 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
  if (pBuf == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _exit;
  }

  *(int64_t *)pBuf = bsize;
  *ppBuf = pBuf + sizeof(int64_t);

_exit:
  return code;
}

static FORCE_INLINE void tFree(uint8_t *pBuf) {
  if (pBuf) {
    taosMemoryFree(pBuf - sizeof(int64_t));
  }
}

#ifdef __cplusplus
}
#endif

65
#endif /*_TD_UTIL_TREALLOC_H_*/