From 7edd6a1b2a5d3cbe7645afeb9b8ad17803b2ebc5 Mon Sep 17 00:00:00 2001 From: Steffen Vogel Date: Tue, 8 May 2018 11:43:53 +0200 Subject: [PATCH] sample: add new function to allocate samples on heap (not in pool) --- include/villas/sample.h | 6 +++++- lib/sample.c | 34 +++++++++++++++++++++++++++------- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/include/villas/sample.h b/include/villas/sample.h index dcd3e19f4..8546ab365 100644 --- a/include/villas/sample.h +++ b/include/villas/sample.h @@ -102,11 +102,15 @@ struct sample { } data[]; /**< Data is in host endianess! */ }; +#define SAMPLE_NON_POOL PTRDIFF_MIN + /** Get the address of the pool to which the sample belongs. */ -#define sample_pool(s) ((struct pool *) ((char *) (s) + (s)->pool_off)) +#define sample_pool(s) ((s)->pool_off == SAMPLE_NON_POOL ? NULL : (struct pool *) ((char *) (s) + (s)->pool_off)) struct sample * sample_alloc(struct pool *p); +struct sample * sample_alloc_mem(int capacity); + struct sample * sample_clone(struct sample *smp); void sample_free(struct sample *s); diff --git a/lib/sample.c b/lib/sample.c index 815db7ddd..870073dd9 100644 --- a/lib/sample.c +++ b/lib/sample.c @@ -56,11 +56,34 @@ struct sample * sample_alloc(struct pool *p) return s; } +struct sample * sample_alloc_mem(int capacity) +{ + size_t sz = SAMPLE_LEN(capacity); + + char *b = alloc(sz); + if (!b) + return NULL; + + struct sample *s = (struct sample *) b; + + s->pool_off = SAMPLE_NON_POOL; + + s->length = 0; + s->format = 0; /* all sample values are float by default */ + s->capacity = capacity; + s->refcnt = ATOMIC_VAR_INIT(1); + + return s; +} + void sample_free(struct sample *s) { struct pool *p = sample_pool(s); - pool_put(p, s); + if (p) + pool_put(p, s); + else + free(s); } int sample_alloc_many(struct pool *p, struct sample *smps[], int cnt) @@ -82,11 +105,8 @@ int sample_alloc_many(struct pool *p, struct sample *smps[], int cnt) void sample_free_many(struct sample *smps[], int cnt) { - for (int i = 0; i < cnt; i++) { - struct pool *p = sample_pool(smps[i]); - - pool_put(p, smps[i]); - } + for (int i = 0; i < cnt; i++) + sample_free(smps[i]); } int sample_put_many(struct sample *smps[], int cnt) @@ -120,7 +140,7 @@ int sample_put(struct sample *s) /* Did we had the last reference? */ if (prev == 1) - pool_put(sample_pool(s), s); + sample_free(s); return prev - 1; }