#include #include "session_private.h" #include "session_pool.h" struct session_pool { uint64_t capacity; uint64_t available; struct session_list free_list; }; struct session_pool *session_pool_new(uint64_t capacity) { struct session_pool *pool = (struct session_pool *)calloc(1, sizeof(struct session_pool) + capacity * sizeof(struct session)); if (pool == NULL) { return NULL; } pool->available = 0; pool->capacity = capacity; TAILQ_INIT(&pool->free_list); struct session *array = (struct session *)(pool + 1); for (uint64_t i = 0; i < capacity; i++) { struct session *sess = &array[i]; TAILQ_INSERT_TAIL(&pool->free_list, sess, free_tqe); pool->available++; } return pool; } void session_pool_free(struct session_pool *pool) { if (pool) { struct session *sess; while ((sess = TAILQ_FIRST(&pool->free_list))) { TAILQ_REMOVE(&pool->free_list, sess, free_tqe); pool->available--; } free(pool); pool = NULL; } } struct session *session_pool_pop(struct session_pool *pool) { if (pool == NULL) { return NULL; } struct session *sess = TAILQ_FIRST(&pool->free_list); if (sess) { TAILQ_REMOVE(&pool->free_list, sess, free_tqe); pool->available--; } return sess; } void session_pool_push(struct session_pool *pool, struct session *sess) { if (pool == NULL || sess == NULL) { return; } TAILQ_INSERT_TAIL(&pool->free_list, sess, free_tqe); pool->available++; } const struct session *session_pool_get0(const struct session_pool *pool, uint64_t idx) { if (pool == NULL || idx >= pool->capacity) { return NULL; } struct session *array = (struct session *)(pool + 1); return &array[idx]; } uint64_t session_pool_available_num(const struct session_pool *pool) { if (pool == NULL) { return 0; } return pool->available; } uint64_t session_pool_capacity_size(const struct session_pool *pool) { if (pool == NULL) { return 0; } return pool->capacity; }