#![no_std] 表示该 crate 不自动链接 std,并使用 core 的 prelude。它不等于“没有操作系统”,也不等于“不能分配内存”:一个 no_std 库可以被普通 Linux 程序使用,也可以在提供合适运行支持的裸机环境里使用。
内核模块的难点也不只是去掉 std。它必须遵守内核的资源生命周期、分配上下文、锁规则与构建配置;把普通用户态 API 换个名字,并不能得到正确模块。
core 语言基础、迭代器、Option/Result、可用的原子类型 alloc(可选) Box、Vec、String 等;最终环境需提供分配支持 目标运行环境 入口、链接布局、panic 策略、设备与同步抽象 no_std 改变库依赖,不自动建立裸机或内核运行环境 std 应用也能使用 no_std 库;内核依赖它自己的 API 和构建系统。
core、alloc、std 分别提供什么
层次 常见能力 依赖条件
core Option、Result、Iterator、基础类型、格式化接口 不依赖堆;部分原子能力受 target 限制
alloc Box、Vec、String、Rc、适用目标上的 Arc、BTreeMap 需要最终程序的分配支持
std 文件、网络、线程等平台接口,以及 core/alloc 的再导出 目标平台需有对应实现
HashMap 不在 alloc 中;需要按目标选择额外实现或使用其他集合。format_args! 构造格式化参数,本身不要求分配 String;alloc::format! 才分配字符串。提供 core::fmt::Write 可以把格式化输出写入固定缓冲或设备,不等于必须先实现堆分配。alloc 文档
no_std 也不是一个“保证依赖图完全没有 std”的检查器。某个依赖的默认 feature 仍可能引入 std,需检查目标与 feature 组合;对于 std 根本不可用的目标,相关依赖会在构建阶段暴露出来。Rust crate 规则
no_std 去掉哪一层依赖?
从一个只解析切片的核心开始,逐项增加需求。固定缓冲格式化仍可以留在 core;增加 Vec 才引入 alloc 的责任,使用 std::fs 则需要平台接口。这些是依赖能力的变化,不能用 no_std 一个开关同时解释是否有堆、是否有操作系统和谁提供程序入口。
正在呈现知识画面 重新加载
no_std 去掉哪一层依赖? no_std 核心可以使用固定缓冲;Vec 需要 alloc 和最终分配支持,文件接口需要 std 或目标适配。
{"id":"rust-no-std-layers","title":"no_std 去掉哪一层依赖?","summary":"no_std 核心可以使用固定缓冲;Vec 需要 alloc 和最终分配支持,文件接口需要 std 或目标适配。","height":1000,"html":"<h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p><label class=\"check\"><input type=\"checkbox\" id=\"vector\"><span data-i18n=\"vector\"></span></label><label class=\"check\"><input type=\"checkbox\" id=\"file\"><span data-i18n=\"file\"></span></label><label class=\"check\"><input type=\"checkbox\" id=\"format\" checked><span data-i18n=\"format\"></span></label><div class=\"track-row\"><span data-i18n=\"layers\"></span><div id=\"layers\" class=\"track\"></div></div><section class=\"panel\"><h3 data-i18n=\"requirements\"></h3><div id=\"requirements\"></div></section><details class=\"scope\"><summary data-i18n=\"scopeLabel\"></summary><p data-i18n=\"scope\"></p></details>","css":".intro{margin:8px 0 18px;color:var(--muted);font-size:14px}.caption,.hint{font-size:12px;color:var(--muted);margin-top:12px}.control{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;align-items:center;margin:14px 0;font-size:13px}.control label{font-size:13px}.control output{color:var(--accent);min-width:5em;text-align:right;font-variant-numeric:tabular-nums}.control input{grid-column:1/-1;width:100%;margin:0}.presets{display:flex;gap:4px;align-items:stretch}.presets button{flex:1 1 0;min-width:0;overflow-wrap:anywhere;font-size:13px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0}.actions button{flex:1;min-width:0;font-size:13px;min-height:42px}.copy{display:grid;font-size:14px;margin:16px 0}.copy>*{grid-area:1/1;margin:0}.reserve{visibility:hidden}.scope{margin-top:14px;color:var(--muted);font-size:12px}.scope summary{padding:8px 0;cursor:pointer}.scope p{margin-top:10px}.two{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.card{border:1px solid var(--rule);border-radius:9px;padding:14px;min-width:0}.card header{font-size:14px;font-weight:600;margin-bottom:10px}.card button{font-size:12px;width:100%;min-width:0}.card small{display:block;font-size:12px;color:var(--muted)}.card code{font-size:12px;overflow-wrap:anywhere}.metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.metrics>div{border-left:2px solid var(--accent);padding-left:10px;min-width:0}.metrics span{display:block;min-height:3.2em;color:var(--muted);font-size:12px}.metrics strong{font-size:23px;display:block;font-weight:550;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.formula{border-top:1px solid var(--rule);padding-top:12px;margin-top:14px;font-size:13px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.value{font:550 20px ui-monospace,monospace}.legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:12px;color:var(--muted);margin:12px 0}.legend span:before{content:'';display:inline-block;width:8px;height:8px;border-radius:2px;background:var(--accent);margin-right:6px}.legend .second:before{background:var(--second)}.check{display:flex;align-items:center;gap:8px;font-size:13px;margin:12px 0}.check input{width:16px;height:16px;flex-shrink:0;accent-color:var(--accent)}select,input[type=text],input[type=number]{background:var(--paper);color:var(--ink);font:inherit;font-size:13px;padding:10px;border:1px solid var(--rule);border-radius:7px;max-width:100%;min-width:0}select{width:100%;min-height:42px}.band{height:20px;display:flex;background:var(--surface);border-radius:4px;overflow:hidden}.band i{height:100%;display:block;background:var(--accent);transition:width .25s}.band i.second{background:var(--second)}button:disabled{cursor:default}.status{font-size:13px;min-height:4.8em}.mono{font-family:ui-monospace,monospace;font-variant-numeric:tabular-nums}.muted{color:var(--muted)}\n@media(max-width:480px){.two{gap:8px}.card{padding:12px 9px}.actions button,.presets button{font-size:12px}.metrics strong{font-size:20px}.metrics{gap:8px}}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important}}\n.track-row{margin:16px 0}.track-row>span{display:block;font-size:12px;color:var(--muted);margin-bottom:7px}.track{display:flex;gap:5px;min-width:0}.cell{flex:1;min-width:0;min-height:48px;border:1px solid var(--rule);border-radius:5px;background:var(--surface);display:flex;align-items:center;justify-content:center;text-align:center;padding:5px 3px;font-size:12px;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.cell.on{background:var(--accent-soft);border-color:var(--accent)}.cell.gold{background:var(--second-soft);border-color:var(--second)}.cell.empty{border-style:dashed;color:var(--muted)}.cell.error{border-color:var(--second);text-decoration:line-through}.choices{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:14px 0}.choices button{min-width:0;padding:10px 4px;font-size:12px;overflow-wrap:anywhere}.choices button[aria-current=true]{border-color:var(--accent);background:var(--accent-soft)}.relation{display:grid;grid-template-columns:minmax(0,1fr) 28px minmax(0,1fr);align-items:center;gap:6px;margin:12px 0}.relation .cell{min-height:72px}.relation>i{text-align:center;font-style:normal;color:var(--accent)}.readout{font-size:13px;white-space:pre-line;min-height:6.4em;overflow-wrap:anywhere}.plot{position:relative;border-left:1px solid var(--rule);border-bottom:1px solid var(--rule);padding:8px 0;margin:18px 0}.plot-row{height:28px;position:relative;margin:4px 0;background:var(--surface)}.plot-row i{position:absolute;inset-block:5px;background:var(--accent);min-width:2px;transition:width .2s,left .2s}.plot-row b{position:relative;padding:4px 6px;font:11px/28px ui-monospace,monospace;background:var(--paper);border-radius:3px}.axis{display:flex;justify-content:space-between;font-size:11px;color:var(--muted)}\n\n/* Action labels must remain readable across locales and narrow embeds. */\n.actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}\n.actions button{overflow-wrap:anywhere;white-space:normal;min-height:58px;padding:8px}\nbutton{overflow-wrap:anywhere}\n@media(min-width:640px){.actions{grid-template-columns:repeat(3,minmax(0,1fr))}}\n\n.metrics span{overflow-wrap:anywhere}\n.panel{border:1px solid var(--rule);border-radius:9px;padding:12px;margin:14px 0;min-width:0}.panel h3{font-size:13px;margin:0 0 10px;color:var(--muted)}.source{font:13px/1.8 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0}.source mark{background:var(--accent-soft);color:var(--ink);border-bottom:2px solid var(--accent)}.source .fault{background:var(--second-soft);border-color:var(--second)}.diagram{display:block;width:100%;height:auto;max-height:320px;margin:14px 0;overflow:visible}.diagram text{fill:var(--ink);font:12px ui-monospace,monospace}.diagram .edge{stroke:var(--muted);stroke-width:1.5;fill:none}.diagram .edge.on{stroke:var(--accent);stroke-width:3}.diagram .node{fill:var(--surface);stroke:var(--rule);stroke-width:1.5}.diagram .node.on{fill:var(--accent-soft);stroke:var(--accent)}.diagram .node.gold{fill:var(--second-soft);stroke:var(--second)}.log{font:12px/1.8 ui-monospace,monospace;white-space:pre-line;overflow-wrap:anywhere;min-height:7.2em}.table{display:grid;gap:5px;margin:14px 0}.table .tr{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}.table .tr>*{padding:8px 5px;background:var(--surface);border-radius:4px;min-width:0;overflow-wrap:anywhere;font-size:12px}.table .tr .on{background:var(--accent-soft)}.table .tr .gold{background:var(--second-soft)}.choices button{min-height:44px}.metrics strong{min-height:1.6em}.code-line{display:block}.code-line.on{background:var(--accent-soft);border-left:2px solid var(--accent);padding-left:6px}.status-badge{font-size:12px;color:var(--accent)}.tile-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}.tile-grid .cell{min-height:40px}.actions button{min-height:48px}.form-field{display:grid;gap:8px;margin:14px 0;font-size:13px}.form-field input{width:100%;font-family:ui-monospace,monospace}.metrics.three{grid-template-columns:repeat(3,minmax(0,1fr))}.formula{min-height:3.2em}.presets{flex-wrap:wrap}.presets button{flex-basis:25%;min-height:44px}\n\n.budget{display:flex;height:28px;margin:16px 0;background:var(--surface);border-radius:5px;overflow:hidden}.budget i{display:block;background:var(--accent);transition:width .2s}.budget i.gold{background:var(--second)}.intervals{margin:16px 0}.interval{position:relative;height:36px;background:var(--surface);margin:6px 0;border-radius:4px;overflow:hidden}.interval i{position:absolute;height:100%;background:var(--accent-soft);border-left:2px solid var(--accent)}.interval i.gold{background:var(--second-soft);border-color:var(--second)}.interval span{position:relative;z-index:1;font:12px/36px ui-monospace,monospace;padding-left:7px}.table .tr>*{min-height:4.8em}.formula{white-space:pre-line;min-height:7.2em}.actions:has(>button:only-child){grid-template-columns:1fr}.metrics strong{min-height:3.2em}.rangegrid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:3px;margin:14px 0}.rangegrid .cell{min-height:30px;padding:3px 1px;font-size:10px}.message{min-height:7.2em;white-space:pre-line;font:13px/1.8 ui-monospace,monospace;overflow-wrap:anywhere}\n/* Allow CJK hanging punctuation without overflowing a metric's border box. */\n.metrics>div{padding-right:4px}.metrics span{line-break:anywhere}\n\n.chart-wrap{margin:18px 0}.chart-label{font-size:12px;color:var(--muted);min-height:3.2em}.curve{display:block;width:100%;height:auto;max-height:320px;overflow:visible}.curve text{font:11px ui-monospace,monospace;fill:var(--muted)}.gridline{stroke:var(--rule);stroke-width:1}.metrics strong{font-size:20px;min-height:3.2em}.formula{font:12px/1.8 ui-monospace,monospace;min-height:9em}.readout{min-height:8em}.presets button{flex-basis:30%}.scope p{overflow-wrap:anywhere} .unit-note{font-size:12px;color:var(--muted);margin:10px 0}\n\n.metrics span{word-break:break-all;line-break:strict}.metrics>div{padding-right:6px}\n\n.cell{min-height:72px}.metrics strong{min-height:3.6em}\n\n#requirements{min-height:20em;font-size:13px;white-space:pre-line}","js":"const $=s=>document.querySelector(s);const set=(id,v)=>$('#'+id).textContent=v;const t=k=>viz.t(k);function cells(id,values){$('#'+id).replaceChildren(...values.map(v=>{const e=document.createElement('div');e.className='cell '+(v.cls||'');e.textContent=v.text;e.title=v.title||v.text;return e;}));}function pressed(mode){document.querySelectorAll('[data-mode]').forEach(e=>e.setAttribute('aria-pressed',String(e.dataset.mode===mode)));}const esc=s=>String(s).replace(/[&<>\"']/g,c=>({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''}[c]));const fmt=s=>'{'+[...s].sort().join(', ')+'}';function graph(id,nodes,edges){const el=$('#'+id);el.setAttribute('viewBox','0 0 360 200');el.innerHTML='<defs><marker id=\"arrow-'+id+'\" viewBox=\"0 0 10 10\" refX=\"8\" refY=\"5\" markerWidth=\"5\" markerHeight=\"5\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 5 L 0 10 z\" fill=\"var(--muted)\"/></marker></defs>'+edges.map(e=>{const a=nodes[e[0]],b=nodes[e[1]],dx=b.x-a.x,dy=b.y-a.y,d=Math.hypot(dx,dy)||1;if(edges.some(r=>r[0]===e[1]&&r[1]===e[0])){const nx=-dy/d,ny=dx/d;return '<path class=\"edge '+(e[2]?'on':'')+'\" d=\"M '+(a.x+dx/d*22+nx*12)+' '+(a.y+dy/d*22+ny*12)+' Q '+((a.x+b.x)/2+nx*38)+' '+((a.y+b.y)/2+ny*38)+' '+(b.x-dx/d*25+nx*12)+' '+(b.y-dy/d*25+ny*12)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}return '<line class=\"edge '+(e[2]?'on':'')+'\" x1=\"'+(a.x+dx/d*25)+'\" y1=\"'+(a.y+dy/d*25)+'\" x2=\"'+(b.x-dx/d*28)+'\" y2=\"'+(b.y-dy/d*28)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}).join('')+nodes.map(n=>'<g><circle class=\"node '+(n.cls||'')+'\" cx=\"'+n.x+'\" cy=\"'+n.y+'\" r=\"25\"/><text x=\"'+n.x+'\" y=\"'+(n.y+4)+'\" text-anchor=\"middle\">'+esc(n.name)+'</text>'+(n.sub?'<text x=\"'+n.x+'\" y=\"'+(n.y+43)+'\" text-anchor=\"middle\">'+esc(n.sub)+'</text>':'')+'</g>').join('');}function table(id,rows){$('#'+id).classList.add('table');$('#'+id).replaceChildren(...rows.map(r=>{const row=document.createElement('div');row.className='tr';row.style.gridTemplateColumns='repeat('+r.length+',minmax(0,1fr))';r.forEach(x=>{const c=document.createElement('div');if(typeof x==='object'){c.textContent=x.text;c.className=x.cls||'';}else c.textContent=x;row.append(c)});return row;}));}function band(id,parts,total){$('#'+id).replaceChildren(...parts.map((p,i)=>{const e=document.createElement('i');e.style.width=(100*p.value/total)+'%';e.className=i%2?'gold':'on';e.title=p.name+': '+p.value;return e}));}function intervals(id,items,total){$('#'+id).replaceChildren(...items.map(p=>{const row=document.createElement('div');row.className='interval';const bar=document.createElement('i');bar.style.left=(100*p.start/total)+'%';bar.style.width=(100*(p.end-p.start)/total)+'%';bar.className=p.cls||'';const label=document.createElement('span');label.textContent=p.label;row.append(bar,label);return row;}));}function plot(id,series,xr,yr,opts={}){const e=$('#'+id),X=x=>42+(x-xr[0])/(xr[1]-xr[0])*298,Y=y=>175-(y-yr[0])/(yr[1]-yr[0])*148;let out='<defs><clipPath id=\"clip-'+id+'\"><rect x=\"42\" y=\"27\" width=\"298\" height=\"148\"/></clipPath></defs>';for(let i=0;i<3;i++){let x=xr[0]+i*(xr[1]-xr[0])/2,y=yr[0]+i*(yr[1]-yr[0])/2;out+='<path class=\"gridline\" d=\"M '+X(x)+' 27V175M42 '+Y(y)+'H340\"/><text x=\"'+X(x)+'\" y=\"194\" text-anchor=\"middle\">'+esc(opts.xfmt?opts.xfmt(x):Number(x.toFixed(2)))+'</text><text x=\"36\" y=\"'+(Y(y)+4)+'\" text-anchor=\"end\">'+esc(opts.yfmt?opts.yfmt(y):Number(y.toFixed(2)))+'</text>';}out+='<g clip-path=\"url(#clip-'+id+')\">';for(const s of series){out+='<path fill=\"none\" stroke=\"'+(s.color||'var(--accent)')+'\" stroke-width=\"2.5\" '+(s.dash?'stroke-dasharray=\"5 4\"':'')+' d=\"'+s.pts.map((p,i)=>(i?'L':'M')+X(p[0]).toFixed(2)+','+Y(p[1]).toFixed(2)).join(' ')+'\"/>';}for(const p of opts.points||[])out+='<circle cx=\"'+X(p[0])+'\" cy=\"'+Y(p[1])+'\" r=\"4\" fill=\"var(--second)\" stroke=\"var(--paper)\" stroke-width=\"1.5\"/>';if(opts.cursor!==undefined)out+='<path d=\"M'+X(opts.cursor)+' 27V175\" stroke=\"var(--muted)\" stroke-dasharray=\"3 3\"/>';e.innerHTML=out+'</g>';e.dataset.curves=JSON.stringify(series.map(s=>s.pts));}const curve=(fn,lo,hi,n=120)=>Array.from({length:n+1},(_,i)=>{const x=lo+(hi-lo)*i/n;return[x,fn(x)]});function inputs(draw){document.querySelectorAll('input,select').forEach(e=>{e.addEventListener('input',draw);e.addEventListener('change',draw)});draw()}const n=id=>+$('#'+id).value;const show=(id,v,d=3)=>set(id,Number(v.toFixed(d)));function draw(){let v=$('#vector').checked,f=$('#file').checked,fmt=$('#format').checked;cells('layers',[{text:'core',cls:'on'},{text:'alloc',cls:v||f?'gold':'empty'},{text:'std',cls:f?'gold':'empty'}]);set('requirements',[t('base'),fmt?t('fmt'):'',v?t('alloc'):'',f?t('std'):''].filter(Boolean).join('\\n\\n'));document.body.dataset.std=f;}inputs(draw);","audio":false,"strings":{"alloc":"alloc::Vec:最终程序负责分配支持。","base":"core:切片解析,不需要堆分配。","file":"需要 std::fs","fmt":"core::fmt::Write:调用者提供固定缓冲。","format":"需要固定缓冲格式化","heading":"no_std 去掉哪一层依赖?","intro":"选择需要的功能,区分 core、alloc 与平台 std 接口。","layers":"需要接入的层","requirements":"最终环境要提供什么","reset":"重置","scope":"展示标准库中的能力来源;最终入口、panic handler、原子支持等仍由目标与产物种类决定。","scopeLabel":"模型范围与约定","std":"std::fs:需要目标平台实现;no_std 不能凭空提供文件系统。","vector":"需要 Vec"}}
从不需要运行时的库开始
下面是一个无堆分配的解析函数。调用者提供输入切片,返回解析结果或明确错误:
#! [ no_std ]
pub fn read_be_u16 ( input : & [u8 ]) -> Option< u16 > {
let bytes: [ u8 ; 2 ] = input.get ( .. 2 ) ? .try_into ( ) .ok ( ) ? ;
Some ( u16 :: from_be_bytes( bytes) )
}
保存为 nostd.rs,用 rustc --edition=2024 --crate-type=rlib nostd.rs 编译。这里构建的是可供其他程序链接的库,不需要自己定义 _start、panic_handler 或链接脚本。可以由普通 std 测试程序调用它,验证空输入、短输入和正确大小端。
这种拆分有实际价值:协议解析、状态机和数据处理尽量放在可测试的核心库,设备访问、调度和分配策略放在目标适配层。no_std 是实现这种依赖边界的一种方式。
在 std 宿主上验证 no_std 核心
将前面的文件作为名为 parser 的库编译,另建下面的 check.rs。库仍不依赖 std,测试入口则使用宿主运行环境。
fn main ( ) {
assert_eq! ( parser:: read_be_u16( & [ ] ) , None ) ;
assert_eq! ( parser:: read_be_u16( & [ 0x12 ] ) , None ) ;
assert_eq! ( parser:: read_be_u16( & [ 0x12 , 0x34 ] ) , Some ( 0x1234 ) ) ;
assert_eq! ( parser:: read_be_u16( & [ 0x12 , 0x34 , 0xff ] ) , Some ( 0x1234 ) ) ;
}
rustc -- edition= 2024 -- crate-name parser -- crate-type= rlib nostd.rs - o libparser.rlib
rustc -- edition= 2024 check.rs -- extern parser=libparser.rlib - o check
./check
最后一个断言明确了这个接口只读前两个字节,允许后面还有输入;如果协议要求报文必须恰好两字节,应在入口另外检查长度。宿主执行验证解析契约,但不能代替目标上的对齐、原子能力、链接和硬件行为检查。
固定缓冲也可以使用格式化接口
下面单独保存为 fixed.rs,是完全不使用 alloc 的库。缓冲区只接受完整 UTF-8 片段;空间不足时当前 write_str 调用保持原值。字段私有,使调用者不能伪造 len 或向已使用区域写入非法编码。
#! [ no_std ]
use core:: fmt:: { self , Write} ;
pub struct FixedText < const N: usize > {
bytes : [u8 ; N],
len : usize ,
}
impl < const N: usize > FixedText < N> {
pub fn new ( ) -> Self { Self { bytes: [ 0 ; N] , len: 0 } }
pub fn as_str ( & self ) -> & str {
core:: str:: from_utf8( & self .bytes[ .. self .len] ) .expect ( " UTF-8 invariant" )
}
pub fn replace_fmt ( & mut self , args : fmt:: Arguments< '_ > ) -> fmt:: Result {
let mut next = Self :: new( ) ;
next.write_fmt ( args) ? ;
* self = next;
Ok ( ( ) )
}
}
impl < const N: usize > Write for FixedText < N> {
fn write_str ( & mut self , text : & str ) -> fmt:: Result {
let end = self .len.checked_add ( text.len ( ) ) .ok_or ( fmt:: Error) ? ;
let destination = self .bytes.get_mut ( self .len.. end) .ok_or ( fmt:: Error) ? ;
destination.copy_from_slice ( text.as_bytes ( ) ) ;
self .len = end;
Ok ( ( ) )
}
}
宿主程序使用这份库时,可把格式化结果写入固定空间,也可检验容量不足的结果:
use core:: fmt:: { self , Write} ;
use fixed:: FixedText;
struct TwoParts ;
impl fmt:: Display for TwoParts {
fn fmt ( & self , out : & mut fmt:: Formatter< '_ > ) -> fmt:: Result {
out.write_str ( " ok" ) ? ;
out.write_str ( " toolong" )
}
}
fn main ( ) {
let mut text = FixedText:: < 8> :: new( ) ;
write! ( &mut text, " n={} " , 42 ) .unwrap ( ) ;
assert_eq! ( text.as_str ( ) , " n=42" ) ;
assert! ( text.write_str ( " 中中" ) .is_err ( ) ) ;
assert_eq! ( text.as_str ( ) , " n=42" ) ;
let mut partial = FixedText:: < 4> :: new( ) ;
assert! ( write! ( &mut partial, " {TwoParts} " ) .is_err ( ) ) ;
assert_eq! ( partial.as_str ( ) , " ok" ) ;
let mut committed = FixedText:: < 4> :: new( ) ;
committed.write_str ( " old" ) .unwrap ( ) ;
assert! ( committed.replace_fmt ( format_args! ( " {TwoParts}" ) ) .is_err ( ) ) ;
assert_eq! ( committed.as_str ( ) , " old" ) ;
}
类似 parser,先以 --crate-name fixed --crate-type=rlib 编译库,再通过 --extern fixed=libfixed.rlib 链接宿主程序。TwoParts 有意分两次写出,说明“一次 write_str 失败不变”不等于“整个 write! 失败不变”:前一个片段已写入,后一个才溢出。
replace_fmt 先写入临时固定缓冲,成功才替换当前值,提供整个输出的提交边界;代价是临时多占 N 字节存储。无堆分配并不意味着内存使用可以忽略,大 N 的局部对象仍会挤压栈空间。这里的 fmt::Error 只表示格式化无法继续;若设备写入需要携带详细 I/O 错误,应额外设计错误保存或接口。core::fmt::Write
alloc 可选,但最终分配责任不会消失
一个使用分配的 no_std 库可以这样写:
#! [ no_std ]
extern crate alloc;
use alloc:: vec:: Vec;
pub fn copy_bytes ( input : & [u8 ])
-> Result< Vec< u8 > , alloc:: collections:: TryReserveError>
{
let mut out = Vec :: new( ) ;
out.try_reserve_exact ( input.len ( ) ) ? ;
out.extend_from_slice ( input) ;
Ok ( out)
}
预留空间成功后,复制 u8 不需要进一步扩容。这个函数把容量/分配失败通过 Result 交给调用者,但不证明整个程序所有分配都可恢复。最终可执行环境仍需要满足 alloc 所需的全局分配等链接条件;普通 std 程序通常已经提供。
裸机自定义分配器还必须满足对齐、布局匹配、并发与中断上下文等约定。不能把一个 bump 指针示例当作已可用于任意多线程程序的 GlobalAlloc 实现。
no_main、panic 与硬件启动是另一组决定
#![no_main] 禁用通常的 main 入口安排,不由 no_std 自动隐含。裸机可执行文件通常需要目标启动代码、初始栈、链接布局、数据初始化和中断向量;这些取决于芯片及运行框架,不能用一个空 loop 代表所有启动工作。
最终无 std 程序通常要由某处提供 panic handler,而每个库都自行定义会导致重复。panic handler 可以按平台记录日志、复位或停止,并非天生不能输出;是否支持展开由目标、运行时和构建策略共同决定。Embedded Rust 的 no_std
同样,忙循环不等于低功耗等待,中断是否打开、看门狗是否复位都可能影响它的实际行为。这些属于目标运行环境,应在平台教程中明确。
Rust-for-Linux:以目标内核源码为接口
Linux 6.1 合入了初步 Rust 支持,不代表之后所有架构、配置或发行版都能直接构建任意 Rust 模块。内核 Rust API 持续演进,旧博客中的 kernel::file::Operations 等代码不能当作所有版本的可编译模板。
以 Linux v6.18 的 rust_minimal 为阅读起点:module! 声明模块元信息,Module::init 返回模块状态,Drop 处理退出时的清理;示例使用 KVec,并在 push 时显式传入 GFP_KERNEL、用 ? 传播失败。这比把用户态 Vec、文件操作 trait 与虚构签名拼起来更能反映实际接口。v6.18 最小模块
学习时先在目标内核源码树中核对依赖,再构建该版本自带样例:
make LLVM=1 rustavailable
随后按该树的配置依赖启用 Rust 与相应样例,使用内核构建系统完成构建。rustavailable 检查工具支持,不替代配置与实际编译;Rust、bindgen、LLVM 的要求应按目标版本文档读取,而不是固定写成“随便装一个最新版本”。内核 Rust Quick Start
内核中的所有权还受执行上下文约束
用户态直觉 内核中还要追问
分配成功后再使用 当前位置是否允许睡眠?分配失败怎样返回?
加 Mutex 即可 当前是否处于中断/原子上下文?锁顺序如何保证?
Drop 自动清理 对象是否仍被回调、工作队列或设备访问?清理能否阻塞?
一个引用计数就够 设备移除、模块卸载与异步执行如何协调?
内核提供自己的分配、同步和错误抽象,不能用 std::sync::Mutex 或用户态线程模型直接代替。unsafe 封装必须把这些额外条件纳入契约,借用检查器不会自行理解硬件仍在 DMA 或某个 C 回调尚未结束。
内核 panic 行为也不能概括成“一定 BUG() 并停止整个内核”。实现随版本与配置变化,异常后的影响取决于具体内核路径;应查看目标版本的 panic handler 与运行策略。无论结果怎样,panic 都不是内核中处理普通可预期失败的替代品。内核 Rust 概览
纯逻辑库 长度、溢出、状态不变量 目标编译与链接 目标 core / ABI / 符号 目标环境执行 启动、设备、中断、资源退出 每层新增条件,也保留上一层的契约 逐层验证:宿主通过不会自动补齐目标运行环境 内核模块使用目标源码树的构建入口,不自行安装用户态全局分配器或启动代码。
把初始化和退出看成资源依赖关系
设一个设备对象先取得资源,再注册回调,最后允许工作队列使用它。初始化在第二步失败时,第一步的资源应由已建立的拥有者回收;注册成功后再失败,则还需取消注册并按子系统约定等待在途使用结束。退出时的关键不是机械地调用几个 free,而是先停止新增访问,再结束已有访问,最后释放被引用的状态。
借用与引用计数有助于表达软件对象的寿命,但 DMA、硬件中断和 C 保存的 context 不会自动变成 Rust 引用。必须由目标子系统的停机、同步和注销接口建立“最后一次访问已经结束”的事实,再允许 Drop 释放。某些注销会等待或睡眠,这又要求退出发生在允许阻塞的上下文。
检查结果 已获得的证据 尚未覆盖
no_std rlib 编译成功 该库在此目标和 feature 下能编译 最终入口、分配器和运行环境
std 宿主边界测试通过 测试输入对应的逻辑行为 目标硬件、中断与内核上下文
rustavailable 成功 目标源码树认可当前 Rust 工具支持 所需配置、模块链接和加载
模块完成构建 所选源码/配置能生成模块产物 设备交互、卸载竞态和压力行为
推荐的学习推进顺序
先把纯数据处理写成可在宿主测试的 no_std 库;再在目标运行框架中接入 panic、日志与分配;最后阅读目标内核版本中已存在的设备或子系统样例,逐项理解其生命周期。这样能区分语言问题、目标运行时问题和内核接口问题,避免一次承担三层未知条件。