kore

An easy to use, scalable and secure web application framework for writing web APIs in C.
Commits | Files | Refs | README | LICENSE | git clone https://git.kore.io/kore.git

commit db7ed69f2ae8dcdf2308815bb899c86ff8cce04c
parent ef814a677de41406c8be1ceb267de89e5c6bead1
Author: Joris Vink <joris@coders.se>
Date:   Wed,  7 Aug 2013 14:56:14 +0200

Add kore_buf_replace_string().

kore_buf_replace_string allows you to replace occurances of a certain
string with something else.

Example:
	char	*username = "Joris";

	page = kore_buf_create(static_len_html_profile);
	kore_buf_append(page, static_html_profile, static_len_html_profile);
	kore_buf_replace_string(page, "%name%", username, strlen(username));

Diffstat:
includes/kore.h | 2++
src/buf.c | 36++++++++++++++++++++++++++++++++++++
2 files changed, 38 insertions(+), 0 deletions(-)

diff --git a/includes/kore.h b/includes/kore.h @@ -346,6 +346,8 @@ u_int8_t *kore_buf_release(struct kore_buf *, u_int32_t *); void kore_buf_appendf(struct kore_buf *, const char *, ...); void kore_buf_appendv(struct kore_buf *, struct buf_vec *, u_int16_t); void kore_buf_appendb(struct kore_buf *, struct kore_buf *); +void kore_buf_replace_string(struct kore_buf *, const char *, + u_int8_t *, size_t); struct spdy_header_block *spdy_header_block_create(int); struct spdy_stream *spdy_stream_lookup(struct connection *, u_int32_t); diff --git a/src/buf.c b/src/buf.c @@ -96,3 +96,39 @@ kore_buf_free(struct kore_buf *buf) kore_mem_free(buf->data); kore_mem_free(buf); } + +void +kore_buf_replace_string(struct kore_buf *b, const char *src, + u_int8_t *dst, size_t len) +{ + u_int32_t blen, off, off2; + size_t nlen, klen; + char *key, *end, *tmp, *p; + + off = 0; + klen = strlen(src); + for (;;) { + blen = b->offset; + nlen = blen + len; + p = (char *)b->data; + + if ((key = strstr((p + off), src)) == NULL) + break; + + end = key + klen; + off = key - p; + off2 = ((char *)(b->data + b->offset) - end); + + tmp = kore_malloc(nlen); + memcpy(tmp, p, off); + memcpy((tmp + off), dst, len); + memcpy((tmp + off + len), end, off2); + + kore_mem_free(b->data); + b->data = (u_int8_t *)tmp; + b->offset = off + len + off2; + b->length = nlen; + + off = off + len; + } +}