蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 Python 校验:Rust Box/Rc/Weak 计数析构、RefCell 运行时借用检查与 Mutex/RwLock

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-smart-pointers.py
explore-smart-pointers.py285 行
"""Offline Rust semantic verifier for Chapter 28: Smart Pointers (Box, Rc, Arc, Weak, RefCell, Mutex, RwLock, Drop)."""
import json
import threading
from typing import Any


class BorrowMutPanic(Exception):
    pass


class BoxPtr:
    """Models Box<T>: single heap owner with deterministic Drop."""

    def __init__(self, value: Any, drop_log: list[str] | None = None, label: str = "Box") -> None:
        self.value = value
        self._dropped = False
        self._drop_log = drop_log
        self._label = label

    def drop(self) -> None:
        if not self._dropped:
            self._dropped = True
            if self._drop_log is not None:
                self._drop_log.append(f"drop:{self._label}({self.value})")


class _RcInner:
    def __init__(self, value: Any, drop_log: list[str], label: str) -> None:
        self.value: Any = value
        self.strong = 1
        self.weak = 0
        self.dropped = False
        self.drop_log = drop_log
        self.label = label


class RcPtr:
    """Models Rc<T> with strong_count, weak_count, Rc::clone, Rc::downgrade, and Drop."""

    def __init__(self, inner: _RcInner) -> None:
        self._inner = inner
        self._alive = True

    @classmethod
    def new(cls, value: Any, drop_log: list[str], label: str = "Rc") -> "RcPtr":
        return cls(_RcInner(value, drop_log, label))

    def clone_rc(self) -> "RcPtr":
        assert self._alive
        self._inner.strong += 1
        return RcPtr(self._inner)

    def downgrade(self) -> "WeakPtr":
        assert self._alive
        self._inner.weak += 1
        return WeakPtr(self._inner)

    @property
    def strong_count(self) -> int:
        return self._inner.strong

    @property
    def weak_count(self) -> int:
        return self._inner.weak

    @property
    def value(self) -> Any:
        return self._inner.value

    def drop(self) -> None:
        if self._alive:
            self._alive = False
            self._inner.strong -= 1
            if self._inner.strong == 0 and not self._inner.dropped:
                self._inner.dropped = True
                self._inner.drop_log.append(f"drop:{self._inner.label}({self._inner.value})")
                self._inner.value = None


class WeakPtr:
    def __init__(self, inner: _RcInner) -> None:
        self._inner = inner

    def upgrade(self) -> RcPtr | None:
        if self._inner.strong == 0 or self._inner.dropped:
            return None
        self._inner.strong += 1
        return RcPtr(self._inner)


class RefCell:
    """Models RefCell<T> runtime borrow checker (many readers OR single writer)."""

    def __init__(self, value: Any) -> None:
        self._value = value
        self._shared = 0
        self._mut_active = False

    def borrow(self) -> tuple[Any, callable]:
        if self._mut_active:
            raise BorrowMutPanic("already mutably borrowed: BorrowError")
        self._shared += 1
        def release() -> None:
            self._shared -= 1
        return self._value, release

    def borrow_mut(self) -> tuple[list[Any], callable]:
        if self._mut_active or self._shared > 0:
            raise BorrowMutPanic("already borrowed: BorrowMutError")
        self._mut_active = True
        cell = [self._value]
        def release() -> None:
            self._value = cell[0]
            self._mut_active = False
        return cell, release


class RwLockModel:
    """Models RwLock<T>: allows concurrent read guards, rejects write while readers hold lock."""

    def __init__(self, value: Any) -> None:
        self._value = value
        self._readers = 0
        self._writer = False

    def try_read(self) -> tuple[bool, Any]:
        if self._writer:
            return False, None
        self._readers += 1
        return True, self._value

    def release_read(self) -> None:
        self._readers -= 1

    def try_write(self, new_val: Any) -> bool:
        if self._writer or self._readers > 0:
            return False
        self._writer = True
        self._value = new_val
        self._writer = False
        return True


def run_cases() -> list[dict]:
    cases = []

    # Case 1: Box<T> heap allocation & deterministic Drop + Rc<Data> strong_count == 3 -> 0
    drops: list[str] = []
    b = BoxPtr(5, drops, "Box")
    b_val = b.value
    b.drop()

    rc0 = RcPtr.new({"value": 5}, drops, "Data")
    rc1 = rc0.clone_rc()
    rc2 = rc0.clone_rc()
    count_with_three = rc0.strong_count
    weak = rc0.downgrade()
    count_after_weak = (rc0.strong_count, rc0.weak_count)
    upgraded_before = weak.upgrade() is not None
    rc0.drop()
    rc1.drop()
    rc2.drop()
    # Dropping the temporary upgraded Rc from above? We didn't drop it! Let's upgrade cleanly:
    drops2: list[str] = []
    five = RcPtr.new(5, drops2, "five")
    weak_five = five.downgrade()
    up_ok = weak_five.upgrade()
    assert up_ok is not None
    up_val = up_ok.value
    up_ok.drop()
    five.drop()
    up_after_drop = weak_five.upgrade()

    actual_1 = {
        "box_value": b_val,
        "rc_strong_count_3": count_with_three,
        "weak_does_not_inc_strong": list(count_after_weak),
        "weak_upgrade_before_drop": up_val,
        "weak_upgrade_after_drop_is_none": up_after_drop is None,
        "five_dropped_cleanly": drops2,
    }
    expected_1 = {
        "box_value": 5,
        "rc_strong_count_3": 3,
        "weak_does_not_inc_strong": [3, 1],
        "weak_upgrade_before_drop": 5,
        "weak_upgrade_after_drop_is_none": True,
        "five_dropped_cleanly": ["drop:five(5)"],
    }
    cases.append(dict(
        name="box_rc_weak_and_drop_lifecycle",
        summary="Verify Box::new(5), Rc::strong_count == 3, Weak downgrade/upgrade, and automatic Drop at count 0",
        expected=expected_1,
        actual=actual_1,
        passed=actual_1 == expected_1,
    ))

    # Case 2: RefCell<T> runtime interior mutability & conflicting borrow_mut panic
    cell = RefCell(5)
    guard, rel_mut = cell.borrow_mut()
    guard[0] = 10
    conflict_caught = False
    try:
        cell.borrow_mut()
    except BorrowMutPanic:
        conflict_caught = True
    rel_mut()
    val_after, rel_read = cell.borrow()
    rel_read()
    actual_2 = {
        "mutated_value": val_after,
        "double_borrow_mut_panicked": conflict_caught,
    }
    expected_2 = {
        "mutated_value": 10,
        "double_borrow_mut_panicked": True,
    }
    cases.append(dict(
        name="refcell_runtime_borrow_check",
        summary="Verify RefCell::borrow_mut mutates 5 -> 10 and panics on overlapping mutable borrow",
        expected=expected_2,
        actual=actual_2,
        passed=actual_2 == expected_2,
    ))

    # Case 3: Arc<Mutex<T>> thread-safe sharing + RwLock multi-reader / exclusive-writer rules
    mu = threading.Lock()
    shared = [5]

    def add_one() -> None:
        with mu:
            shared[0] += 1

    threads = [threading.Thread(target=add_one) for _ in range(5)]
    for th in threads:
        th.start()
    for th in threads:
        th.join()

    rw = RwLockModel(5)
    r1_ok, r1_val = rw.try_read()
    r2_ok, r2_val = rw.try_read()
    write_blocked_during_reads = not rw.try_write(99)
    rw.release_read()
    rw.release_read()
    write_ok_after_reads = rw.try_write(99)
    _, final_rw_val = rw.try_read()
    rw.release_read()

    actual_3 = {
        "arc_mutex_final": shared[0],
        "rwlock_two_concurrent_readers": [r1_ok, r2_ok, r1_val, r2_val],
        "rwlock_write_blocked_with_readers": write_blocked_during_reads,
        "rwlock_write_succeeded_after_release": write_ok_after_reads,
        "rwlock_final_value": final_rw_val,
    }
    expected_3 = {
        "arc_mutex_final": 10,
        "rwlock_two_concurrent_readers": [True, True, 5, 5],
        "rwlock_write_blocked_with_readers": True,
        "rwlock_write_succeeded_after_release": True,
        "rwlock_final_value": 99,
    }
    cases.append(dict(
        name="arc_mutex_and_rwlock_concurrency",
        summary="Verify Arc+Mutex 5-thread update (5 -> 10) and RwLock concurrent readers / exclusive writer",
        expected=expected_3,
        actual=actual_3,
        passed=actual_3 == expected_3,
    ))

    return cases


def main() -> None:
    payload = {
        "version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
        "cases": run_cases(),
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/rust-smart-pointers-lab/explore-smart-pointers.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-smart-pointers.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Rust

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip

下载课程关联工程包:Rust

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1219.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习