Skip to main content

wackasm_opencomputers/
computer.rs

1//! This computer: its address, uptime, memory, beeps, and power.
2//! (The `computer` component itself is [`crate::components::Computer`].)
3
4use std::time::Duration;
5
6use crate::{component::Address, sys};
7
8/// This computer's component address.
9pub fn address() -> Address {
10    let mut buf = [0u8; 64];
11    let len = unsafe { sys::address(buf.as_mut_ptr(), buf.len()) }.max(0) as usize;
12    Address(String::from_utf8_lossy(&buf[..len.min(buf.len())]).into_owned())
13}
14
15/// The filesystem `std::fs` uses: the disk this program sees as `/`.
16/// `None` if the computer has no filesystem. On first use the architecture
17/// picks the boot disk if it is writable, else the first writable disk, else
18/// a read-only one; child processes share their parent's.
19pub fn files_disk() -> Option<Address> {
20    let status = unsafe { sys::files_disk() };
21    (status == sys::STATUS_OK).then(|| Address(String::from_utf8_lossy(&sys::response()).into_owned()))
22}
23
24/// Time since the computer started, in game time. It survives world saves.
25pub fn uptime() -> Duration {
26    Duration::from_millis(unsafe { sys::uptime_ms() }.max(0) as u64)
27}
28
29/// Bytes of RAM this program may use (installed RAM, minus what the other
30/// programs on this computer hold).
31pub fn memory_limit() -> u64 {
32    unsafe { sys::memory_limit() }.max(0) as u64
33}
34
35/// Beeps at `frequency` Hz (20 to 2000) for `duration`.
36pub fn beep(frequency: u32, duration: Duration) {
37    let ms = duration.as_millis().min(i32::MAX as u128) as i32;
38    unsafe { sys::beep(frequency.min(i32::MAX as u32) as i32, ms) };
39}
40
41pub fn shutdown() -> ! {
42    unsafe { sys::shutdown(0) }
43}
44
45pub fn reboot() -> ! {
46    unsafe { sys::shutdown(1) }
47}
48
49/// Stops the computer with an error, shown in its GUI like a Lua crash.
50pub fn crash(message: &str) -> ! {
51    unsafe { sys::crash(message.as_ptr(), message.len()) }
52}
53
54/// Appends a line to this computer's server-side log (`<world>/wackasm/logs`).
55pub fn log(message: &str) {
56    unsafe { sys::log(message.as_ptr(), message.len()) }
57}