1 /*
2  * Copyright (c) 2006-2023, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author       Notes
8  */
9 
10 #include <rtthread.h>
11 #include <sys/types.h>
12 #include <stdio.h>
13 #include <unistd.h>
14 #ifdef RT_USING_POSIX_STDIO
15 #include <posix/stdio.h>
16 #endif /* RT_USING_POSIX_STDIO */
17 #define DBG_TAG    "picolibc.iob"
18 #define DBG_LVL    DBG_INFO
19 #include <rtdbg.h>
20 
21 #ifdef TINY_STDIO
22 
23 static int __fputc(char c, FILE *file);
24 static int __fgetc(FILE *file);
25 
26 static FILE __stdio_in = FDEV_SETUP_STREAM(NULL, __fgetc, NULL, _FDEV_SETUP_READ);
27 static FILE __stdio_out = FDEV_SETUP_STREAM(__fputc, NULL, NULL, _FDEV_SETUP_WRITE);
28 
29 #ifdef __strong_reference
30 #define STDIO_ALIAS(x) __strong_reference(stdout, x);
31 #else
32 #define STDIO_ALIAS(x) FILE *const x = &__stdio_out;
33 #endif
34 
35 FILE *const stdin = &__stdio_in;
36 FILE *const stdout = &__stdio_out;
37 STDIO_ALIAS(stderr);
38 
__fputc(char c,FILE * file)39 static int __fputc(char c, FILE *file)
40 {
41     if (file == &__stdio_out)
42     {
43 #if defined(RT_USING_CONSOLE) && defined(RT_USING_DEVICE)
44         rt_device_t console = rt_console_get_device();
45         if (console)
46         {
47             rt_ssize_t rc = rt_device_write(console, -1, &c, 1);
48             return rc > 0 ? rc : -1;
49         }
50 #endif /* defined(RT_USING_CONSOLE) && defined(RT_USING_DEVICE) */
51     }
52 
53     return -1;
54 }
55 
__fgetc(FILE * file)56 static int __fgetc(FILE *file)
57 {
58     if (file == &__stdio_in)
59     {
60 #ifdef RT_USING_POSIX_STDIO
61         if (rt_posix_stdio_get_console() >= 0)
62         {
63             char c;
64             int rc = read(STDIN_FILENO, &c, 1);
65             return rc == 1 ? c : EOF;
66         }
67 #endif /* RT_USING_POSIX_STDIO */
68     }
69 
70     return EOF;
71 }
72 
73 #endif
74