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

运行离线 Python 校验:Rust Vec<T>、UTF-8 String 边界切片与 HashMap Entry API

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-collection-string.py
explore-collection-string.py154 行
"""Offline Rust semantic verifier for Chapter 24: Collections & String (Vec<T>, UTF-8 String, HashMap<K, V>)."""
import json


def utf8_slice(s: str, start: int, end: int) -> tuple[bool, str]:
    raw = s.encode("utf-8")
    def is_boundary(idx: int) -> bool:
        if idx == 0 or idx == len(raw):
            return True
        return 0 < idx < len(raw) and (raw[idx] & 0xC0) != 0x80

    if not (is_boundary(start) and is_boundary(end)):
        return False, f"byte index {end if not is_boundary(end) else start} is not a char boundary"
    return True, raw[start:end].decode("utf-8")


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

    # Case 1: Vec<T> push, append (drains v2), get -> Option, indexing panic, &mut iteration
    v1 = [1, 2, 4, 8]
    for x in (16, 32, 64):
        v1.append(x)
    v_a = [1, 2, 4, 8]
    v_b = [16, 32, 64]
    v_a.extend(v_b)
    v_b.clear()  # Rust Vec::append moves all elements out of v2, leaving v2 empty

    v_get = [1, 2, 4, 8]
    get_0 = ("Some", v_get[0]) if 0 < len(v_get) else ("None", None)
    get_4 = ("Some", v_get[4]) if 4 < len(v_get) else ("None", None)
    idx_oob_panicked = False
    try:
        _ = v_get[4]
    except IndexError:
        idx_oob_panicked = True

    v_mut = [100, 32, 57]
    for idx in range(len(v_mut)):
        v_mut[idx] += 50

    actual_1 = {
        "after_push": v1,
        "after_append": v_a,
        "source_vec_drained": v_b == [],
        "get_0_and_4": [list(get_0), list(get_4)],
        "index_4_panics": idx_oob_panicked,
        "mut_iter_plus_50": v_mut,
    }
    expected_1 = {
        "after_push": [1, 2, 4, 8, 16, 32, 64],
        "after_append": [1, 2, 4, 8, 16, 32, 64],
        "source_vec_drained": True,
        "get_0_and_4": [["Some", 1], ["None", None]],
        "index_4_panics": True,
        "mut_iter_plus_50": [150, 82, 107],
    }
    cases.append(dict(
        name="vec_push_append_get_and_mut_iter",
        summary="Verify Vec push/append drain, Option-returning get(), OOB index panic, and &mut traversal",
        expected=expected_1,
        actual=actual_1,
        passed=actual_1 == expected_1,
    ))

    # Case 2: String construction, push_str/push, +, format!, UTF-8 byte len vs chars().count() & boundary panic
    s_push = "rust"
    s_push += "_lang"
    s_push += "!"
    s_plus = "Hello, " + "world!"
    s_fmt = f"{'tic'}-{'tac'}-{'toe'}"
    s_mix = "hello你好"
    s_cn = "EN中文"
    chars_list = list("hello中文")
    nth_2 = list(s_cn)[2]
    ok_sub, sub_val = utf8_slice(s_cn, 0, 2)
    bad_sub, bad_err = utf8_slice(s_cn, 0, 3)

    actual_2 = {
        "push_result": s_push,
        "plus_and_format": [s_plus, s_fmt],
        "byte_lens": [len("hello".encode("utf-8")), len("你好".encode("utf-8"))],
        "char_count_mix": len(s_mix),
        "chars_iter": chars_list,
        "nth_2": nth_2,
        "valid_slice_0_2": [ok_sub, sub_val],
        "invalid_slice_0_3": [bad_sub, "not a char boundary" in bad_err],
    }
    expected_2 = {
        "push_result": "rust_lang!",
        "plus_and_format": ["Hello, world!", "tic-tac-toe"],
        "byte_lens": [5, 6],
        "char_count_mix": 7,
        "chars_iter": ["h", "e", "l", "l", "o", "中", "文"],
        "nth_2": "中",
        "valid_slice_0_2": [True, "EN"],
        "invalid_slice_0_3": [False, True],
    }
    cases.append(dict(
        name="string_utf8_len_chars_and_slicing",
        summary="Verify String mutations, UTF-8 byte length (6 for 你好) vs char count (7), nth(2), and char-boundary panic",
        expected=expected_2,
        actual=actual_2,
        passed=actual_2 == expected_2,
    ))

    # Case 3: HashMap insert, get, iter, entry().or_insert(), and get_mut()
    hm: dict[str, str] = {}
    hm["color"] = "red"
    hm["size"] = "10 m^2"
    color_val = hm.get("color")
    pairs = sorted(hm.items())
    # entry("color").or_insert("blue") should NOT overwrite existing "red"
    hm.setdefault("color", "blue")
    hm.setdefault("theme", "sky")

    hm_int: dict[int, str] = {1: "a"}
    if 1 in hm_int:
        hm_int[1] = "b"

    actual_3 = {
        "get_color": color_val,
        "iter_pairs": [list(p) for p in pairs],
        "after_entry_or_insert": {"color": hm["color"], "theme": hm["theme"]},
        "after_get_mut": hm_int[1],
    }
    expected_3 = {
        "get_color": "red",
        "iter_pairs": [["color", "red"], ["size", "10 m^2"]],
        "after_entry_or_insert": {"color": "red", "theme": "sky"},
        "after_get_mut": "b",
    }
    cases.append(dict(
        name="hashmap_insert_entry_and_get_mut",
        summary="Verify HashMap insert/get/iter, non-overwriting entry().or_insert(), and get_mut() update",
        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-collection-string-lab/explore-collection-string.py

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

下载课程关联工程包:Rust

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

下载课程关联工程包:Rust

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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