"""Offline Rust semantic verifier for Chapter 16: Slice (UTF-8 byte slices, borrow guards, array slices)."""
import json
class RustBorrowError(Exception):
pass
class RustSlicePanic(Exception):
pass
class RustString:
"""Models Rust String (UTF-8 bytes + capacity + immutable slice borrow tracking)."""
def __init__(self, text: str) -> None:
self._buf = bytearray(text.encode("utf-8"))
self._capacity = max(len(self._buf), 8)
self._active_shared_borrows = 0
@property
def byte_len(self) -> int:
return len(self._buf)
@property
def capacity(self) -> int:
return self._capacity
def is_char_boundary(self, idx: int) -> bool:
if idx == 0 or idx == len(self._buf):
return True
if idx < 0 or idx > len(self._buf):
return False
# UTF-8 continuation bytes have bit pattern 10xxxxxx (0x80..0xBF)
return (self._buf[idx] & 0xC0) != 0x80
def slice_str(self, start: int | None = None, end: int | None = None) -> tuple[str, int, int]:
s = 0 if start is None else start
e = len(self._buf) if end is None else end
if s < 0 or e < s or e > len(self._buf):
raise RustSlicePanic(f"range {s}..{e} out of bounds for len {len(self._buf)}")
if not self.is_char_boundary(s):
raise RustSlicePanic(f"byte index {s} is not a char boundary")
if not self.is_char_boundary(e):
raise RustSlicePanic(f"byte index {e} is not a char boundary")
self._active_shared_borrows += 1
return self._buf[s:e].decode("utf-8"), s, e - s
def release_borrow(self) -> None:
self._active_shared_borrows = max(0, self._active_shared_borrows - 1)
def push_str(self, suffix: str) -> None:
if self._active_shared_borrows > 0:
raise RustBorrowError("cannot borrow `s` as mutable because it is also borrowed as immutable")
data = suffix.encode("utf-8")
self._buf.extend(data)
if len(self._buf) > self._capacity:
self._capacity = max(self._capacity * 2, len(self._buf))
def as_str(self) -> str:
return self._buf.decode("utf-8")
def run_cases() -> list[dict]:
cases = []
# Case 1: String slice range syntax (x..y, ..y, x.., ..)
s = RustString("broadcast")
p1, p1_off, p1_len = s.slice_str(0, 5)
p2, p2_off, p2_len = s.slice_str(5, 9)
p_prefix, _, _ = s.slice_str(None, 5)
p_suffix, _, _ = s.slice_str(5, None)
p_full, _, _ = s.slice_str(None, None)
actual_1 = {
"formatted": f"{s.as_str()}={p1}+{p2}",
"ranges": [p_prefix, p_suffix, p_full],
"meta": [[p1_off, p1_len], [p2_off, p2_len]],
}
expected_1 = {
"formatted": "broadcast=broad+cast",
"ranges": ["broad", "cast", "broadcast"],
"meta": [[0, 5], [5, 4]],
}
cases.append(dict(
name="string_slice_ranges_and_layout",
summary="Verify half-open byte range x..y, ..y, x.., .. and (offset, len) view metadata",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: UTF-8 char boundary check (valid boundary vs mid-character panic)
utf8_s = RustString("Rust切片")
valid_ascii, _, _ = utf8_s.slice_str(0, 4)
valid_cjk, _, _ = utf8_s.slice_str(4, 10)
boundary_err = ""
try:
utf8_s.slice_str(0, 5)
except RustSlicePanic as exc:
boundary_err = str(exc)
actual_2 = {
"byte_len": utf8_s.byte_len,
"valid_slices": [valid_ascii, valid_cjk],
"mid_char_error": boundary_err,
}
expected_2 = {
"byte_len": 10,
"valid_slices": ["Rust", "切片"],
"mid_char_error": "byte index 5 is not a char boundary",
}
cases.append(dict(
name="utf8_char_boundary_enforcement",
summary="Verify UTF-8 byte-index slicing succeeds on char boundaries and panics inside multi-byte chars",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Borrow conflict when mutating a String with an active &str slice
s_mut = RustString("mbsky")
sl, _, _ = s_mut.slice_str(0, 3)
borrow_conflict = ""
try:
s_mut.push_str("yes!")
except RustBorrowError as exc:
borrow_conflict = str(exc)
s_mut.release_borrow()
s_mut.push_str("_ok")
actual_3 = {
"slice_before_release": sl,
"conflict_detected": "cannot borrow `s` as mutable" in borrow_conflict,
"after_release_push": s_mut.as_str(),
}
expected_3 = {
"slice_before_release": "mbs",
"conflict_detected": True,
"after_release_push": "mbsky_ok",
}
cases.append(dict(
name="slice_immutable_borrow_blocks_mutation",
summary="Verify active &str slice prevents push_str mutation until the borrow scope ends",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
# Case 4: Non-string array slice (&[i32]) and String -> &str conversion
arr = (1, 3, 5, 7, 9)
part = list(arr[0:3])
s_conv = RustString("hello")
as_slice, _, slice_len = s_conv.slice_str(None, None)
actual_4 = {
"array_slice": part,
"string_to_str": as_slice,
"string_has_capacity": s_conv.capacity >= slice_len,
}
expected_4 = {
"array_slice": [1, 3, 5],
"string_to_str": "hello",
"string_has_capacity": True,
}
cases.append(dict(
name="array_slice_and_str_conversion",
summary="Verify &[i32] array slicing [0..3] -> [1, 3, 5] and &s[..] conversion to &str",
expected=expected_4,
actual=actual_4,
passed=actual_4 == expected_4,
))
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-slice-lab/explore-slice.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-slice.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1218.zip