C/Code snippet
오픈소스에서 조각 쓰는 데이터들 chunk (수정중)
2021. 12. 23. 20:59반응형
아래의 소스 코드 참고.
strongswan/src/libstrongswan/utils/chunk.h
strongswan/src/libstrongswan/utils/chunk.c
스트롱스완
오픈소스에서 조각 쓰는 데이터들 chunk
/**
* Clone a chunk on heap
*/
#define chunk_clone(chunk) ({chunk_t x = (chunk); chunk_create_clone(x.len ? malloc(x.len) : NULL, x);})
/**
* Empty chunk.
*/
chunk_t chunk_empty = { NULL, 0 };
static inline chunk_t chunk_create(u_char *ptr, size_t len)
{
chunk_t chunk = {ptr, len};
return chunk;
}
struct chunk_t {
/** Pointer to start of data */
u_char *ptr;
/** Length of data in bytes */
size_t len;
};
/**
* Described in header.
*/
chunk_t chunk_create_clone(u_char *ptr, chunk_t chunk)
{
chunk_t clone = chunk_empty;
if (chunk.ptr && chunk.len > 0)
{
clone.ptr = ptr;
clone.len = chunk.len;
memcpy(clone.ptr, chunk.ptr, chunk.len);
}
}
/**
* Skip n bytes in chunk (forward pointer, shorten length)
*/
static inline chunk_t chunk_skip(chunk_t chunk, size_t bytes)
{
if (chunk.len > bytes)
{
chunk.ptr += bytes;
chunk.len -= bytes;
return chunk;
}
return chunk_empty;
}
/**
* Initialize a chunk using a char array
*/
#define chunk_from_chars(...) ((chunk_t){(u_char[]){__VA_ARGS__}, sizeof((u_char[]){__VA_ARGS__})})
/**
* Initialize a chunk to point to a thing
*/
#define chunk_from_thing(thing) chunk_create((u_char*)&(thing), sizeof(thing))
/**
* Initialize a chunk from a string, not containing 0-terminator
*/
#define chunk_from_str(str) ({char *x = (str); chunk_create((u_char*)x, strlen(x));})
/**
* Allocate a chunk on the heap
*/
#define chunk_alloc(bytes) ({size_t x = (bytes); chunk_create(x ? malloc(x) : NULL, x);})
/**
* Allocate a chunk on the stack
*/
#define chunk_alloca(bytes) ({size_t x = (bytes); chunk_create(x ? alloca(x) : NULL, x);})
/**
* Clone a chunk on heap
*/
#define chunk_clone(chunk) ({chunk_t x = (chunk); chunk_create_clone(x.len ? malloc(x.len) : NULL, x);})
/**
* Clone a chunk on stack
*/
#define chunk_clonea(chunk) ({chunk_t x = (chunk); chunk_create_clone(x.len ? alloca(x.len) : NULL, x);})
/**
* Concatenate chunks into a chunk on heap
*/
#define chunk_cat(mode, ...) chunk_create_cat(malloc(chunk_length(mode, __VA_ARGS__)), mode, __VA_ARGS__)
/**
* Concatenate chunks into a chunk on stack
*/
#define chunk_cata(mode, ...) chunk_create_cat(alloca(chunk_length(mode, __VA_ARGS__)), mode, __VA_ARGS__)
반응형
'C > Code snippet' 카테고리의 다른 글
[C] 파일 읽기 간단한 예제 (0) | 2022.05.02 |
---|---|
[C] argc와 argv의 관계 (0) | 2022.04.30 |
[C] 간단한 fork 예제 및 fork 이론 (0) | 2022.04.20 |
[C] 로그 파일명, 함수명, 라인 출력 (0) | 2022.04.08 |
[C] 콘솔 커서를 이동하는 함수 (0) | 2022.01.23 |