Exemple #1
0
Fichier : cbuf.c Projet : danscu/lk
size_t cbuf_write(cbuf_t *cbuf, const void *_buf, size_t len, bool canreschedule)
{
	const char *buf = (const char *)_buf;

	LTRACEF("len %zd\n", len);

	DEBUG_ASSERT(cbuf);
	DEBUG_ASSERT(_buf);
	DEBUG_ASSERT(len < valpow2(cbuf->len_pow2));

	enter_critical_section();

	size_t write_len;
	size_t pos = 0;

	while (pos < len && cbuf_space_avail(cbuf) > 0) {
		if (cbuf->head >= cbuf->tail) {
			write_len = MIN(valpow2(cbuf->len_pow2) - cbuf->head, len - pos);
		} else {
			write_len = MIN(cbuf->tail - cbuf->head - 1, len - pos);
		}

		// if it's full, abort and return how much we've written
		if (write_len == 0) {
			break;
		}

		memcpy(cbuf->buf + cbuf->head, buf + pos, write_len);

		cbuf->head = INC_POINTER(cbuf, cbuf->head, write_len);
		pos += write_len;
	}

	if (cbuf->head != cbuf->tail)
		event_signal(&cbuf->event, canreschedule);

	exit_critical_section();

	return pos;
}
Exemple #2
0
Fichier : cbuf.c Projet : dankex/lk
size_t cbuf_read(cbuf_t *cbuf, void *_buf, size_t buflen, bool block)
{
	size_t ret;
	char *buf = (char *)_buf;

	DEBUG_ASSERT(cbuf);
	DEBUG_ASSERT(_buf);

	enter_critical_section();

	if (block)
		event_wait(&cbuf->event);

	// see if there's data available
	if (cbuf->tail != cbuf->head) {
		size_t pos = 0;

		// loop until we've read everything we need
		// at most this will make two passes to deal with wraparound
		while (pos < buflen && cbuf->tail != cbuf->head) {
			size_t read_len;
			if (cbuf->head > cbuf->tail) {
				// simple case where there is no wraparound
				read_len = MIN(cbuf->head - cbuf->tail, buflen - pos);
			} else {
				// read to the end of buffer in this pass
				read_len = MIN(valpow2(cbuf->len_pow2) - cbuf->tail, buflen - pos);
			}

			memcpy(buf + pos, cbuf->buf + cbuf->tail, read_len);

			cbuf->tail = INC_POINTER(cbuf, cbuf->tail, read_len);
			pos += read_len;
		}

		if (cbuf->tail == cbuf->head) {
			// we've emptied the buffer, unsignal the event
			event_unsignal(&cbuf->event);
		}

		ret = pos;
	} else {
		DEBUG_ASSERT(!block);
		ret = 0;
	}

	exit_critical_section();

	return ret;
}
Exemple #3
0
Fichier : cbuf.c Projet : danscu/lk
size_t cbuf_space_avail(cbuf_t *cbuf)
{
	uint consumed = modpow2((uint)(cbuf->head - cbuf->tail), cbuf->len_pow2);
	return valpow2(cbuf->len_pow2) - consumed - 1;
}