Menu
CoddyTech

将房间对象移植到 Rust

Coddy 面向 Rust 开发者的 Lua 课程的第 48 课,共 48 课。

challenge icon

挑战

中等

移植 Rust 参考实现。第一行输入是非负的房间容量,剩余各行是带符号的整数预订请求。只接受严格大于 0 且符合容量的请求。失败的请求不会改变已使用座位数。返回 remaining:accepted。在 model.lua 中实现 Model.new(capacity) 和 Model:reserve(seats);reserve 返回布尔值。每次运行都使用一个新对象。

编辑 app.lua、model.lua。可见的锁定文件 main.lua 会将 stdin 读入一个行序列,调用 app.run(lines),并输出返回值,末尾带一个换行符。不要输出诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数值输入都足够小,不会溢出。

公共 API 检查:Model.new(capacity) 会公开 capacity 和 used,后者初始为 0。reserve 返回布尔值,并且只会在请求大于 0 且符合容量时更新 used。各个房间互相独立。锁定的驱动程序会在调用 app.run 前检查此行为。成功时,这些检查不会输出任何内容。

Rust 2021 参考实现

use std::io::{self, Read};
struct Room { capacity: i64, used: i64 }
impl Room {
    fn new(capacity: i64) -> Self { Self { capacity, used: 0 } }
    fn reserve(&mut self, seats: i64) -> bool {
        if seats <= 0 || seats > self.capacity - self.used { return false; }
        self.used += seats;
        true
    }
    fn remaining(&self) -> i64 { self.capacity - self.used }
}
fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    let mut values = input.split_whitespace().map(|s| s.parse::<i64>().unwrap());
    let mut room = Room::new(values.next().unwrap());
    let mut accepted = 0;
    for seats in values { if room.reserve(seats) { accepted += 1; } }
    println!("{}:{}", room.remaining(), accepted);
}

在其模块外,Rust 结构体会将字段保持为私有,并公开一个共享借用的观察方法。Lua 合约会向驱动程序检查公开 capacity 和 used,而预订行为保持不变。每个房间都要单独创建;失败的请求必须保持其状态不变。不要使用 Lua 逻辑运算符将布尔值转换为整数。

亲手试试

-- 公共 API 检查
do
local Model=require("model")
local a,b=Model.new(5),Model.new(2)
assert(a:reserve(6)==false and a.used==0,"oversized reservation must not mutate")
assert(a:reserve(0)==false and a:reserve(-1)==false and a.used==0,"nonpositive requests are rejected")
assert(a:reserve(2)==true and a.used==2,"accepted seats update used")
assert(a:reserve(3)==true and a.used==5 and a.capacity==5,"exact fit succeeds without changing capacity")
assert(b.used==0 and b.capacity==2,"rooms must be independent")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))

面向 Rust 开发者的 Lua中的所有课

自己练习: Lua 在线编译器