小さな検証 project

入力値の検証は、最初の失敗を Err として返す関数に分けると扱いやすくなります。呼び出し側は match で検証結果を受け取ります。

TESTstdionormalize_newlines
#entry main
#indent 4
#target std

#import "core/result" as *
#import "std/test" as *
#import "core/math" as *

fn validate_port %fn i32 Result i32 str \port:
    if:
        lt port 1
        then:
            Result::Err "port too small"
        else:
            if:
                lt 65535 port
                then:
                    Result::Err "port too large"
                else:
                    Result::Ok port

fn expect_port %fn i32 fn i32 Result unit str \input\expected:
    match validate_port input:
        Result::Ok port:
            check_eq_i32 expected port
        Result::Err msg:
            Result::Err msg

fn expect_port_error %fn i32 fn str Result unit str \input\expected:
    match validate_port input:
        Result::Ok port:
            Result::Err "expected validation error"
        Result::Err msg:
            check_str_eq expected msg

fn main %impure fn void i32 \void:
    let checks:
        checks_new
        |> checks_push expect_port 8080 8080
        |> checks_push expect_port_error 0 "port too small"
        |> checks_push expect_port_error 70000 "port too large"
    let shown checks_print_report checks
    checks_exit_code shown

validation の段階で理由付きの Err にしておくと、呼び出し元は panic せずに表示、既定値、再入力などを選べます。

On this page