Files
2026-11-27 06:03:56 +00:00

81 lines
2.6 KiB
Python

"""Bytes 的真实转换、共享切片与完整内容校验;Rust 对端不依赖 Dever runtime。"""
def source(language):
if language == 'dever':
return '''loop values(n: Int) (out: List<Int>)
| each value in range(0, n) | result |
| out | list value % 256 |
loop total(data: Bytes) (out: Int)
| each byte in data | result |
| out | sum byte |
measure(n: Int) (out: Int) {
data = dever.bytes.fromInts(values(n))
out = total(dever.bytes.slice(data, 1, n))
}
cmd bench = app.measure
'''
if language == 'rust':
return '''use bytes::Bytes;
fn from_ints(values: &[i64]) -> Result<Bytes, &'static str> {
let mut bytes = Vec::with_capacity(values.len());
for value in values { bytes.push(u8::try_from(*value).map_err(|_| "invalid byte")?); }
Ok(bytes.into())
}
fn slice(bytes: &Bytes, start: i64, end: i64) -> Result<Bytes, &'static str> {
let start = usize::try_from(start).map_err(|_| "invalid range")?;
let end = usize::try_from(end).map_err(|_| "invalid range")?;
bytes.get(start..end).map(|range| bytes.slice_ref(range)).ok_or("invalid range")
}
fn values(n: i64) -> Vec<i64> {
let mut values = Vec::with_capacity(n as usize);
for value in 0..n { values.push(value.checked_rem(256).expect("remainder")); }
values
}
fn total(bytes: &[u8]) -> i64 {
let mut total = 0i64;
for byte in bytes { total = total.checked_add(i64::from(*byte)).expect("sum overflow"); }
total
}
fn main() {
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
let data = from_ints(&values(n)).unwrap();
println!("{}", total(&slice(&data, 1, n).unwrap()));
}
'''
return '''package main
import ("fmt"; "os"; "strconv")
func values(n int64) []int64 {
values := make([]int64, 0, n)
for value := int64(0); value < n; value++ { values = append(values, value % 256) }
return values
}
func fromInts(values []int64) []byte {
bytes := make([]byte, 0, len(values))
for _, value := range values {
if value < 0 || value > 255 { panic("invalid byte") }
bytes = append(bytes, byte(value))
}
return bytes
}
func slice(bytes []byte, start, end int64) []byte {
if start < 0 || end < start || end > int64(len(bytes)) { panic("invalid range") }
return bytes[start:end]
}
func total(bytes []byte) int64 {
total := int64(0)
for _, value := range bytes {
sum := total + int64(value)
if sum < total { panic("sum overflow") }
total = sum
}
return total
}
func main() {
n, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil { panic(err) }
data := fromInts(values(n))
fmt.Println(total(slice(data, 1, n)))
}
'''