ruchy 4.2.0

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! `Time` Operations Module (ruchy/std/time)
//!
//! Thin wrappers around Rust's `std::time` for time measurement and duration operations.
//!
//! **Design**: Thin wrappers (complexity ≤2 per function) around `std::time`.
//! **Quality**: 100% unit test coverage, property tests, ≥75% mutation coverage.

use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// Get current system time in milliseconds since Unix epoch
///
/// # Examples
///
/// ```
/// use ruchy::stdlib::time;
///
/// let timestamp = time::now().expect("operation should succeed in test");
/// assert!(timestamp > 0);
/// ```
///
/// # Errors
///
/// Returns error if system time is before Unix epoch (should never happen)
pub fn now() -> Result<u128, String> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis())
        .map_err(|e| e.to_string())
}

/// Calculate elapsed milliseconds since start time
///
/// # Examples
///
/// ```
/// use ruchy::stdlib::time;
///
/// let start = time::now().expect("operation should succeed in test");
/// // ... do work ...
/// let elapsed = time::elapsed_millis(start).expect("operation should succeed in test");
/// assert!(elapsed >= 0);
/// ```
///
/// # Errors
///
/// Returns error if current time cannot be retrieved
pub fn elapsed_millis(start: u128) -> Result<u128, String> {
    let current = now()?;
    Ok(current.saturating_sub(start))
}

/// Sleep for specified milliseconds
///
/// # Examples
///
/// ```
/// use ruchy::stdlib::time;
///
/// time::sleep_millis(100).expect("operation should succeed in test");  // Sleep for 100ms
/// ```
pub fn sleep_millis(millis: u64) -> Result<(), String> {
    thread::sleep(Duration::from_millis(millis));
    Ok(())
}

/// Convert milliseconds to seconds
///
/// # Examples
///
/// ```
/// use ruchy::stdlib::time;
///
/// let secs = time::duration_secs(1500).expect("operation should succeed in test");
/// assert!((secs - 1.5).abs() < 0.01);  // ~1.5 seconds
/// ```
pub fn duration_secs(millis: u128) -> Result<f64, String> {
    Ok(millis as f64 / 1000.0)
}

/// Format duration as human-readable string
///
/// # Examples
///
/// ```
/// use ruchy::stdlib::time;
///
/// let formatted = time::format_duration(90500).expect("operation should succeed in test");
/// assert_eq!(formatted, "1m 30s");
/// ```
pub fn format_duration(millis: u128) -> Result<String, String> {
    if millis < 1000 {
        return Ok(format!("{millis}ms"));
    }

    let mut remaining = millis;
    let days = remaining / (24 * 60 * 60 * 1000);
    remaining %= 24 * 60 * 60 * 1000;

    let hours = remaining / (60 * 60 * 1000);
    remaining %= 60 * 60 * 1000;

    let minutes = remaining / (60 * 1000);
    remaining %= 60 * 1000;

    let seconds = remaining / 1000;

    let mut parts = Vec::new();
    if days > 0 {
        parts.push(format!("{days}d"));
    }
    if hours > 0 {
        parts.push(format!("{hours}h"));
    }
    if minutes > 0 {
        parts.push(format!("{minutes}m"));
    }
    if seconds > 0 {
        parts.push(format!("{seconds}s"));
    }

    Ok(parts.join(" "))
}

/// Parse human-readable duration string to milliseconds
///
/// # Examples
///
/// ```
/// use ruchy::stdlib::time;
///
/// let millis = time::parse_duration("1h 30m").expect("operation should succeed in test");
/// assert_eq!(millis, 5_400_000);
/// ```
///
/// # Errors
///
/// Returns error if format is invalid
pub fn parse_duration(duration_str: &str) -> Result<u128, String> {
    let mut total_millis: u128 = 0;

    for part in duration_str.split_whitespace() {
        if part.ends_with("ms") {
            let value = part
                .trim_end_matches("ms")
                .parse::<u128>()
                .map_err(|e| e.to_string())?;
            total_millis += value;
        } else if part.ends_with('s') {
            let value = part
                .trim_end_matches('s')
                .parse::<u128>()
                .map_err(|e| e.to_string())?;
            total_millis += value * 1000;
        } else if part.ends_with('m') {
            let value = part
                .trim_end_matches('m')
                .parse::<u128>()
                .map_err(|e| e.to_string())?;
            total_millis += value * 60 * 1000;
        } else if part.ends_with('h') {
            let value = part
                .trim_end_matches('h')
                .parse::<u128>()
                .map_err(|e| e.to_string())?;
            total_millis += value * 60 * 60 * 1000;
        } else if part.ends_with('d') {
            let value = part
                .trim_end_matches('d')
                .parse::<u128>()
                .map_err(|e| e.to_string())?;
            total_millis += value * 24 * 60 * 60 * 1000;
        } else {
            return Err(format!("Invalid duration format: {part}"));
        }
    }

    if total_millis == 0 {
        return Err("Invalid duration: must have at least one component".to_string());
    }

    Ok(total_millis)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_now_positive() {
        let timestamp = now().expect("operation should succeed in test");
        assert!(timestamp > 0);
        assert!(timestamp > 946_684_800_000); // After year 2000
    }

    #[test]
    fn test_elapsed_millis_basic() {
        let start = now().expect("operation should succeed in test");
        std::thread::sleep(std::time::Duration::from_millis(10));
        let elapsed = elapsed_millis(start).expect("operation should succeed in test");
        assert!(elapsed >= 10);
    }

    #[test]
    fn test_sleep_millis() {
        let result = sleep_millis(1);
        assert!(result.is_ok());
    }

    #[test]
    fn test_duration_secs_conversion() {
        assert_eq!(
            duration_secs(1000).expect("operation should succeed in test"),
            1.0
        );
        assert!(
            (duration_secs(1500).expect("operation should succeed in test") - 1.5).abs() < 0.01
        );
    }

    #[test]
    fn test_format_duration_ms() {
        assert_eq!(
            format_duration(0).expect("operation should succeed in test"),
            "0ms"
        );
        assert_eq!(
            format_duration(500).expect("operation should succeed in test"),
            "500ms"
        );
    }

    #[test]
    fn test_format_duration_seconds() {
        assert_eq!(
            format_duration(1000).expect("operation should succeed in test"),
            "1s"
        );
        assert_eq!(
            format_duration(5000).expect("operation should succeed in test"),
            "5s"
        );
    }

    #[test]
    fn test_format_duration_minutes() {
        assert_eq!(
            format_duration(60_000).expect("operation should succeed in test"),
            "1m"
        );
        assert_eq!(
            format_duration(90_000).expect("operation should succeed in test"),
            "1m 30s"
        );
    }

    #[test]
    fn test_format_duration_hours() {
        assert_eq!(
            format_duration(3_600_000).expect("operation should succeed in test"),
            "1h"
        );
        assert_eq!(
            format_duration(5_400_000).expect("operation should succeed in test"),
            "1h 30m"
        );
    }

    #[test]
    fn test_format_duration_days() {
        assert_eq!(
            format_duration(86_400_000).expect("operation should succeed in test"),
            "1d"
        );
        assert_eq!(
            format_duration(90_000_000).expect("operation should succeed in test"),
            "1d 1h"
        );
    }

    #[test]
    fn test_parse_duration_simple() {
        assert_eq!(
            parse_duration("500ms").expect("operation should succeed in test"),
            500
        );
        assert_eq!(
            parse_duration("1s").expect("operation should succeed in test"),
            1_000
        );
        assert_eq!(
            parse_duration("1m").expect("operation should succeed in test"),
            60_000
        );
        assert_eq!(
            parse_duration("1h").expect("operation should succeed in test"),
            3_600_000
        );
        assert_eq!(
            parse_duration("1d").expect("operation should succeed in test"),
            86_400_000
        );
    }

    #[test]
    fn test_parse_duration_compound() {
        assert_eq!(
            parse_duration("1h 30m").expect("operation should succeed in test"),
            5_400_000
        );
        assert_eq!(
            parse_duration("1d 2h").expect("operation should succeed in test"),
            93_600_000
        );
    }

    #[test]
    fn test_parse_duration_invalid() {
        assert!(parse_duration("invalid").is_err());
        assert!(parse_duration("10x").is_err());
        assert!(parse_duration("").is_err());
        assert!(parse_duration("0s").is_err()); // Zero not allowed
    }

    #[test]
    fn test_format_parse_roundtrip() {
        for millis in [1000, 60_000, 90_000, 3_600_000, 86_400_000] {
            let formatted = format_duration(millis).expect("operation should succeed in test");
            let parsed = parse_duration(&formatted).expect("operation should succeed in test");
            assert_eq!(parsed, millis);
        }
    }

    // ===== EXTREME TDD Round 156 - Additional Time Tests =====

    #[test]
    fn test_now_increases() {
        let t1 = now().expect("operation should succeed in test");
        std::thread::sleep(std::time::Duration::from_millis(1));
        let t2 = now().expect("operation should succeed in test");
        assert!(t2 >= t1);
    }

    #[test]
    fn test_elapsed_millis_zero() {
        let start = now().expect("operation should succeed in test");
        let elapsed = elapsed_millis(start).expect("operation should succeed in test");
        // Should be zero or very small
        assert!(elapsed < 100);
    }

    #[test]
    fn test_elapsed_millis_future() {
        // Start time in the "future" (larger than current time)
        let current = now().expect("operation should succeed in test");
        let elapsed =
            elapsed_millis(current + 1_000_000).expect("operation should succeed in test");
        // Should saturate to 0
        assert_eq!(elapsed, 0);
    }

    #[test]
    fn test_sleep_millis_zero() {
        // Zero sleep should succeed immediately
        assert!(sleep_millis(0).is_ok());
    }

    #[test]
    fn test_duration_secs_zero() {
        assert_eq!(
            duration_secs(0).expect("operation should succeed in test"),
            0.0
        );
    }

    #[test]
    fn test_duration_secs_large() {
        let secs = duration_secs(86_400_000).expect("operation should succeed in test");
        assert!((secs - 86_400.0).abs() < 0.01);
    }

    #[test]
    fn test_format_duration_complex() {
        // 1 day, 2 hours, 30 minutes, 45 seconds
        let millis = 86_400_000 + 2 * 3_600_000 + 30 * 60_000 + 45 * 1_000;
        let formatted = format_duration(millis).expect("operation should succeed in test");
        assert!(formatted.contains("1d"));
        assert!(formatted.contains("2h"));
        assert!(formatted.contains("30m"));
        assert!(formatted.contains("45s"));
    }

    #[test]
    fn test_format_duration_only_days() {
        let formatted = format_duration(172_800_000).expect("operation should succeed in test");
        assert_eq!(formatted, "2d");
    }

    #[test]
    fn test_format_duration_999ms() {
        let formatted = format_duration(999).expect("operation should succeed in test");
        assert_eq!(formatted, "999ms");
    }

    #[test]
    fn test_parse_duration_with_spaces() {
        let parsed = parse_duration("1h  30m").expect("operation should succeed in test");
        // Multiple spaces between components
        assert_eq!(parsed, 5_400_000);
    }

    #[test]
    fn test_parse_duration_only_days() {
        assert_eq!(
            parse_duration("2d").expect("operation should succeed in test"),
            172_800_000
        );
    }

    #[test]
    fn test_parse_duration_large_values() {
        let parsed = parse_duration("365d").expect("operation should succeed in test");
        assert_eq!(parsed, 365 * 86_400_000);
    }

    #[test]
    fn test_parse_duration_all_components() {
        let parsed = parse_duration("1d 2h 3m 4s 5ms").expect("operation should succeed in test");
        let expected = 86_400_000 + 2 * 3_600_000 + 3 * 60_000 + 4 * 1_000 + 5;
        assert_eq!(parsed, expected);
    }

    #[test]
    fn test_parse_duration_invalid_number() {
        assert!(parse_duration("xyzs").is_err());
        assert!(parse_duration("-1s").is_err()); // Negative values
    }

    #[test]
    fn test_parse_duration_missing_unit() {
        assert!(parse_duration("100").is_err());
    }

    #[test]
    fn test_elapsed_millis_accuracy() {
        let start = now().expect("operation should succeed in test");
        std::thread::sleep(std::time::Duration::from_millis(50));
        let elapsed = elapsed_millis(start).expect("operation should succeed in test");
        // Should be at least 50ms (allowing some variance)
        assert!(elapsed >= 45); // Allow 5ms variance for system scheduling
    }
}