Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
"""同步共享文件流:一次读取、校验全部字节、关闭后验证别名结束。"""
import file_reference
def source(language):
if language == 'dever':
return '''setting input: Text
loop checksum(bytes: Bytes) (out: Int)
| each byte in bytes | result |
| out | sum byte |
rule sumChunk(event: dever.io.ReadEvent) (out: Int)
| event | out |
| Chunk(bytes) | checksum(bytes) |
| Failed(message) | fail(dever.io.ReadEvent.Failed(message)) |
loop total(events: Stream<dever.io.ReadEvent>) (sum: Int, count: Int)
| each event in events | result |
| sum | sum sumChunk(event) |
| count | count |
flow measure(n: Int) (out: Int)
| step | kind | do |
| file | flow | dever.io.open(input) |
| events | flow | dever.io.chunks(file, 64) |
| result | loop | total(events) |
| - | check | result.count == n else Invalid |
| remaining | loop | total(events) |
| - | check | remaining.count == 0 else Invalid |
| - | flow | dever.io.close(file) |
| out | calc | result.sum |
cmd bench = measure
'''
if language == 'rust':
prefix = file_reference.source('rust').split('fn main()')[0].replace('struct File(', '#[derive(Clone)]\nstruct File(')
prefix = prefix.replace('limit: i64', 'limit: usize').replace(""" let limit = usize::try_from(limit).ok().filter(|n| *n > 0)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "read limit must be positive"))?;
""", '')
return prefix + '''struct Stream { source: Arc<Mutex<Option<File>>>, limit: usize }
impl Stream {
fn new(file: &File, limit: i64) -> io::Result<Self> {
let limit = usize::try_from(limit).ok().filter(|n| *n > 0).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "read limit must be positive"))?;
if file.0.lock().unwrap().is_none() { return Err(closed()); }
Ok(Self { source: Arc::new(Mutex::new(Some(file.clone()))), limit })
}
fn next(&self) -> Option<io::Result<Bytes>> {
let mut source = self.source.lock().unwrap();
match source.as_ref()?.read(self.limit) {
Ok(Some(bytes)) => Some(Ok(bytes)),
Ok(None) => { source.take(); None },
Err(error) => { source.take(); Some(Err(error)) },
}
}
fn close(&self) { self.source.lock().unwrap().take(); }
}
struct Consume<'a>(&'a Stream);
impl Drop for Consume<'_> { fn drop(&mut self) { self.0.close(); } }
fn main() {
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
let config = fs::read_to_string(std::env::args().nth(2).unwrap()).unwrap();
let root: Root = serde_json::from_str(&config).unwrap();
let file = File(Arc::new(Mutex::new(Some(fs::File::open(root.module.main.main.input).unwrap()))));
let stream = Stream::new(&file, 64).unwrap();
let out = {
let _close = Consume(&stream);
let mut out = 0i64;
let mut count = 0i64;
while let Some(bytes) = stream.next() {
let bytes = bytes.unwrap();
let mut sum = 0i64;
for byte in bytes { sum = sum.checked_add(i64::from(byte)).unwrap(); }
out = out.checked_add(sum).unwrap();
count = count.checked_add(1).unwrap();
}
assert_eq!(count, n);
out
};
assert!(stream.next().is_none());
file.close().unwrap();
println!("{out}");
}
'''
return '''package main
import ("encoding/json"; "fmt"; "io"; "os"; "strconv"; "sync")
type File struct { mu sync.Mutex; file *os.File }
func (file *File) read(limit int) []byte {
file.mu.Lock(); defer file.mu.Unlock()
if file.file == nil { panic("file is closed") }
bytes := make([]byte, limit); n, err := file.file.Read(bytes)
if err != nil && err != io.EOF { panic(err) }; return bytes[:n]
}
type Stream struct { mu sync.Mutex; file *File; limit int }
func (stream *Stream) next() []byte {
stream.mu.Lock(); defer stream.mu.Unlock()
if stream.file == nil { return nil }
bytes := stream.file.read(stream.limit)
if len(bytes) == 0 { stream.file = nil }; return bytes
}
func (stream *Stream) close() { stream.mu.Lock(); stream.file = nil; stream.mu.Unlock() }
func total(stream *Stream, n int64) int64 {
defer stream.close(); out, count := int64(0), int64(0)
for bytes := stream.next(); len(bytes) > 0; bytes = stream.next() {
sum := int64(0)
for _, value := range bytes { next := sum + int64(value); if next < sum { panic("overflow") }; sum = next }
next := out + sum; if next < out { panic("overflow") }; out = next; count++
}
if count != n { panic("chunk count") }; return out
}
func main() {
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
input, err := os.Open(os.Args[2]); if err != nil { panic(err) }
var config struct { Module struct { Main struct { Main struct { Input string } } } }
decoder := json.NewDecoder(input); decoder.DisallowUnknownFields()
if err := decoder.Decode(&config); err != nil { panic(err) }; input.Close()
opened, err := os.Open(config.Module.Main.Main.Input); if err != nil { panic(err) }
file := File{file: opened}; stream := Stream{file: &file, limit: 64}
out := total(&stream, n); if len(stream.next()) != 0 { panic("closed alias") }
if err := opened.Close(); err != nil { panic(err) }; file.file = nil
fmt.Println(out)
}
'''