| 1 | import time |
| 2 | |
| 3 | enum StopAfterType { |
| 4 | time |
| 5 | tx |
| 6 | } |
| 7 | |
| 8 | struct StopAfter { |
| 9 | t f64 |
| 10 | stop_after_type StopAfterType |
| 11 | } |
| 12 | |
| 13 | pub fn parse(str string) !StopAfter { |
| 14 | time_format := [str[str.len - 1]].bytestr() |
| 15 | time_string := str[0..str.len - 1] |
| 16 | if time_string == '0' { |
| 17 | return StopAfter{} |
| 18 | } |
| 19 | timef64 := time_string.f64() |
| 20 | if timef64 == 0 { |
| 21 | return error('invalid string "${str}"') |
| 22 | } |
| 23 | |
| 24 | match time_format { |
| 25 | 's' { |
| 26 | return StopAfter{timef64 * time.second, .time} |
| 27 | } |
| 28 | 'm' { |
| 29 | return StopAfter{timef64 * time.minute, .time} |
| 30 | } |
| 31 | 'h' { |
| 32 | return StopAfter{timef64 * time.hour, .time} |
| 33 | } |
| 34 | 'd' { |
| 35 | return StopAfter{timef64 * time.hour * 24, .time} |
| 36 | } |
| 37 | 't' { |
| 38 | return StopAfter{timef64, .tx} |
| 39 | } |
| 40 | else { |
| 41 | return error('no match for "${time_format}" format') |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | fn main() { |
| 47 | assert parse('0s')! == StopAfter{} |
| 48 | assert parse('10s')! == StopAfter{f64(10 * time.second), .time} |
| 49 | assert parse('10m')! == StopAfter{f64(10 * time.minute), .time} |
| 50 | assert parse('10h')! == StopAfter{f64(10 * time.hour), .time} |
| 51 | assert parse('10d')! == StopAfter{f64(10 * time.hour * 24), .time} |
| 52 | assert parse('10t')! == StopAfter{f64(10), .tx} |
| 53 | assert parse('10x') or { err } == StopAfter{} |
| 54 | assert StopAfter{} == parse('10x') or { err } |
| 55 | } |
| 56 | |