Rust in Everything
基于 cu29-runtime 1.3.1

动手:用 150 行 Rust 实现微缩版编译期 CopperList 调度器

主线位置:全卷收官实战。我们把全卷学到的三大核心机制——静态元组 CopperList 槽位复用、Freezable 状态快照、RobotClockMock + SimOverride 字节级确定性重放——浓缩成一个 150 行、零外部依赖、可直接 rustc 编译运行的微缩引擎!

架构与数据流图

flowchart LR
  clk["MiniClock\n(Real 或 Mock AtomicU64)"] --> slot["CopperList<(CuMsg<f32>, CuMsg<f32>)>\n预分配环形槽位池 [Slot; 4]"]
  slot --> s1["ImuSource::process\n写入角速度 gx"]
  s1 --> s2["PidTask::process (含积分状态 integral)\n计算控制量 u"]
  s2 --> s3["MotorSink::process\n执行器输出"]
  s2 -.Freezable::freeze/thaw.- kf["KeyFrame 快照与录制日志\n支持 100% 比特级确定性重放"]

完整可运行代码(mini_copper.rs)

我们在 ssh cu 上验证了如下完整实现:

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

#[derive(Clone)]
pub struct MiniClock {
  mock_ns: Arc<AtomicU64>,
}

impl MiniClock {
  pub fn new_mock() -> Self {
    Self { mock_ns: Arc::new(AtomicU64::new(0)) }
  }
  pub fn advance_ns(&self, delta: u64) {
    self.mock_ns.fetch_add(delta, Ordering::SeqCst);
  }
  pub fn set_ns(&self, val: u64) {
    self.mock_ns.store(val, Ordering::SeqCst);
  }
  pub fn now_ns(&self) -> u64 {
    self.mock_ns.load(Ordering::SeqCst)
  }
}

#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub struct CuMsg<T: Copy + Default> {
  pub payload: Option<T>,
  pub process_start_ns: u64,
  pub process_end_ns: u64,
}

impl<T: Copy + Default> CuMsg<T> {
  pub fn reset(&mut self) {
    self.payload = None;
    self.process_start_ns = 0;
    self.process_end_ns = 0;
  }
}

pub type MyDataSet = (CuMsg<f32>, CuMsg<f32>);

#[derive(Clone, Copy, Default, Debug)]
pub struct CopperList<P: Copy + Default> {
  pub id: u64,
  pub msgs: P,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SimOverride {
  ExecutedBySim,
  ExecuteByRuntime,
}

pub struct ImuSource;
impl ImuSource {
  pub fn process(&mut self, cycle: u64, out: &mut CuMsg<f32>) {
    out.payload = Some((cycle as f32) * 0.1);
  }
}

#[derive(Clone, Copy, Default, Debug)]
pub struct PidTask {
  pub kp: f32,
  pub ki: f32,
  pub integral: f32,
}

impl PidTask {
  pub fn freeze(&self) -> f32 {
    self.integral
  }
  pub fn thaw(&mut self, saved_integral: f32) {
    self.integral = saved_integral;
  }
  pub fn process(&mut self, input: &CuMsg<f32>, output: &mut CuMsg<f32>) {
    if let Some(err) = input.payload {
      self.integral += err * 0.001;
      output.payload = Some(self.kp * err + self.ki * self.integral);
    }
  }
}

pub struct MiniRuntime<const NBCL: usize> {
  pub clock: MiniClock,
  pub pool: [CopperList<MyDataSet>; NBCL],
  pub next_id: u64,
  pub imu: ImuSource,
  pub pid: PidTask,
  pub last_motor_cmd: f32,
}

impl<const NBCL: usize> MiniRuntime<NBCL> {
  pub fn new(clock: MiniClock) -> Self {
    Self {
      clock,
      pool: [CopperList::default(); NBCL],
      next_id: 0,
      imu: ImuSource,
      pid: PidTask { kp: 2.0, ki: 0.5, integral: 0.0 },
      last_motor_cmd: 0.0,
    }
  }

  pub fn run_one_iteration<F>(&mut self, mut sim_cb: F) -> (CopperList<MyDataSet>, f32)
  where
    F: FnMut(&str, &mut MyDataSet) -> SimOverride,
  {
    let id = self.next_id;
    self.next_id += 1;
    let slot = &mut self.pool[(id as usize) % NBCL];
    slot.id = id;
    slot.msgs.0.reset();
    slot.msgs.1.reset();

    let keyframe = self.pid.freeze();

    // Step 0: Source
    slot.msgs.0.process_start_ns = self.clock.now_ns();
    if sim_cb("imu", &mut slot.msgs) == SimOverride::ExecuteByRuntime {
      self.imu.process(id, &mut slot.msgs.0);
    }
    slot.msgs.0.process_end_ns = self.clock.now_ns();

    // Step 1: Regular Task (PID)
    slot.msgs.1.process_start_ns = self.clock.now_ns();
    if sim_cb("pid", &mut slot.msgs) == SimOverride::ExecuteByRuntime {
      let (ref m0, ref mut m1) = slot.msgs;
      self.pid.process(m0, m1);
    }
    slot.msgs.1.process_end_ns = self.clock.now_ns();

    // Step 2: Sink
    if let Some(cmd) = slot.msgs.1.payload {
      self.last_motor_cmd = cmd;
    }
    (*slot, keyframe)
  }
}

fn main() {
  let clk = MiniClock::new_mock();
  let mut rt = MiniRuntime::<4>::new(clk.clone());
  let mut recorded = Vec::new();
  for _ in 0..10 {
    clk.advance_ns(1_000_000);
    recorded.push(rt.run_one_iteration(|_, _| SimOverride::ExecuteByRuntime));
  }

  // 从第 5 帧 KeyFrame 精确重放并验证比特级一致
  let clk_replay = MiniClock::new_mock();
  let mut rt_replay = MiniRuntime::<4>::new(clk_replay.clone());
  rt_replay.pid.thaw(recorded[5].1);
  rt_replay.next_id = 5;
  for (rec_cl, _) in &recorded[5..] {
    clk_replay.set_ns(rec_cl.msgs.0.process_start_ns);
    let (rep_cl, _) = rt_replay.run_one_iteration(|step, msgs| {
      if step == "imu" {
        msgs.0.payload = rec_cl.msgs.0.payload;
        SimOverride::ExecutedBySim
      } else {
        SimOverride::ExecuteByRuntime
      }
    });
    assert_eq!(rep_cl.msgs.1.payload, rec_cl.msgs.1.payload);
  }
  println!("Deterministic replay from KeyFrame #5 verified bit-exact!");
}
❗IMPORTANT

动脑筋:在上面的 run_one_iteration 中,对 slot.msgs 解构时写了 let (ref m0, ref mut m1) = slot.msgs; self.pid.process(m0, m1);。如果直接写 self.pid.process(&slot.msgs.0, &mut slot.msgs.1),Rust 借用检查器允许吗?

动脑筋答案

允许!Rust 编译器支持结构体与元组字段的析构分裂借用(Split Borrowing / Disjoint Capture):编译器能够静态识别 slot.msgs.0 与 slot.msgs.1 是完全不重叠的两个内存字段,因此可以同时持有 .0 的共享引用 &CuMsg<f32> 与 .1 的独占可变引用 &mut CuMsg<f32>。这正是 cu29-derive 生成 CopperList 内联访问代码能够通过借用检查的语言基石!

小结

  • 通过 150 行代码,我们亲手复现了 CopperList 静态槽位复用、Freezable 关键帧恢复与 SimOverride 确定性重放的核心闭环。

💬 关联讨论

加载中...