summaryrefslogtreecommitdiff
path: root/libfmt/libmisc.c
blob: 552b916b633f3e4c3f2afa7113a3627f885f0719 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* libfmt/libmisc.c - Integrate pico-fmt with libmisc
 *
 * Copyright (C) 2024-2025  Luke T. Shumaker <lukeshu@lukeshu.com>
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

#include <stdarg.h>             /* for va_list, va_start(), va_end() */
#include <stdio.h>              /* for vprintf(), putchar(), fflush() */
#if LIB_PICO_STDIO
#include <pico/stdio.h>         /* for stdio_putchar_raw() */
#endif

#include <libmisc/macro.h>      /* for LM_UNUSED() */
#include <libmisc/_intercept.h> /* for __lm_printf() */

#include <libfmt/fmt.h>         /* for fmt_vfctprintf() */

#if !LIB_PICO_STDIO
static void libfmt_libc_fct(char character, void *LM_UNUSED(arg)) {
	putchar(character);
}
#endif

size_t __lm_printf(const char *format, ...) {
	va_list va;
	va_start(va, format);
#if LIB_PICO_STDIO
	/* pico_stdio has already intercepted vprintf for us, and
	 * their stdio_buffered_printer() is better than our
	 * libfmt_libc_fct() because buffering.  */
	size_t ret = (size_t) vprintf(format, va);
#else
	size_t ret = (size_t) fmt_vfctprintf(libfmt_libc_fct, NULL, format, va);
	fflush(stdout);
#endif
	va_end(va);
	return ret;
}

static void libfmt_conv_formatter(struct fmt_state *state) {
	lo_interface fmt_formatter obj = va_arg(*state->args, lo_interface fmt_formatter);
	LO_CALL(obj, format, state);
}

[[gnu::constructor]]
static void libfmt_install_formatter(void) {
	fmt_install('v', libfmt_conv_formatter);
}