Skip to content

Instantly share code, notes, and snippets.

@horpto
Last active February 20, 2017 21:30
Show Gist options
  • Save horpto/32c983fc5de7d985f628 to your computer and use it in GitHub Desktop.
Save horpto/32c983fc5de7d985f628 to your computer and use it in GitHub Desktop.
#ifndef VECTOR_H
#define VECTOR_H
#include <stddef.h>
#include <string.h>
#include <malloc.h>
/* Динамически растущий велосипед */
#define SINGLE_ARG(...) __VA_ARGS__
#define TYPE_VECTOR(type, size) \
struct { \
size_t capacity; \
size_t length; \
union { \
type local_items[size]; \
type *items; \
}; \
}
#define _VECTOR_LOCAL_LENGTH(vector) \
(sizeof((vector).local_items) / _VECTOR_ITEM_SIZEOF(vector))
#define _VECTOR_TYPE(vector) typeof((vector).items)
#define _VECTOR_ITEM_SIZEOF(vector) sizeof((vector).local_items[0])
#define VECTOR_INIT(vector) \
{ .capacity = _VECTOR_LOCAL_LENGTH(vector), .length = 0, {} }
#define VECTOR_ADD_ELEMENT(vector, element) do \
{ \
(vector).length++; \
if ((vector).length < _VECTOR_LOCAL_LENGTH(vector)) \
{ \
(vector).local_items[(vector).length] = element; \
break; \
} \
\
if ((vector).length == _VECTOR_LOCAL_LENGTH(vector)) \
{ \
(vector).capacity = (vector).length * 2; \
(vector).items = memcpy( \
malloc((vector).capacity * _VECTOR_ITEM_SIZEOF(vector)), \
(vector).local_items, \
sizeof((vector).local_items)); \
} \
else if ((vector).length == (vector).capacity) \
{ \
(vector).capacity += ((vector).capacity >> 1); \
(vector).items = realloc((vector).items, \
(vector).capacity * _VECTOR_ITEM_SIZEOF(vector)); \
} \
\
(vector).items[(vector).length] = element; \
} while(0);
#define VECTOR_GET_LENGTH(vector) ((vector).length)
#define VECTOR_GET_DATA(vector) \
(((vector).length <= _VECTOR_LOCAL_LENGTH(vector)) ? (vector).local_items : (vector).items)
#define VECTOR_FREE(vector) do \
{ \
if ((vector).length > _VECTOR_LOCAL_LENGTH(vector)) \
free((vector).items); \
} while(0);
#endif /* VECTOR_H_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment