Newer
Older
rtlibc / src / stdio.c
/* Copyright (C) Thornwave Labs Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written by Razvan Turiac <razvan.turiac@thornwave.com>
 */

#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* const str_descriptor = (string_descriptor_t*)user;
	if (str_descriptor->ptr && str_descriptor->len)
	{
		const size_t len = size < (str_descriptor->len - 1) ? size : (str_descriptor->len - 1);

		if (len)
		{
			str_descriptor->len -= 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, ...)
{
	if (n > 0)
	{
		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;
	}
	else
	{
		return 0;
	}
}


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)
{
	if (n > 0)
	{
		string_descriptor_t str_descriptor = {str, n};
		return rtiprintf(rtstring_output_handler, &str_descriptor, format, args);
	}
	else
	{
		return 0;
	}
}