第26.15章:Freestanding API

English

1. 头文件边界

Freestanding 是头文件的属性,不是 hosted 二进制里的运行期开关。三个总括头文件标出边界:

头文件 包含什么 用途
<fast_io_core.h> 核心词汇、格式化、扫描、缓冲区、序列化、分配器。 最小的 freestanding 表面。
<fast_io_freestanding.h> 核心加 freestanding 容器、算法和缓冲设备。 通常的 freestanding 目标。
<fast_io_hosted.h> 增加原生文件、控制台、进程、线程、文件系统。 Hosted 目标。
<fast_io.h> Hosted 加遗留 iostream 桥。 教程的正常构建;freestanding 目标绝不要包含。

fast_io 模块使用同样的边界:目标不是 hosted 时, 它定义 FAST_IO_FREESTANDING 并省略 hosted 导出单元。 freestanding 模块仍然导出核心 I/O、容器和分配器。

2. 分配器契约

Freestanding 目标没有隐藏堆。默认分配器是 freestanding_global_allocator:fast_io 声明,你定义。 它在函数名里暴露两种失败策略:

函数 策略
allocate_aligned_conditional_zero_at_least_die(...) arena 耗尽时通过 fast_terminate() 终止。
allocate_aligned_conditional_zero_at_least_try(...) 通过 herbception 通道报告 std::errc::not_enough_memory。
deallocate_aligned_n(p, alignment, n) 释放块;arena 实现可以把它做成空操作。

返回类型是 allocation_least_result,即指针加可用大小。 generic_allocator_adapter 和 typed_generic_allocator_adapter 把原始分配器变成容器期望的接口。


using heap_a = ::fast_io::generic_allocator_adapter<my_arena>;
::fast_io::containers::vector<int, heap_a> v;
v.push_back(42);

没有退回 malloc,没有全局 operator new,也没有异常分配。 目标没有堆的话,需要堆的容器根本不会被实例化。

3. Freestanding 算法

fast_io::freestanding 命名空间提供容器或格式化器需要、 又不想拉进 <algorithm> 的算法:

分组 名字
复制与填充 copy、copy_n、copy_backward、 move_backward、fill、fill_n、 non_overlapped_copy、non_overlapped_copy_n、 overlapped_copy、overlapped_copy_n
内存 my_memcpy、my_memmove、my_memset、 my_memcmp、bytes_clear_n、 nonoverlapped_bytes_copy_n
查找与比较 find_if、find_not、find_last、 find_last_not、find_first_not_of、 find_last_of、find_last_not_of、 my_mismatch、equal、 lexicographical_compare、 lexicographical_compare_three_way、lower_bound
构造与旋转 uninitialized_copy、uninitialized_copy_n、 uninitialized_move_n、uninitialized_default_construct、 uninitialized_default_construct_n、uninitialized_fill、 uninitialized_fill_n、rotate、remove
Traits is_zero_default_constructible、 is_trivially_copyable_or_relocatable 及其 _v 形式。

这些就是 hosted 构建内部使用的同一批名字。它们由模块的 freestanding.inc 导出,模块使用者不需要头文件算法。

4. 没有控制台的 I/O

Freestanding 目标没有默认 stdout。print 和 println 仍然存在,但第一个参数必须是目标提供的设备: UART 缓冲区、framebuffer、环形缓冲区、宿主 mailbox。 不存在悄悄退回一个不存在的控制台。


::fast_io::obuffer_view out{uart_buffer, uart_buffer + sizeof(uart_buffer)};
::fast_io::io::println(out, "boot: ", stage);

错误同理:herbception 在返回路径上携带 domain 和 code。 没有 unwinder、frame table 或 personality routine。 连这些都不想付的目标可以用 _die 分配策略,在耗尽时终止。

5. 模块与头文件边界

模块导出分配适配器、原生分配器、freestanding 算法和核心 I/O 词汇。 freestanding_global_allocator 本身在头文件侧: 它是你实现的声明,不是库定义。fast_terminate 随 hosted 单元导出; freestanding 构建直接用目标的 trap,或选择匹配的分配策略。

不要在 freestanding 目标里包含 <fast_io.h>。 它会要求控制台、文件、进程和 iostream 桥。改用 <fast_io_freestanding.h> 或更小的核心头文件。

要点