Created
November 28, 2010 13:21
-
-
Save neesenk/718919 to your computer and use it in GitHub Desktop.
简单的动态buff实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef __DYNAMINC_ARRAY_H__ | |
#define __DYNAMINC_ARRAY_H__ | |
#include <string.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
#ifdef __cplusplus | |
extern "C" { | |
#endif | |
#define D_ARRAY_INIT() (D_ARRAY) { 0, 0, NULL } | |
#define D_ARRAY_RESET(_array) do { (_array)->len = 0; } while (0) | |
typedef struct _D_ARRAY { | |
size_t size; /* array的长度 */ | |
size_t len; /* array填充了的长度 */ | |
char *array; | |
} D_ARRAY; | |
/* 失败返回负数, 成功返回0; len是array应该具有的最少长度 */ | |
static inline int dynamic_array_resize(D_ARRAY *array, size_t len) | |
{ | |
char *newarr = NULL; | |
assert(len + array->size >= array->size); /* 断言不会溢出 */ | |
if ((newarr = realloc(array->array, len + array->size)) == NULL) | |
return -1; | |
array->array = newarr; | |
array->size += len; | |
return 0; | |
} | |
static inline int dynamic_array_prealloc(D_ARRAY *array, size_t len) | |
{ | |
assert(array->len <= array->size); | |
assert(len + array->len >= array->len); /* 断言没有溢出 */ | |
if (array->size < len + array->len) | |
return dynamic_array_resize(array, len + array->len); | |
return 0; | |
} | |
static inline int dynamic_array_alloc(D_ARRAY *array, size_t len) | |
{ | |
int ret = 0; | |
if (dynamic_array_prealloc(array, len) < 0) | |
return -1; | |
ret = array->len; | |
array->len += len; | |
return ret; | |
} | |
static inline int dynamic_array_put(D_ARRAY *array, const void *content, size_t len) | |
{ | |
int ret = dynamic_array_alloc(array, len); | |
if (ret < 0) | |
return -1; | |
memcpy(array->array + ret, content, len); | |
return 0; | |
} | |
static inline | |
int dynamic_array_insert(D_ARRAY *array, size_t offset, const void *buf, size_t len) | |
{ | |
assert(array->len <= array->size); | |
assert(offset + len >= offset); /* 断言没有溢出 */ | |
if (offset + len > array->len) { | |
if (dynamic_array_alloc(array, len + offset - array->len) < 0) | |
return -1; | |
} | |
memcpy(array->array + offset, buf, len); | |
return 0; | |
} | |
static inline void dynamic_array_exit(D_ARRAY *array) | |
{ | |
free(array->array); | |
*array = D_ARRAY_INIT(); | |
} | |
#ifdef __cplusplus | |
} | |
#endif | |
#endif /* __DYNAMINC_ARRAY_H__ */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment