Loading...
Loading...
Compare original and translation side by side
#![no_std]coreallocstdno_std#![no_std]coreallocstdno_std#![no_std]// src/lib.rs
#![no_std]
// core is always available (no OS needed)
use core::fmt;
use core::mem;
use core::slice;
// alloc: heap collections — requires a global allocator
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use alloc::{vec::Vec, string::String, boxed::Box, format};
pub fn add(a: u32, b: u32) -> u32 {
a + b
}undefined// src/lib.rs
#![no_std]
// core始终可用(无需操作系统)
use core::fmt;
use core::mem;
use core::slice;
// alloc:堆集合 — 需要全局分配器
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use alloc::{vec::Vec, string::String, boxed::Box, format};
pub fn add(a: u32, b: u32) -> u32 {
a + b
}undefinedundefinedundefined| Crate | 需要操作系统 | 需要堆 | 提供功能 |
|---|---|---|---|
| 否 | 否 | 基础类型、trait、迭代器、格式化、内存操作、指针、切片、Option、Result |
| 否 | 是(需分配器) | Vec、String、Box、Arc、Rc、HashMap(需要全局分配器) |
| 是 | 是 | 包含core和alloc的所有内容 + 操作系统API(线程、文件、套接字、环境变量) |
stdcoreallocstduse std::fmtuse core::fmtcore// 这些在no_std环境中可正常使用:
core::fmt::Write // write!宏对应的trait
core::iter // 迭代器
core::ops // 运算符(+、-、*、Deref等)
core::option::Option
core::result::Result
core::mem::{size_of, align_of, swap, replace}
core::ptr::{read, write, null, NonNull}
core::slice, core::str
core::sync::atomic // 原子类型
core::cell::{Cell, UnsafeCell, RefCell}
core::cmp, core::convert, core::clone, core::default
core::num // 数值转换
core::panic::PanicInfo // 用于panic处理器| Crate | Requires OS | Requires heap | Provides |
|---|---|---|---|
| No | No | Primitives, traits, iter, fmt, mem, ptr, slice, option, result |
| No | Yes (allocator) | Vec, String, Box, Arc, Rc, HashMap (requires global allocator) |
| Yes | Yes | All of core + alloc + OS APIs (threads, files, sockets, env) |
stdcoreallocuse std::fmtuse core::fmtstdcore// These work in no_std:
core::fmt::Write // trait for write! macro
core::iter // iterators
core::ops // operators (+, -, *, Deref, etc.)
core::option::Option
core::result::Result
core::mem::{size_of, align_of, swap, replace}
core::ptr::{read, write, null, NonNull}
core::slice, core::str
core::sync::atomic // atomic types
core::cell::{Cell, UnsafeCell, RefCell}
core::cmp, core::convert, core::clone, core::default
core::num // numeric conversions
core::panic::PanicInfo // for panic handlerno_stdalloc// src/allocator.rs — 使用linked_list_allocator的嵌入式分配器
use linked_list_allocator::LockedHeap;
#[global_allocator]
static ALLOCATOR: LockedHeap = LockedHeap::empty();
pub fn init_heap(heap_start: usize, heap_size: usize) {
unsafe {
ALLOCATOR.lock().init(heap_start as *mut u8, heap_size);
}
}[dependencies]
linked-list-allocator = { version = "0.10", default-features = false }// src/main.rs(裸机环境)
#![no_std]
#![no_main]
extern crate alloc;
use alloc::vec::Vec;
mod allocator;
// 在初始化代码中(BSS/data初始化完成后):
allocator::init_heap(0x20010000, 0x10000); // 在RAM+64KB处分配64KB堆空间
// 现在可以使用分配类型:
let mut v: Vec<u32> = Vec::new();
v.push(42);linked-list-allocatorno_stdbuddy-allocdlmalloctalcallocno_std// src/allocator.rs — embedded allocator using linked_list_allocator
use linked_list_allocator::LockedHeap;
#[global_allocator]
static ALLOCATOR: LockedHeap = LockedHeap::empty();
pub fn init_heap(heap_start: usize, heap_size: usize) {
unsafe {
ALLOCATOR.lock().init(heap_start as *mut u8, heap_size);
}
}[dependencies]
linked-list-allocator = { version = "0.10", default-features = false }// src/main.rs (bare-metal)
#![no_std]
#![no_main]
extern crate alloc;
use alloc::vec::Vec;
mod allocator;
// In init code (after BSS/data init):
allocator::init_heap(0x20010000, 0x10000); // 64KB heap at RAM+64KB
// Now alloc types work:
let mut v: Vec<u32> = Vec::new();
v.push(42);linked-list-allocatorno_stdbuddy-allocdlmalloctalcno_std// 选项1:panic时暂停(最简单,适用于生产环境)
use core::panic::PanicInfo;
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {} // 无限循环
}
// 选项2:通过defmt打印panic信息(带调试探针的嵌入式环境)
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
defmt::error!("{}", defmt::Display2Format(info));
cortex_m::asm::udf(); // 未定义指令 → 硬 fault
}
// 选项3:使用panic crate(在Cargo.toml中添加)
// panic-halt = "0.2" — 自旋循环
// panic-reset = "0.1.1" — 重置MCU
// panic-probe = "0.3" — defmt + probe-rsno_std// Option 1: halt on panic (simplest, production)
use core::panic::PanicInfo;
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {} // spin forever
}
// Option 2: print panic info via defmt (embedded with debug probe)
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
defmt::error!("{}", defmt::Display2Format(info));
cortex_m::asm::udf(); // undefined instruction → hard fault
}
// Option 3: use a panic crate (in Cargo.toml)
// panic-halt = "0.2" — spin loop
// panic-reset = "0.1.1" — reset MCU
// panic-probe = "0.3" — defmt + probe-rsalloc#![no_std]
#[cfg(feature = "alloc")]
extern crate alloc;
pub struct Parser<'a> {
data: &'a [u8], // 借用的切片:无需分配
pos: usize,
}
impl<'a> Parser<'a> {
pub fn new(data: &'a [u8]) -> Self {
Parser { data, pos: 0 }
}
// 核心API:返回借用的数据,无需分配
pub fn next_token(&mut self) -> Option<&'a [u8]> { /* ... */ None }
// 分配API:仅当启用alloc特性时可用
#[cfg(feature = "alloc")]
pub fn collect_all(&mut self) -> alloc::vec::Vec<&'a [u8]> {
let mut tokens = alloc::vec::Vec::new();
while let Some(tok) = self.next_token() {
tokens.push(tok);
}
tokens
}
}alloc#![no_std]
#[cfg(feature = "alloc")]
extern crate alloc;
pub struct Parser<'a> {
data: &'a [u8], // borrowed slice: no allocation needed
pos: usize,
}
impl<'a> Parser<'a> {
pub fn new(data: &'a [u8]) -> Self {
Parser { data, pos: 0 }
}
// Core API: return borrowed data, no allocation
pub fn next_token(&mut self) -> Option<&'a [u8]> { /* ... */ None }
// Alloc API: only when alloc feature is enabled
#[cfg(feature = "alloc")]
pub fn collect_all(&mut self) -> alloc::vec::Vec<&'a [u8]> {
let mut tokens = alloc::vec::Vec::new();
while let Some(tok) = self.next_token() {
tokens.push(tok);
}
tokens
}
}undefinedundefined
```rust
// lib.rs
#![cfg_attr(not(test), no_std)] // 除测试外均为no_std
// 测试代码正常使用std编译 — 仅库代码为no_stdundefined
```rust
// lib.rs
#![cfg_attr(not(test), no_std)] // no_std except during tests
// Tests compile normally with std — only library code is no_stdundefined
```bash
```bashundefinedundefinedskills/embedded/embedded-rustskills/rust/rust-crossskills/rust/rust-unsafeskills/embedded/linker-scriptsskills/embedded/embedded-rustskills/rust/rust-crossskills/rust/rust-unsafeskills/embedded/linker-scripts