commit f832858583fc9c23935231421d0ea1aeb5e7ce70 Author: luxick Date: Wed Jul 1 14:12:09 2020 +0200 Init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..adb36c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.exe \ No newline at end of file diff --git a/oi.nimble b/oi.nimble new file mode 100644 index 0000000..490539a --- /dev/null +++ b/oi.nimble @@ -0,0 +1,13 @@ +# Package + +version = "0.1.0" +author = "luxick" +description = "Generic result type for operations that can fail." +license = "GPL-2.0" +srcDir = "src" + + + +# Dependencies + +requires "nim >= 1.2.4" diff --git a/src/oi.nim b/src/oi.nim new file mode 100644 index 0000000..21c67a7 --- /dev/null +++ b/src/oi.nim @@ -0,0 +1,17 @@ +type + Err = string + OI*[T] = object of RootObj + case isOk*: bool + of true: + val*: T + of false: + error*: string + +proc ok*[T](val: T): OI[T] = + OI[T](isOK: true, val: val) + +proc fail*(oi: OI, msg: string): OI = + OI(isOK: false, error: msg) + +proc fail*(msg: string): OI[auto] = + OI[auto](isOK: false, error: msg) diff --git a/tests/config.nims b/tests/config.nims new file mode 100644 index 0000000..3bb69f8 --- /dev/null +++ b/tests/config.nims @@ -0,0 +1 @@ +switch("path", "$projectDir/../src") \ No newline at end of file diff --git a/tests/testResults.nim b/tests/testResults.nim new file mode 100644 index 0000000..3be7ace --- /dev/null +++ b/tests/testResults.nim @@ -0,0 +1,38 @@ +# To run these tests, simply execute `nimble test`. + +import unittest +import oi + +test "Check OK": + let test = ok 1 + check test.isOk == true + +test "Check fail": + let test = fail "no data here" + check test.isOk == false + +test "Check proc results": + proc createValue: OI[string] = + let myString = "This is test code!" + ok myString + let data = createValue() + check data.isOk + check data.val == "This is test code!" + +test "Check failing proc": + proc destinedToFail(): OI[int] = + result.fail "no data found" + + let data = destinedToFail() + check data.isOk == false + check data.error == "no data found" + +test "Check changing result": + proc checker(): OI[int] = + result = ok 42 + # something happend here + result = fail "data got corrupted" + + let data = checker() + check data.isOk == false + check data.error == "data got corrupted" \ No newline at end of file