반응형

 

아래의 소스 코드 참고.

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__)
반응형