X-Git-Url: https://git.m6w6.name/?a=blobdiff_plain;f=phpstr%2Fphpstr.c;h=c0d9543f3d3e4a7e5b11b9d20b3aee68f3632c04;hb=3f048c60b3f3b8151eb86121eed8c9b8927c55dc;hp=8d8df3ea25f383cf1e9ec1efe9f0b73d495a4654;hpb=909134d3309bdc12023c0fea5acf931041ea0f6b;p=m6w6%2Fext-http diff --git a/phpstr/phpstr.c b/phpstr/phpstr.c index 8d8df3e..c0d9543 100644 --- a/phpstr/phpstr.c +++ b/phpstr/phpstr.c @@ -4,11 +4,7 @@ #include "php.h" #include "phpstr.h" -#ifndef PHPSTR_DEFAULT_SIZE -#define PHPSTR_DEFAULT_SIZE 256 -#endif - -PHPSTR_API phpstr *phpstr_init_ex(phpstr *buf, size_t chunk_size, zend_bool pre_alloc) +PHPSTR_API phpstr *phpstr_init_ex(phpstr *buf, size_t chunk_size, int pre_alloc) { if (!buf) { buf = emalloc(sizeof(phpstr)); @@ -235,20 +231,69 @@ PHPSTR_API int phpstr_cmp(phpstr *left, phpstr *right) PHPSTR_API void phpstr_dtor(phpstr *buf) { - if (buf->data) { - efree(buf->data); - buf->data = NULL; - } + STR_SET(buf->data, NULL); buf->used = 0; buf->free = 0; } -PHPSTR_API void phpstr_free(phpstr *buf) +PHPSTR_API void phpstr_free(phpstr **buf) +{ + if (*buf) { + phpstr_dtor(*buf); + efree(*buf); + *buf = NULL; + } +} + +PHPSTR_API size_t phpstr_chunk_buffer(phpstr **s, const char *data, size_t data_len, char **chunk, size_t chunk_size) +{ + phpstr *storage; + + *chunk = NULL; + + if (!*s) { + *s = phpstr_init_ex(NULL, chunk_size * 2, chunk_size ? 1 : 0); + } + storage = *s; + + if (data_len) { + phpstr_append(storage, data, data_len); + } + + if (!chunk_size) { + phpstr_data(storage, chunk, &chunk_size); + phpstr_free(s); + return chunk_size; + } + + if (storage->used >= storage->size/2) { + phpstr *avail = phpstr_left(storage, storage->size/2); + *chunk = estrndup(PHPSTR_VAL(avail), PHPSTR_LEN(avail)); + phpstr_free(&avail); + phpstr_cut(storage, 0, storage->size/2); + return storage->size/2; + } + + return 0; +} + +PHPSTR_API void phpstr_chunked_output(phpstr **s, const char *data, size_t data_len, size_t chunk_len, void (*passthru)(const char *, size_t TSRMLS_DC) TSRMLS_DC) { - if (buf) { - phpstr_dtor(buf); - efree(buf); + char *chunk = NULL; + size_t got = 0; + + while (got = phpstr_chunk_buffer(s, data, data_len, &chunk, chunk_len)) { + passthru(chunk, got TSRMLS_CC); + if (!chunk_len) { + /* we already got the last chunk, + and freed all resources */ + break; + } + data = NULL; + data_len = 0; + STR_SET(chunk, NULL); } + STR_FREE(chunk); } /*