read.c 1.02 KB
#include <stdlib.h>
#include <unistd.h>

#include "http/request/parser.h"


size_t
httpRequestParserRead(HttpRequestParser this, int fd)
{
	size_t            remaining, chunks;
	char              buffer[1024];

	ssize_t size = read(fd, buffer, 1024);

	if (0 < size) {
		remaining = this->buffer_used % HTTP_REQUEST_PARSER_READ_CHUNK;
		chunks    = this->buffer_used / HTTP_REQUEST_PARSER_READ_CHUNK;

		/**
		 * because a division always rounds down
		 * chunks holds exactly the currently allocated chunks if
		 * remaining equals 0 but there is no space left.
		 * Else chunks holds the actually allocated amount of chunks
		 * minus 1.
		 * For this reason chunks always has to be increased by 1.
		 */
		chunks++;

		if (size >= remaining) {
			this->buffer =
				realloc(this->buffer, chunks * HTTP_REQUEST_PARSER_READ_CHUNK);
		}

		memcpy(this->buffer + this->buffer_used, buffer, size);
		this->buffer_used += size;
		this->buffer[this->buffer_used] = 0;

		httpRequestParserParse(this);
	}

	return size;
}

// vim: set ts=4 sw=4: