/* 
 * Copyright 2010 Stefan Lankes, Chair for Operating Systems,
 *                               RWTH Aachen University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *  This file is part of MetalSVM.
 */

#include <metalsvm/stdio.h>

typedef struct {
	char *str;
	size_t pos;
	size_t max;
} sputchar_arg_t;

static void sputchar(int c, void *arg)
{
	sputchar_arg_t *dest = (sputchar_arg_t *) arg;

	if (dest->pos < dest->max) {
		dest->str[dest->pos] = (char)c;
		dest->pos++;
	}
}

int ksnprintf(char *str, size_t size, const char *format, ...)
{
	int ret;
	va_list ap;
	sputchar_arg_t dest;

	dest.str = str;
	dest.pos = 0;
	dest.max = size;

	va_start(ap, format);
	ret = kvprintf(format, sputchar, &dest, 10, ap);
	va_end(ap);

	str[ret] = 0;

	return ret;
}

int ksprintf(char *str, const char *format, ...)
{
	int ret;
	va_list ap;
	sputchar_arg_t dest;

	dest.str = str;
	dest.pos = 0;
	dest.max = (size_t) -1;

	va_start(ap, format);
	ret = kvprintf(format, sputchar, &dest, 10, ap);
	va_end(ap);

	str[ret] = 0;

	return ret;
}