(module main)

(fn parse_text ((text string)) -> (result i32 i32)
  (std.string.parse_i32_result text))

(fn parse_stdin_text () -> (result i32 i32)
  (let input (result string i32) (std.io.read_stdin_result))
  (match input
    ((ok text)
      (std.string.parse_i32_result text))
    ((err code)
      (err i32 i32 code))))

(test "parse 42 ok"
  (= (unwrap_ok (parse_text "42")) 42))

(test "parse negative 7 ok"
  (= (unwrap_ok (parse_text "-7")) -7))

(test "parse empty err"
  (= (unwrap_err (parse_text "")) 1))

(test "parse trailing byte err"
  (= (unwrap_err (parse_text "12x")) 1))

(test "parse overflow err"
  (= (unwrap_err (parse_text "2147483648")) 1))

(test "parse stdin text structurally"
  (let value (result i32 i32) (parse_stdin_text))
  (match value
    ((ok parsed)
      (= parsed parsed))
    ((err code)
      (= code 1))))

(fn main () -> i32
  (let value (result i32 i32) (parse_stdin_text))
  (if (is_ok value)
    (unwrap_ok value)
    (unwrap_err value)))
