add asprintf

This commit is contained in:
Mathieu Maret 2021-01-25 10:17:19 +01:00
parent bea3449b11
commit 3f4fb9e952
3 changed files with 67 additions and 9 deletions

View File

@ -1,3 +1,4 @@
#include "alloc.h"
#include "klibc.h" #include "klibc.h"
#include "serial.h" #include "serial.h"
#include "vga.h" #include "vga.h"
@ -211,7 +212,7 @@ int vsnprintf(char *str, size_t size, const char *format, va_list ap)
int i = 0; int i = 0;
int c = 0; int c = 0;
while (format[i] != '\0' && size) { while (format[i] != '\0' && (size|| !str)) {
switch (format[i]) { switch (format[i]) {
case '%': case '%':
switch (format[i + 1]) { switch (format[i + 1]) {
@ -381,3 +382,47 @@ int vprintf(const char *fmt, va_list ap)
} }
return ret; return ret;
} }
int asprintf(char **strp, const char *fmt, ...)
{
int ret;
va_list ap;
va_start(ap, fmt);
ret = vasprintf(strp, fmt, ap);
va_end(ap);
return ret;
}
int vasprintf(char **strp, const char *fmt, va_list ap)
{
int n = 0;
size_t size = 0;
char *p = NULL;
/* Determine required size */
n = vsnprintf(p, size, fmt, ap);
printf("Found length %d\n", n);
if (n < 0)
return -1;
/* One extra byte for '\0' */
size = (size_t)n + 1;
p = malloc(size);
if (p == NULL)
return -1;
n = vsnprintf(p, size, fmt, ap);
if (n < 0) {
free(p);
return -1;
}
*strp = p;
return size;
}

View File

@ -25,6 +25,10 @@ int vsnprintf(char *str, size_t size, const char *format, va_list ap);
int vprintf(const char *format, va_list ap); int vprintf(const char *format, va_list ap);
int printf(const char *format, ...); int printf(const char *format, ...);
// Could be used after malloc is available
int asprintf(char **strp, const char *fmt, ...);
int vasprintf(char **strp, const char *fmt, va_list ap);
/* /*
* Dummy printk for disabled debugging statements to use whilst maintaining * Dummy printk for disabled debugging statements to use whilst maintaining
* gcc's format checking. * gcc's format checking.

View File

@ -311,6 +311,7 @@ void testKthread()
} }
void run_test(void) void run_test(void)
{
{ {
int test = 1000; int test = 1000;
long long int test64 = 0x100000000; long long int test64 = 0x100000000;
@ -320,6 +321,14 @@ void run_test(void)
assert(printf("hello %llx\n", test64) == 16); assert(printf("hello %llx\n", test64) == 16);
assert(printf("hello %c\n", 'a') == 8); assert(printf("hello %c\n", 'a') == 8);
assert(printf("hello %s\n", "world") == 12); assert(printf("hello %s\n", "world") == 12);
}
{
char *strAlloc;
int ret = asprintf(&strAlloc, "hello %s\n", "world");
printf("asprint ret %d %s\n", ret, strAlloc);
assert(ret == 13); //include the '\0'
free(strAlloc);
}
testPaging(); testPaging();
printf("Testing Serial\n"); printf("Testing Serial\n");
serialPutc('h'); serialPutc('h');