Skip to main content

aver_rt/
runtime.rs

1use crate::{AverDisplay, AverList, aver_display};
2
3pub fn console_print<T: AverDisplay>(val: &T) {
4    println!("{}", aver_display(val));
5}
6
7pub fn console_error<T: AverDisplay>(val: &T) {
8    eprintln!("{}", aver_display(val));
9}
10
11pub fn console_warn<T: AverDisplay>(val: &T) {
12    eprintln!("[warn] {}", aver_display(val));
13}
14
15pub fn read_line() -> Result<String, String> {
16    let mut buf = String::new();
17    match std::io::stdin().read_line(&mut buf) {
18        Ok(0) => Err("EOF".to_string()),
19        Ok(_) => {
20            if buf.ends_with('\n') {
21                buf.pop();
22                if buf.ends_with('\r') {
23                    buf.pop();
24                }
25            }
26            Ok(buf)
27        }
28        Err(e) => Err(e.to_string()),
29    }
30}
31
32pub fn time_now() -> String {
33    let (secs, nanos) = unix_parts_now();
34    format_utc_rfc3339_like(secs, nanos)
35}
36
37pub fn time_unix_ms() -> i64 {
38    let now = std::time::SystemTime::now()
39        .duration_since(std::time::UNIX_EPOCH)
40        .expect("Time.unixMs: system clock error");
41    i64::try_from(now.as_millis()).expect("Time.unixMs: value out of i64 range")
42}
43
44pub fn time_sleep(ms: i64) {
45    if ms < 0 {
46        panic!("Time.sleep: ms must be non-negative");
47    }
48    // Browsers have no synchronous sleep primitive on
49    // wasm32-unknown-unknown — std::thread::sleep panics with
50    // "can't sleep". Treat it as a no-op there; the playground's
51    // recorder still captures the call + duration in args, and
52    // replay reproduces the trace faithfully. Native builds keep
53    // real blocking sleep.
54    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
55    {
56        let _ = ms;
57        return;
58    }
59    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
60    std::thread::sleep(std::time::Duration::from_millis(ms as u64));
61}
62
63pub fn string_slice(s: &str, from: i64, to: i64) -> String {
64    let start = from.max(0) as usize;
65    let end = to.max(0) as usize;
66    if start >= end {
67        return String::new();
68    }
69
70    let mut start_byte = None;
71    let mut end_byte = None;
72    let mut char_index = 0usize;
73
74    for (byte_index, _) in s.char_indices() {
75        if char_index == start {
76            start_byte = Some(byte_index);
77        }
78        if char_index == end {
79            end_byte = Some(byte_index);
80            break;
81        }
82        char_index += 1;
83    }
84
85    if start_byte.is_none() && char_index == start {
86        start_byte = Some(s.len());
87    }
88    if end_byte.is_none() && char_index == end {
89        end_byte = Some(s.len());
90    }
91
92    let start_byte = start_byte.unwrap_or(s.len());
93    let end_byte = end_byte.unwrap_or(s.len());
94    if start_byte >= end_byte {
95        return String::new();
96    }
97
98    s[start_byte..end_byte].to_string()
99}
100
101pub fn read_text(path: &str) -> Result<String, String> {
102    std::fs::read_to_string(path).map_err(|e| e.to_string())
103}
104
105pub fn write_text(path: &str, content: &str) -> Result<(), String> {
106    std::fs::write(path, content)
107        .map(|_| ())
108        .map_err(|e| e.to_string())
109}
110
111pub fn append_text(path: &str, content: &str) -> Result<(), String> {
112    use std::io::Write;
113
114    let mut file = std::fs::OpenOptions::new()
115        .create(true)
116        .append(true)
117        .open(path)
118        .map_err(|e| e.to_string())?;
119    file.write_all(content.as_bytes())
120        .map_err(|e| e.to_string())
121}
122
123pub fn path_exists(path: &str) -> bool {
124    std::path::Path::new(path).exists()
125}
126
127pub fn delete_file(path: &str) -> Result<(), String> {
128    let p = std::path::Path::new(path);
129    if p.is_dir() {
130        return Err(
131            "Disk.delete: path is a directory — use Disk.deleteDir to remove directories"
132                .to_string(),
133        );
134    }
135    std::fs::remove_file(p)
136        .map(|_| ())
137        .map_err(|e| e.to_string())
138}
139
140pub fn delete_dir(path: &str) -> Result<(), String> {
141    let p = std::path::Path::new(path);
142    if !p.is_dir() {
143        return Err(
144            "Disk.deleteDir: path is not a directory — use Disk.delete to remove files".to_string(),
145        );
146    }
147    std::fs::remove_dir_all(p)
148        .map(|_| ())
149        .map_err(|e| e.to_string())
150}
151
152pub fn list_dir(path: &str) -> Result<AverList<String>, String> {
153    let entries = std::fs::read_dir(path).map_err(|e| e.to_string())?;
154    let mut result = Vec::new();
155    for entry in entries {
156        let entry = entry.map_err(|e| e.to_string())?;
157        result.push(entry.file_name().to_string_lossy().into_owned());
158    }
159    Ok(AverList::from_vec(result))
160}
161
162pub fn make_dir(path: &str) -> Result<(), String> {
163    std::fs::create_dir_all(path)
164        .map(|_| ())
165        .map_err(|e| e.to_string())
166}
167
168pub fn env_get(key: &str) -> Option<String> {
169    std::env::var(key).ok()
170}
171
172pub fn env_set(key: &str, value: &str) -> Result<(), String> {
173    validate_env_key(key)?;
174    if value.contains('\0') {
175        return Err("Env.set: value must not contain NUL".to_string());
176    }
177
178    unsafe {
179        std::env::set_var(key, value);
180    }
181    Ok(())
182}
183
184pub fn cli_args() -> AverList<String> {
185    AverList::from_vec(std::env::args().skip(1).collect())
186}
187
188fn validate_env_key(key: &str) -> Result<(), String> {
189    if key.is_empty() {
190        return Err("Env.set: key must not be empty".to_string());
191    }
192    if key.contains('=') {
193        return Err("Env.set: key must not contain '='".to_string());
194    }
195    if key.contains('\0') {
196        return Err("Env.set: key must not contain NUL".to_string());
197    }
198    Ok(())
199}
200
201fn unix_parts_now() -> (i64, u32) {
202    match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
203        Ok(d) => (
204            i64::try_from(d.as_secs()).expect("Time.now: seconds out of i64 range"),
205            d.subsec_nanos(),
206        ),
207        Err(e) => {
208            let d = e.duration();
209            let secs = i64::try_from(d.as_secs()).expect("Time.now: seconds out of i64 range");
210            let nanos = d.subsec_nanos();
211            if nanos == 0 {
212                (-secs, 0)
213            } else {
214                (-(secs + 1), 1_000_000_000 - nanos)
215            }
216        }
217    }
218}
219
220fn format_utc_rfc3339_like(unix_secs: i64, nanos: u32) -> String {
221    let days = unix_secs.div_euclid(86_400);
222    let sod = unix_secs.rem_euclid(86_400);
223    let hour = sod / 3_600;
224    let minute = (sod % 3_600) / 60;
225    let second = sod % 60;
226    let millis = nanos / 1_000_000;
227    let (year, month, day) = civil_from_days(days);
228    format!(
229        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
230        year, month, day, hour, minute, second, millis
231    )
232}
233
234fn civil_from_days(days_since_epoch: i64) -> (i32, u32, u32) {
235    let z = days_since_epoch + 719_468;
236    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
237    let doe = z - era * 146_097;
238    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
239    let y = yoe + era * 400;
240    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
241    let mp = (5 * doy + 2) / 153;
242    let day = doy - (153 * mp + 2) / 5 + 1;
243    let month = mp + if mp < 10 { 3 } else { -9 };
244    let year = y + if month <= 2 { 1 } else { 0 };
245    (year as i32, month as u32, day as u32)
246}