Newer
Older
rtlibc / src / stdio.c
@Razvan Turiac Razvan Turiac on 19 Dec 2019 2 KB Improved code.
#include <stdio.h>
#include <string.h>
#include <printf.h>
#include <assert.h>

#include <../src/stdio_internal.h>



static int32_t rtstring_output_handler(void *user, const char *data, size_t size)
{
	string_descriptor_t *str_descriptor = (string_descriptor_t*)user;

	size_t len = size;

	if (str_descriptor->len > 0)
	{
		if (len > (str_descriptor->len - 1))
			len = str_descriptor->len - 1;
			
		str_descriptor->len -= len;
	}

	if (str_descriptor->ptr && len)
	{
		memcpy(str_descriptor->ptr, data, len);
		str_descriptor->ptr += len;
		*str_descriptor->ptr = 0;
	}
	
	return size;
}



int32_t sprintf(char *str, const char *format, ...)
{
	va_list args;
	va_start(args, format);	

	string_descriptor_t str_descriptor = {str, -1};
	const int32_t rv = rtprintf(rtstring_output_handler, &str_descriptor, format, args);

	va_end(args);
	return rv;
}


int32_t snprintf(char *str, size_t n, const char *format, ...)
{
	va_list args;
	va_start(args, format);	

	string_descriptor_t str_descriptor = {str, n};
	const int32_t rv = rtprintf(rtstring_output_handler, &str_descriptor, format, args);

	va_end(args);
	return rv;
}


int32_t vsprintf(char *str, const char *format, va_list args)
{
	string_descriptor_t str_descriptor = {str, -1};
	return rtprintf(rtstring_output_handler, &str_descriptor, format, args);
}



int32_t vsnprintf(char *str, size_t n, const char *format, va_list args)
{
	string_descriptor_t str_descriptor = {str, n};
	return rtprintf(rtstring_output_handler, &str_descriptor, format, args);
}



//simplified versions
int32_t isprintf(char *str, const char *format, ...)
{
	va_list args;
	va_start(args, format);	

	string_descriptor_t str_descriptor = {str, -1};
	const int32_t rv = rtiprintf(rtstring_output_handler, &str_descriptor, format, args);

	va_end(args);
	return rv;
}


int32_t isnprintf(char *str, size_t n, const char *format, ...)
{
	va_list args;
	va_start(args, format);	

	string_descriptor_t str_descriptor = {str, n};
	int32_t rv = rtiprintf(rtstring_output_handler, &str_descriptor, format, args);

	va_end(args);
	return rv;
}


int32_t ivsprintf(char *str, const char *format, va_list args)
{
	string_descriptor_t str_descriptor = {str, -1};
	return rtiprintf(rtstring_output_handler, &str_descriptor, format, args);
}



int32_t ivsnprintf(char *str, size_t n, const char *format, va_list args)
{
	string_descriptor_t str_descriptor = {str, n};
	return rtiprintf(rtstring_output_handler, &str_descriptor, format, args);
}